@adhdev/daemon-standalone 0.8.97 → 0.8.99
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +269 -50
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-OS2tw3XG.js +77 -0
- package/public/assets/{terminal-2SYILvaH.js → terminal-Dawba88C.js} +17 -15
- package/public/index.html +1 -1
- package/vendor/session-host-daemon/index.js +4 -4
- package/vendor/session-host-daemon/index.js.map +1 -1
- package/vendor/session-host-daemon/index.mjs +13 -6
- package/vendor/session-host-daemon/index.mjs.map +1 -1
- package/public/assets/index-BAKxsqur.js +0 -79
|
@@ -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 cd=Object.defineProperty;var ld=(e,s,r)=>s in e?cd(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Ye=(e,s,r)=>ld(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as Ca,a as Ia,b as _i,c as Pi,u as Ws,R as lt,d as ir,t as dd,e as ud,D as md,f as oa,g as ia,h as Aa,i as pd,k as fd,B as hd,l as xd,m as is,N as ca,n as bd}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 gd(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 Ps=gd();function No(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 yd(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function la(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?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 er(e,s){const r=yd(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:la(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 Co(e,s){if(!(s!=null&&s.length))return e;if(!(e!=null&&e.length))return s;const r=new Map(e.map(n=>[n.id,n]));return s.map(n=>{const a=r.get(n.id);return a?er(n,a):n})}const Di=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}),Ei=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Io(e){var r,n;let s=0;return e.activeChat!==void 0&&(s+=4),(r=e.childSessions)!=null&&r.length&&(s+=2),e.workspace&&(s+=1),e.machine&&(s+=1),(n=e.agents)!=null&&n.length&&(s+=1),s}function Mn(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 tn(e){return Array.isArray(e)?e.map(tn):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,tn(r)]))}function vd(e,s){try{return JSON.stringify(tn(e))===JSON.stringify(tn(s))}catch{return!1}}function Nr(e,s,r){return vd(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function wd(e,s,r){var f,d,b,v,w,A,m;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(p=>({...p,_lastUpdate:n}));const i=new Map;for(const p of s)i.set(p.id,p);for(const p of e){const x=i.get(p.id);if(!x){i.set(p.id,{...p,_lastUpdate:n});continue}const h=Io(p),S=Io(x);if(h>S){const _=(f=p.chats)!=null&&f.length?p.chats:x.chats,j=Co(x.childSessions,p.childSessions),C=la(p.activeChat,x.activeChat),k=Mn(x,p,{...x,...p,chats:_,childSessions:j,activeChat:C,_lastUpdate:n});i.set(p.id,Nr(x,k,n))}else if(h<S){const _={};if(p.status&&p.status!==x.status&&(_.status=p.status),p.cdpConnected!==void 0&&(_.cdpConnected=p.cdpConnected),(d=p.chats)!=null&&d.length&&!((b=x.chats)!=null&&b.length)&&(_.chats=p.chats),p.title!==void 0&&(_.title=p.title),p.workspace!==void 0&&(_.workspace=p.workspace),p.providerSessionId!==void 0&&(_.providerSessionId=p.providerSessionId),p.parentSessionId!==void 0&&(_.parentSessionId=p.parentSessionId),p.sessionKind!==void 0&&(_.sessionKind=p.sessionKind),p.sessionCapabilities!==void 0&&(_.sessionCapabilities=p.sessionCapabilities),p.controlValues!==void 0&&(_.controlValues=p.controlValues),p.providerControls!==void 0&&(_.providerControls=p.providerControls),p.summaryMetadata!==void 0&&(_.summaryMetadata=p.summaryMetadata),p.lastMessagePreview!==void 0&&(_.lastMessagePreview=p.lastMessagePreview),p.lastMessageRole!==void 0&&(_.lastMessageRole=p.lastMessageRole),p.lastMessageAt!==void 0&&(_.lastMessageAt=p.lastMessageAt),p.lastMessageHash!==void 0&&(_.lastMessageHash=p.lastMessageHash),p.lastUpdated!==void 0&&(_.lastUpdated=p.lastUpdated),p.unread!==void 0&&(_.unread=p.unread),p.lastSeenAt!==void 0&&(_.lastSeenAt=p.lastSeenAt),p.inboxBucket!==void 0&&(_.inboxBucket=p.inboxBucket),p.completionMarker!==void 0&&(_.completionMarker=p.completionMarker),p.seenCompletionMarker!==void 0&&(_.seenCompletionMarker=p.seenCompletionMarker),p.surfaceHidden!==void 0&&(_.surfaceHidden=p.surfaceHidden),p.runtimeKey!==void 0&&(_.runtimeKey=p.runtimeKey),p.runtimeDisplayName!==void 0&&(_.runtimeDisplayName=p.runtimeDisplayName),p.runtimeWorkspaceLabel!==void 0&&(_.runtimeWorkspaceLabel=p.runtimeWorkspaceLabel),p.runtimeWriteOwner!==void 0&&(_.runtimeWriteOwner=p.runtimeWriteOwner),p.runtimeAttachedClients!==void 0&&(_.runtimeAttachedClients=p.runtimeAttachedClients),p.machineNickname!==void 0&&p.machineNickname!==x.machineNickname&&(_.machineNickname=p.machineNickname),p.version!==void 0&&(_.version=p.version),p.serverVersion!==void 0&&(_.serverVersion=p.serverVersion),p.versionMismatch===!0&&(_.versionMismatch=!0),Object.keys(_).length>0){const j=Mn(x,p,{...x,..._,_lastUpdate:n});i.set(p.id,Nr(x,j,n))}else Nr(x,{...x,_lastUpdate:n},n)}else{const _=p.timestamp||n,j=x._lastUpdate||x.timestamp||0;if(_>=j){const C=(v=p.chats)!=null&&v.length?p.chats:x.chats,k=Co(x.childSessions,p.childSessions),y=la(p.activeChat,x.activeChat),g=Mn(x,p,{...x,...p,chats:C,childSessions:k,activeChat:y,_lastUpdate:n});i.set(p.id,Nr(x,g,n))}else(w=p.chats)!=null&&w.length&&!((A=x.chats)!=null&&A.length)&&i.set(p.id,{...x,chats:p.chats})}}const c=new Set(e.map(p=>p.id)),l=new Set,u=new Set;for(const p of e){const x=p.daemonId||((m=p.id)==null?void 0:m.split(":")[0]);x&&l.add(x),x&&p.type!=="adhdev-daemon"&&u.add(x)}for(const[p,x]of i){const h=x.daemonId||p.split(":")[0];if(!l.has(h))continue;if(a.has(h)&&!c.has(p)){i.delete(p);continue}const S=n-(x._lastUpdate||x.timestamp||0);(x.transport==="pty"&&u.has(h)&&!c.has(p)&&S>1e4||x.transport==="acp"&&u.has(h)&&!c.has(p)&&S>1e4||x.transport==="cdp-page"&&u.has(h)&&!c.has(p)&&S>3e4)&&i.delete(p)}for(const[p,x]of i){const h=x.daemonId||p.split(":")[0];if(l.has(h)&&x.transport&&!u.has(h))continue;n-(x._lastUpdate||x.timestamp||0)>3e5&&x.status!=="online"&&i.delete(p)}return Array.from(i.values())}function jd(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 kd({children:e,connectionOverrides:s}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,f]=o.useState(void 0),d=o.useRef(r);o.useEffect(()=>{d.current=r},[r]);const b=o.useCallback((x,h)=>{n(S=>{let _=!1;const j=S.map(C=>C.id!==x||C.chats===h?C:(_=!0,{...C,chats:h}));return _?j:S})},[]),v=o.useCallback((x,h)=>{n(S=>{const _=S.length===0?x:wd(x,S,h),j=!jd(S,_);return j&&Ps.record({kind:"dashboard.entries_applied",payload:{incoming:No(x),next:No(_)}}),j?_:S})},[]),w=o.useCallback(()=>i(!0),[]),A=o.useMemo(()=>({injectEntries:v,markLoaded:w,getIdes:()=>d.current}),[v,w]),m=s,p=o.useMemo(()=>({ides:r,updateRouteChats:b,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:f}),[r,b,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(Ei.Provider,{value:A,children:t.jsx(Di.Provider,{value:p,children:e})})}function vs(){return o.useContext(Di)}function cr(){return o.useContext(Ei)}function $i(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${s}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),f=a(l),d=l.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!l.startsWith("http")&&!s?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function c(l,u={}){const f={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(f.Authorization=`Bearer ${d}`);const b=a(l),v=new AbortController,w=setTimeout(()=>v.abort(),15e3);try{const A=await fetch(b,{...u,headers:f,signal:v.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,f={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:f})}),execTerminal:(l,u,f)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:f})}),sendAgentMessage:(l,u,f)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:f})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,f)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:f?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,f={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:f})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Sd=$i({baseUrl:"http://localhost:3847"}),Nd=o.createContext(Sd);function Cd({client:e,children:s}){return t.jsx(Nd.Provider,{value:e,children:s})}const Id={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Ki=o.createContext(Id);function Ad({value:e,children:s}){return t.jsx(Ki.Provider,{value:e,children:s})}function Lt(){return o.useContext(Ki)}function Md(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 Td(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Bi(e){return e?Md([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Td(e.content)]):""}const He={size:18};function Oi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Ma({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 Qt({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 Ta({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Ld({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"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 Rd({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 Wi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 _d({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),t.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),t.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),t.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),t.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function mn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Hi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Pd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Zt({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 La({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 Dd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ds({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 Hs({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 ws({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 lr({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 Fi({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 Ui({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 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("polyline",{points:"12 6 12 12 16 14"})]})}function Ed({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 pn({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 $d({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Ra({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 Kd({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 Bd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"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 Od({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Wd({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 Hd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),t.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function fn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),t.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function 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("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 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 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function zd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"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 Vd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Gd({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 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("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 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("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 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("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 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("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}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:"2",y:"4",width:"20",height:"16",rx:"2"}),t.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),t.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),t.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),t.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),t.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),t.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),t.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),t.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),t.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Zd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),t.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function 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:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function Ao(e){return!!e&&typeof e=="object"&&"text"in e}function _a(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:Ao(i)?String(i.text||""):"").join(r):Ao(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Pa(e){return _a(e,{normalizeWhitespace:!0})}const Tn=new Map;function Mo(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function tu(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${Bi(s)}`}function To(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function Vi(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function su(e,s,r){return Number(e.receivedAt||r[sn(e,s)]||0)||0}function Gi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function ru(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function Cr(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 Ln(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function Lo(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):Gi(e)?t.jsx(Ca,{remarkPlugins:[Ia,_i,Pi],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Ir({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:Lo(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=Ln(r);return a?t.jsx("img",{src:a,alt:Cr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=Ln(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=Ln(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:Cr(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||Cr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=Cr(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}),Lo(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 sn(e,s){const r=e,n=_a(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 nu=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(Ca,{remarkPlugins:[Ia],children:s.text}),t.jsx("span",{className:"action-time",children:Vi(s.timestamp)})]})},(e,s)=>e.log===s.log),au=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var C,k,y;const u=(s.role||"").toLowerCase(),f=u==="user"||u==="human",d=s.kind||(u==="tool"?"tool":"standard"),b=ru(s.content)?s.content:null,v=!!(b!=null&&b.some(g=>g.type!=="text")),w=_a(s.content,{joiner:`
|
|
4
|
-
`});if(d==="thought"){const g=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(Wd,{size:13}),t.jsx("span",{children:g})]}),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:"⏺"}),v&&b?t.jsx("div",{className:"tool-text w-full",children:t.jsx(Ir,{parts:b,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(d==="terminal"){const g=(k=s.meta)!=null&&k.isRunning?"⏳":"✅",$=typeof((y=s.meta)==null?void 0:y.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:g}),t.jsx("span",{children:$})]}),v&&b?t.jsx("div",{className:"chat-msg-body",children:t.jsx(Ir,{parts:b,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:v&&b?t.jsx(Ir,{parts:b,renderAsPreformatted:!1}):w.slice(0,100)});const A=s.meta,p=(typeof(A==null?void 0:A.renderMode)=="string"?A.renderMode.trim():"")==="preformatted",x=w,h=!1,S=x,_=p,j=!_&&Gi(S);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(x||v||f)&&t.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${x||v?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:f?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Vi(r)})]}),(x||v)&&t.jsx("div",{className:"chat-markdown",children:v&&b?t.jsx(Ir,{parts:b,renderAsPreformatted:_}):_?t.jsx("pre",{className:"chat-preformatted",children:S}):j?t.jsx(Ca,{remarkPlugins:[Ia,_i,Pi],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),ou=o.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},emptyState:f,onLoadMore:d,isLoadingMore:b,hasMoreHistory:v,hiddenLiveCount:w=0,loadError:A,scrollToBottomRequestNonce:m},p){const x=o.useRef(null),h=o.useRef(null),S=o.useRef(null),_=o.useRef(0),j=o.useRef(""),C=o.useRef(!1),k=o.useRef(null),y=o.useRef(!1),g=o.useRef(null),$=o.useRef(!1),[L,M]=o.useState(new Set),R=o.useRef(!1),O=o.useRef(!1),F=()=>{const Y=x.current;return Y?Y.scrollHeight-Y.scrollTop-Y.clientHeight<200:!0},N=o.useCallback((Y="auto")=>{const he=x.current;he&&he.scrollTo({top:he.scrollHeight,behavior:Y})},[]),P=o.useCallback(()=>{var oe;const Y=x.current,he=(oe=window.getSelection)==null?void 0:oe.call(window);if(!Y||!he||he.rangeCount===0||he.isCollapsed){$.current=!1;return}const W=he.anchorNode,X=he.focusNode;$.current=!!(W&&X&&Y.contains(W)&&Y.contains(X))},[]),G=tu(s),I=o.useCallback(()=>{const Y=x.current;!Y||!l||Tn.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,R.current=!1,y.current=!0,!$.current){const X=l?Tn.get(l):null;X&&Mo(X,G)?requestAnimationFrame(()=>{const oe=x.current;oe&&(To(oe,X),O.current=!0)}):E("auto")}_.current=s.length;return}s.length>_.current?!R.current&&!$.current&&E("auto"):F()&&!R.current&&!$.current&&E("auto"),_.current=s.length},[G,l,c,s.length,E]),o.useEffect(()=>{m&&(R.current=!1,y.current=!0,O.current=!0,g.current!=null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{y.current=!1,g.current=null},180),$.current||E("auto"))},[E,m]),o.useEffect(()=>()=>{I(),k.current!=null&&cancelAnimationFrame(k.current),g.current!=null&&window.clearTimeout(g.current)},[I]),o.useEffect(()=>{const Y=h.current;if(!Y)return;const he=()=>{g.current!=null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{y.current=!1,g.current=null},180)},W=new ResizeObserver(()=>{y.current&&($.current||(E("auto"),he()))});return W.observe(Y),()=>{W.disconnect(),g.current!=null&&(window.clearTimeout(g.current),g.current=null)}},[E,l]),o.useImperativeHandle(p,()=>({scrollToBottom:(Y="smooth")=>{N(Y)}}),[N]),o.useEffect(()=>{const Y=x.current;if(!Y)return;let he;const W=()=>{clearTimeout(he),he=setTimeout(()=>{R.current=!F(),I()},50)};return Y.addEventListener("scroll",W,{passive:!0}),()=>{Y.removeEventListener("scroll",W),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=x.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(O.current||!l)return;const Y=Tn.get(l),he=x.current;if(!(!Y||!he)){if(!Mo(Y,G)){N("auto"),O.current=!0;return}To(he,Y),O.current=!0}},[l,G,s.length,N]);const V=()=>{const Y=x.current;Y&&(B.current=Y.scrollHeight),U.current=!0,d==null||d()},ae=o.useMemo(()=>{const Y=s.map((oe,le)=>({type:"message",data:oe,index:le,ts:su(oe,le,u)}));if(!r||r.length===0)return Y;const he=[...r].sort((oe,le)=>oe.timestamp-le.timestamp).map((oe,le)=>({type:"action",data:oe,index:le,ts:oe.timestamp})),W=[];let X=0;for(const oe of Y){for(;X<he.length&&oe.ts>0&&he[X].ts<oe.ts;)W.push(he[X++]);W.push(oe)}for(;X<he.length;)W.push(he[X++]);return W},[s,r,u]),we=w>0||!!v,be=w>0?`↑ Show ${Math.min(w,80)} earlier messages${w>80?` (${w} hidden)`:""}`:A?`↻ ${A}`:"↑ Load older messages";return t.jsx("div",{ref:x,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:h,className:"chat-container-content",children:[b&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),we&&!b&&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&&(f||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ae.map(Y=>{if(Y.type==="action"){const Se=Y.data;return t.jsx(nu,{log:Se},`action-${Y.index}`)}const he=Y.data,W=Y.index,X=sn(he,W),oe=he.receivedAt||u[X],le=`${l}-${X}`,de=L.has(le);return t.jsx(au,{message:he,receivedAt:oe,agentName:n,userName:a,isCliMode:i,isTextExpanded:de,onToggleTextExpanded:()=>M(Se=>{const ue=new Set(Se);return de?ue.delete(le):ue.add(le),ue})},`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})]})})}),iu=o.memo(ou,(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),cu="modulepreload",lu=function(e){return"/"+e},Ro={},du=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=lu(u),u in Ro)return;Ro[u]=!0;const f=u.endsWith(".css"),d=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const b=document.createElement("link");if(b.rel=f?"stylesheet":cu,f||(b.as="script"),b.crossOrigin="",b.href=u,l&&b.setAttribute("nonce",l),document.head.appendChild(b),f)return new Promise((v,w)=>{b.addEventListener("load",v),b.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 _o=!1;const qi=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([]),f=o.useRef(!1),d=o.useRef(!1),b=o.useRef(!1),v=()=>{const w=i.current;if(w){f.current&&(w.clear(),f.current=!1);for(const A of u.current)w.write(A);u.current=[],d.current&&(w.fit(),d.current=!1),b.current&&(w.bumpResize(),b.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=[],f.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(u.current=[],f.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():b.current=!0}}),[]),o.useEffect(()=>{if(!c)return;const w=requestAnimationFrame(()=>{v()});return()=>cancelAnimationFrame(w)},[c]),o.useEffect(()=>{let w=!1;return du(()=>import("./terminal-2SYILvaH.js"),__vite__mapDeps([0,1,2])).then(A=>{_o||(_o=!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"}})});qi.displayName="CliTerminal";function Ar({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 Po({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 uu({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,f=a.width/a.height;let d,b,v,w;u>f?(d=a.width,b=a.width/u,v=0,w=(a.height-b)/2):(b=a.height,d=a.height*u,v=(a.width-d)/2,w=0);const A=a.left-i.left+v+d*e.nx,m=a.top-i.top+w+b*e.ny,p=Math.max(8,Math.min(i.width-8,A)),x=Math.max(8,Math.min(i.height-8,m));return t.jsxs("div",{style:{position:"absolute",left:p-8,top:x-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[t.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function mu({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:f,zoom:d,isMobile:b,mobileFillZoom:v,onZoomOut:w,onZoomReset:A,onZoomIn:m,transportType:p,screenshotUsage:x,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:f?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),d>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),p==="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"}),p==="relay"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),x&&x.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:x.budgetExhausted?"#ef4444":"#c4b5fd",background:x.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:x.budgetExhausted?"TURN blocked":`TURN ${x.dailyUsedMinutes}/${x.dailyBudgetMinutes}m`}),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<=(b?v:1)+.01?b?"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:b?"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 pu({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 fu(){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 Do(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 hr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!fu())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,Do(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,Do(s[c])]))}),r.current=s})}function hu({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:f,setPanY:d,setZoom:b,lastWheelTimeRef:v,onAction:w,setLastActionStatus:A,spawnRippleFromNormalized:m,clampPan:p,isMobile:x,mobileFillZoom:h}){const[S,_]=o.useState(null),j=o.useRef(null),C=o.useRef(null),k=o.useRef(null),y=o.useRef(!1),g=o.useRef(null),$=o.useRef(0),L=o.useRef(null),M=o.useRef(1),R=o.useRef({x:0,y:0}),O=o.useRef(!1),F=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,_(be)};return o.useEffect(()=>{F.current=n,n==="mouse"&&V()},[n]),o.useEffect(()=>{N.current=w},[w]),o.useEffect(()=>{const be=e.current;if(!be)return;const Y=de=>{if(!r.current)return null;const Se=r.current.getBoundingClientRect();return!Se.width||!Se.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-Se.left)/Se.width)),ny:Math.max(0,Math.min(1,(de.clientY-Se.top)/Se.height))}},he=(de,Se)=>{if(!r.current)return{dnx:0,dny:0};const ue=r.current,ce=ue.getBoundingClientRect(),re=ue.naturalWidth||ce.width,pe=ue.naturalHeight||ce.height,te=re/pe,Ne=ce.width/ce.height;let ke,Ae;return te>Ne?(ke=ce.width,Ae=ce.width/te):(Ae=ce.height,ke=ce.height*te),{dnx:de/ke,dny:Se/Ae}},W=(de,Se,ue)=>{if(ue<=1.05)return;const ce=-(de-.5)*100,re=-(Se-.5)*100,pe=p(ce,re,ue);(Math.abs(pe.x-l.current)>.1||Math.abs(pe.y-u.current)>.1)&&(f(pe.x),d(pe.y),l.current=pe.x,u.current=pe.y)},X=de=>{const Se=s.current;if(Se&&de.target instanceof Node&&Se.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const ue=de.touches[0];C.current={x:ue.clientX,y:ue.clientY,time:Date.now()},k.current={x:ue.clientX,y:ue.clientY},O.current||(y.current=!1),g.current=setTimeout(()=>{if(!y.current&&!O.current)if(y.current=!0,F.current==="mouse"){const ce=j.current||{nx:.5,ny:.5};A("Right Click"),m(ce.nx,ce.ny,"right"),N.current("input_click",{...ce,button:"right"}).catch(()=>{})}else{const ce=Y(ue);ce&&(A("Right Click"),m(ce.nx,ce.ny,"right"),N.current("input_click",{...ce,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){g.current&&clearTimeout(g.current),y.current=!0,O.current=!0;const ue=de.touches[1].clientX-de.touches[0].clientX,ce=de.touches[1].clientY-de.touches[0].clientY;L.current=Math.sqrt(ue*ue+ce*ce),M.current=c.current,R.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},oe=de=>{const Se=s.current;if(Se&&de.target instanceof Node&&Se.contains(de.target)&&de.preventDefault(),de.touches.length===1&&k.current){const ue=de.touches[0],ce=ue.clientX-k.current.x,re=ue.clientY-k.current.y;if(!y.current&&C.current){const pe=ue.clientX-C.current.x,te=ue.clientY-C.current.y;Math.sqrt(pe*pe+te*te)>8&&(y.current=!0,g.current&&clearTimeout(g.current))}if(y.current)if(F.current==="mouse"){const pe=he(ce,re),te=j.current||{nx:.5,ny:.5},Ne=Math.max(0,Math.min(1,te.nx+pe.dnx)),ke=Math.max(0,Math.min(1,te.ny+pe.dny));j.current={nx:Ne,ny:ke},_({nx:Ne,ny:ke}),A(`Cursor: ${Math.round(Ne*100)}%, ${Math.round(ke*100)}%`),W(Ne,ke,c.current);const Ae=Date.now();Ae-v.current>=30&&(v.current=Ae,N.current("input_mouseMoved",{nx:Ne,ny:ke}).catch(()=>{}))}else if(c.current>1){const pe=s.current;if(pe){const te=pe.clientWidth,Ne=pe.clientHeight,ke=l.current+ce/te*100,Ae=u.current+re/Ne*100,T=p(ke,Ae,c.current);f(T.x),d(T.y),l.current=T.x,u.current=T.y}}else{const pe=Y(ue);if(pe){const te=Date.now();te-v.current>=40&&(v.current=te,A("Scroll"),N.current("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(-ce*2.5),deltaY:Math.round(-re*2.5)}).catch(()=>{}))}}k.current={x:ue.clientX,y:ue.clientY};return}if(de.touches.length===2&&L.current!==null){const ue=de.touches[1].clientX-de.touches[0].clientX,ce=de.touches[1].clientY-de.touches[0].clientY,pe=Math.sqrt(ue*ue+ce*ce)/L.current,te=(de.touches[0].clientX+de.touches[1].clientX)/2,Ne=(de.touches[0].clientY+de.touches[1].clientY)/2,ke=te-R.current.x,Ae=Ne-R.current.y,T=Math.abs(pe-1)>.03;if(F.current==="mouse"){if(T){const xe=Math.max(i,Math.min(5,M.current*pe));b(xe),c.current=xe}else if(Math.abs(ke)>2||Math.abs(Ae)>2){const xe=j.current||{nx:.5,ny:.5},ve=Date.now();ve-v.current>=30&&(v.current=ve,A("Scroll"),N.current("input_wheel",{nx:xe.nx,ny:xe.ny,deltaX:Math.round(-ke*3),deltaY:Math.round(-Ae*3)}).catch(()=>{}))}}else{const xe=Math.max(i,Math.min(5,M.current*pe));b(xe),c.current=xe;const ve=s.current;if(ve&&xe>1){const Q=ve.clientWidth,ye=ve.clientHeight,_e=l.current+ke/Q*100,We=u.current+Ae/ye*100,Pe=p(_e,We,xe);f(Pe.x),d(Pe.y),l.current=Pe.x,u.current=Pe.y}}R.current={x:te,y:Ne}}},le=de=>{var Se;if(g.current&&clearTimeout(g.current),L.current=null,de.touches.length===1&&O.current){const ue=de.touches[0];C.current={x:ue.clientX,y:ue.clientY,time:Date.now()},k.current={x:ue.clientX,y:ue.clientY},y.current=!0;return}if(de.touches.length===0){if(O.current){O.current=!1,y.current=!1;return}if(de.changedTouches.length===1){const ue=de.changedTouches[0],ce=Date.now(),re=ce-(((Se=C.current)==null?void 0:Se.time)||0),pe=C.current?ue.clientX-C.current.x:0,te=C.current?ue.clientY-C.current.y:0,Ne=Math.sqrt(pe*pe+te*te);if(F.current==="mouse"){if(re<P||re>G||Ne>I){y.current=!1;return}const ke=j.current||Y(ue);ke&&(A(`Click: ${Math.round(ke.nx*100)}%, ${Math.round(ke.ny*100)}%`),m(ke.nx,ke.ny,"left"),N.current("input_click",{...ke}).catch(()=>{}))}else{if(y.current){y.current=!1;return}if(re<E||re>B||Ne>U){y.current=!1;return}const ke=Y(ue);if(!ke)return;ce-$.current<300?(A("Double tap"),m(ke.nx,ke.ny,"double"),N.current("input_click",{...ke,clickCount:2}).catch(()=>{}),$.current=0):(A(`Tap: ${Math.round(ke.nx*100)}%, ${Math.round(ke.ny*100)}%`),m(ke.nx,ke.ny,"left"),N.current("input_click",{...ke}).catch(()=>{}),$.current=ce)}}y.current=!1}};return be.addEventListener("touchstart",X,{passive:!1}),be.addEventListener("touchmove",oe,{passive:!1}),be.addEventListener("touchend",le,{passive:!1}),()=>{be.removeEventListener("touchstart",X),be.removeEventListener("touchmove",oe),be.removeEventListener("touchend",le),g.current&&clearTimeout(g.current)}},[e,s,r,i,c,l,u,f,d,b,v,A,m,p]),{cursorPos:S,cursorPosRef:j,handleToggleInputMode:()=>{a(be=>{const Y=be==="touch"?"mouse":"touch";return Y==="mouse"&&V(),Y})},handleZoomReset:()=>{const be=x?h:1;b(be),c.current=be,f(0),d(0),l.current=0,u.current=0}}}function Yi({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[f,d]=o.useState(null),[b,v]=o.useState(""),[,w]=o.useState(!1),[A,m]=o.useState([]),p=o.useRef(0),[x,h]=o.useState(!1),[S,_]=o.useState(!1),j=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[C,k]=o.useState(j?"mouse":"touch"),[y,g]=o.useState(1),$=o.useRef(!1),[L,M]=o.useState(1),[R,O]=o.useState(0),[F,N]=o.useState(0);hr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:C,zoom:L,panX:R,panY:F,isMenuOpen:x,isImeOpen:S});const P=o.useRef(0),G=o.useRef(L),I=o.useRef(R),E=o.useRef(F);o.useEffect(()=>{G.current=L},[L]),o.useEffect(()=>{I.current=R},[R]),o.useEffect(()=>{E.current=F},[F]),o.useEffect(()=>{var re;(re=c.current)==null||re.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 re=u.current,pe=l.current;if(!re||!pe)return;const te=()=>{const Ne=pe.clientWidth,ke=pe.clientHeight,Ae=re.naturalWidth,T=re.naturalHeight;if(!Ae||!T||!Ne||!ke)return;const xe=Math.min(Ne/Ae,ke/T),Q=Math.max(Ne/Ae,ke/T)/xe;Q>1.01&&(g(Q),M(Q),G.current=Q),$.current=!0};re.complete&&re.naturalWidth?te():re.addEventListener("load",te,{once:!0})},[U,j]);const we=.5;o.useEffect(()=>{L<=we&&(O(0),N(0))},[L,we]);const be=(re,pe,te)=>{if(te<=we)return{x:0,y:0};const Ne=(te-1)/(2*te)*100,ke=(te-1)/(2*te)*100;return{x:Math.max(-Ne,Math.min(Ne,re)),y:Math.max(-ke,Math.min(ke,pe))}},Y=(re,pe)=>{if(!u.current)return null;const te=u.current.getBoundingClientRect();return!te.width||!te.height?null:{nx:Math.max(0,Math.min(1,(re-te.left)/te.width)),ny:Math.max(0,Math.min(1,(pe-te.top)/te.height))}},he=(re,pe,te)=>{const Ne=l.current;if(!Ne)return;const ke=Ne.getBoundingClientRect(),Ae=++p.current;m(T=>[...T,{id:Ae,x:re-ke.left,y:pe-ke.top,type:te}]),setTimeout(()=>m(T=>T.filter(xe=>xe.id!==Ae)),600)},W=(re,pe,te)=>{const Ne=u.current,ke=l.current;if(!Ne||!ke)return;const Ae=Ne.getBoundingClientRect(),T=ke.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*re,it=Ae.top-T.top+ze+We*pe,et=++p.current;m(pt=>[...pt,{id:et,x:Qe,y:it,type:te}]),setTimeout(()=>m(pt=>pt.filter(tt=>tt.id!==et)),600)},X=async re=>{var te;const pe=Y(re.clientX,re.clientY);if(pe){d(`Click: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),he(re.clientX,re.clientY,"left"),(te=c.current)==null||te.focus();try{const Ne=await e("input_click",{nx:pe.nx,ny:pe.ny});Ne!=null&&Ne.success||s(`❌ Click failed: ${Ne==null?void 0:Ne.error}`)}catch(Ne){s(`❌ Click error: ${Ne.message||Ne}`)}}},oe=async(re,pe,te,Ne=0)=>{try{await e("input_key",{type:te?"char":"keyDown",key:re,code:pe,text:te?re:void 0,unmodifiedText:te?re:void 0,modifiers:Ne})}catch(ke){s(`❌ Key error: ${ke.message||ke}`)}},le=async re=>{if(re.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(re.key)&&re.preventDefault();let te=0;re.altKey&&(te|=1),re.ctrlKey&&(te|=2),re.metaKey&&(te|=4),re.shiftKey&&(te|=8),d(`Key: ${re.key}`),await oe(re.key,re.code,re.key.length===1,te)},de=async re=>{if(re.key==="Enter"){if(re.nativeEvent.isComposing)return;if(b){const pe=b;v(""),d(`IME Sent: ${pe}`);try{const te=await e("input_type",{text:pe});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 oe("Enter","Enter",!1)}};o.useEffect(()=>{const re=c.current;if(!re)return;const pe=te=>{var Ne;if((Ne=u.current)!=null&&Ne.contains(te.target)){te.preventDefault();const ke=Date.now();if(ke-P.current<40)return;P.current=ke;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 re.addEventListener("wheel",pe,{passive:!1}),()=>re.removeEventListener("wheel",pe)},[e]);const{cursorPos:Se,handleToggleInputMode:ue,handleZoomReset:ce}=hu({containerRef:c,viewportRef:l,imgRef:u,inputMode:C,setInputMode:k,minZoom:we,zoomRef:G,panXRef:I,panYRef:E,setPanX:O,setPanY:N,setZoom:M,lastWheelTimeRef:P,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:W,clampPan:be,isMobile:j,mobileFillZoom:y});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:le,onContextMenu:re=>re.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(${R}%, ${F}%)`,transformOrigin:"center center",cursor:C==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:X,onContextMenu:re=>re.preventDefault(),onDragStart:re=>re.preventDefault()}):t.jsx(pu,{waitingLabel:V,waitingHint:ae,transportType:i}),C==="mouse"&&U&&t.jsx(uu,{cursorPos:Se,viewportRef:l,imgRef:u}),A.map(re=>{const te={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[re.type];return t.jsxs("div",{style:{position:"absolute",left:re.x,top:re.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}})]},re.id)})]}),t.jsx(mu,{inputMode:C,onToggleInputMode:ue,isImeOpen:S,setIsImeOpen:_,isMenuOpen:x,setIsMenuOpen:h,imeText:b,setImeText:v,handleImeSubmit:de,isConnActive:B,zoom:L,isMobile:j,mobileFillZoom:y,onZoomOut:()=>M(re=>Math.max(.5,re-.25)),onZoomReset:ce,onZoomIn:()=>M(re=>Math.min(5,re+.25)),transportType:i,screenshotUsage:a,lastActionStatus:f}),t.jsx("style",{children:`
|
|
5
|
-
@keyframes slideUp {
|
|
6
|
-
from { opacity: 0; transform: translateY(6px); }
|
|
7
|
-
to { opacity: 1; transform: translateY(0); }
|
|
8
|
-
}
|
|
9
|
-
@keyframes slideUpSidebar {
|
|
10
|
-
from { opacity: 0; transform: translateY(6px); }
|
|
11
|
-
to { opacity: 1; transform: translateY(0); }
|
|
12
|
-
}
|
|
13
|
-
@keyframes click-ripple-ring {
|
|
14
|
-
0% { transform: scale(0.3); opacity: 1; }
|
|
15
|
-
100% { transform: scale(2.2); opacity: 0; }
|
|
16
|
-
}
|
|
17
|
-
@keyframes click-ripple-dot {
|
|
18
|
-
0% { transform: scale(1); opacity: 0.9; }
|
|
19
|
-
50% { transform: scale(1.8); opacity: 0.6; }
|
|
20
|
-
100% { transform: scale(0.5); opacity: 0; }
|
|
21
|
-
}
|
|
22
|
-
@keyframes remote-float {
|
|
23
|
-
0% { transform: translateY(0px); }
|
|
24
|
-
50% { transform: translateY(-7px); }
|
|
25
|
-
100% { transform: translateY(0px); }
|
|
26
|
-
}
|
|
27
|
-
`})]})}function Nt(e){return(typeof e=="string"?e.trim():"")||void 0}function Jt(e,s){const r=Nt(s);return r?`${e}:${r}`:void 0}function ts(e,s,r){const n=Jt(s,r),a=Nt(r);n&&e.push(n),a&&e.push(a)}function Ms(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function Xi(e){return Nt(e.providerSessionId)||Nt(e.sessionId)||Nt(e.tabKey)||Nt(e.routeId)}function Da(e){return Ms([Nt(e.providerSessionId),Nt(e.sessionId)])}function ss(e){const s=[];return ts(s,"provider",e.providerSessionId),ts(s,"session",e.sessionId),ts(s,"tab",e.tabKey),ts(s,"route",e.routeId),Ms(s)}function xu(e){const s=[];return Nt(e.providerSessionId)?(ts(s,"provider",e.providerSessionId),Ms(s)):Nt(e.sessionId)?(ts(s,"session",e.sessionId),Ms(s)):Nt(e.tabKey)?(ts(s,"tab",e.tabKey),Ms(s)):Nt(e.routeId)?(ts(s,"route",e.routeId),Ms(s)):[]}function Ea(e){return Jt("provider",e.providerSessionId)||Jt("session",e.sessionId)||Jt("tab",e.tabKey)||Jt("route",e.routeId)||"unknown:"}function xr(e){return Da(e)[0]}function Ji(e){const s=Nt(e.providerSessionId),r=Nt(e.sessionId),n=Nt(e.tabKey),a=Nt(e.routeId),i=[Jt("provider",s),Jt("session",r),Jt("tab",n),Jt("route",a)].filter(u=>typeof u=="string"),c=ss({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=Ea({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Xi({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:xr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function dr(e,s){const r=Ji(e);return xu(s).some(n=>r.lookupKeys.includes(n))}function hn(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=s,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const f=Math.floor(u/24);return f<7?`${f}d${r}`:new Date(e).toLocaleDateString()}const Qi=e=>hn(e);function bu(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 Fs(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 gu(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...bu(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 rn(e,s){if(e.sessionId){const r=s.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function xn(e,s,r){const n=rn(e,s),a=Fs(e),i=ss(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,f=a.isWaiting,d=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||f,b=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:b,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:f,inboxBucket:d?"needs_attention":b?"working":w?"task_complete":"idle"}}function yu(e,s,r){return xn(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation,notificationStateBySessionId:r==null?void 0:r.notificationStateBySessionId}).unread}function Zi({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Fs(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(ws,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const f=c(l).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(f),b=/^(reject|deny|delete|remove|abort)/.test(f),v=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":b?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!v?"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)"}:b?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:v?"⏳ ...":c(l)},u)})})]})]})}const $a="adhdev_controls_bar_visible",da="adhdev:controlsbarvisibilitychange";function Rn(e){if(!e)return!1;try{return e.getItem($a)==="1"}catch{return!1}}function Eo(e,s){if(s)try{s.setItem($a,e?"1":"0")}catch{}}function $o(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(da,{detail:{visible:e}}))}function ec(){const[e,s]=o.useState(()=>typeof window>"u"?!1:Rn(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(Rn(window.localStorage))},i=c=>{c.key===$a&&s(Rn(window.localStorage))};return window.addEventListener(da,a),window.addEventListener("storage",i),()=>{window.removeEventListener(da,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{s(a),typeof window<"u"&&Eo(a,window.localStorage),$o(a)},[]),n=o.useCallback(()=>{s(a=>{const i=!a;return typeof window<"u"&&Eo(i,window.localStorage),$o(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var vu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function wu(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function St(e,s){if(wu(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":vu.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 tc(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 ju(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 _n(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function bn(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 ku(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 Su(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Nu(e){return ku(e.trim().replace(/\.local$/i,""))}function Cu(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function sc(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&&!Su(c));if(r&&r!=="Unknown")return Nu(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function _t(e,s={}){return Cu(e)||sc(e,s)}function rc(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 nc(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 js(e,s){return rc(e).join(" · ")}function ur(e){return e.transport==="pty"}function Ts(e){return e.transport==="acp"}function Iu(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 Ko(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 Au(e){return St(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Mu(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 Tu(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 Lu(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&&Tu(s.receivedAt)||0}function Ru(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ua(e){return Math.max(Ru(e),Lu(e.activeChat))}function _u(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 Ka(e,s){return _u(ua(e),ua(s),_t(e,{fallbackId:e.id}),_t(s,{fallbackId:s.id}),e.id,s.id)}const ac="adhdev_notification_prefs",Bo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Pu(){try{const e=localStorage.getItem(ac);if(e){const s=JSON.parse(e);return{...Bo,...s}}}catch{}return{...Bo}}function Du(e){try{localStorage.setItem(ac,JSON.stringify(e))}catch{}}let Xt=Pu(),Vr=[];function Eu(){Vr.forEach(e=>e())}function $u(e){Xt={...Xt,...e},Du(Xt),Eu()}function Ku(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Vr.push(r),()=>{Vr=Vr.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{$u(r)},[]);return[{...Xt},s]}function sr(e){if(!Xt.globalEnabled)return!1;switch(e){case"disconnect":return Xt.disconnectAlert;case"completion":return Xt.completionAlert;case"approval":return Xt.approvalAlert;case"browser":return Xt.browserNotifications;default:return!0}}const Bu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function oc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function ic(){return"Notification"in window&&Notification.permission==="granted"}let cs=null;async function Ou(){if(cs!==null)return cs;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return cs=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(cs=!!await e.pushManager.getSubscription(),cs):(cs=!1,!1)}catch{return cs=!1,!1}}function ma(e,s,r){if(ic())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 Wu(e,s={}){const r={...Bu,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Ou().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,f)=>{const d=Date.now();d-a.current<r.throttleMs||(a.current=d,ma(l,u,f))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!ic())&&sr("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 f=n.current.get(u.id),d=St(u.status,{activeModal:u.activeModal}),b=u.name||u.id;if(r.onApproval&&sr("approval")&&d==="waiting_approval"&&f!=="waiting_approval"){const v=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${b} — Approval needed`,v.slice(0,120),`approval-${u.id}`)}r.onComplete&&sr("completion")&&tc(f)&&d==="idle"&&c(`✅ ${b} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&d==="error"&&f!=="error"&&c(`⚠️ ${b} — 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 Hu=/^(run|approve|accept|yes|allow|always)/,Fu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Uu=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ba(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function zu(e){const s=Ba(e).toLowerCase();return Hu.test(s)?"primary":Uu.test(s)?"danger":"default"}function Vu(e){return Fu.test(Ba(e).toLowerCase())?"approve":"reject"}function Gu(e){return e.map((s,r)=>({label:Ba(s),variant:zu(s),action:Vu(s),button:s,buttonIndex:r}))}function qu(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 Yu(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Xu(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 Ju{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,f=(u==null?void 0:u.type)||"";let d=dt(f);const b=this.resolveOwningDaemon(s);if(b){const p=_t(b,{fallbackId:b.id});p&&(d=!f||f==="adhdev-daemon"?p:`${p}/${d}`)}let v="",w="info";if(s.event==="agent:generating_completed"){const p=s.duration?` (${s.duration}s)`:"";v=`✅ ${d} agent task completed${p}`,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(v=`⚡ ${d} approval needed`,w="warning",n&&!((A=s.modalButtons)!=null&&A.length)&&this.emitSystemMessage(n,{role:"system",timestamp:a,content:qu(s.modalMessage,s.modalButtons),_localId:`sys_approval_${a}`}),(m=s.modalButtons)!=null&&m.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(s);if(!p)return;const x=this.resolveActionFn,h=Gu(s.modalButtons).map(j=>({label:j.label,variant:j.variant,onClick:()=>{x(p,"resolve_action",{action:j.action,button:j.button,buttonIndex:j.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),S=Yu(d,s.modalMessage,v),_=Date.now();this.emitToast({id:_,message:S,type:w,timestamp:_,targetKey:n||p,actions:h,duration:15e3}),v=""}}else if(s.event==="monitor:long_generating"){const p=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";v=`⚠️ ${d} agent is taking a long time${p}`,w="warning",sr("browser")&&!document.hasFocus()&&ma(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const p=s.requesterName||"A team member",x=s.requestId,h=s.orgId;if(v=`👁️ ${p} wants to view your session`,w="warning",x&&h&&this.viewRequestRespondFn){const S=Date.now(),_=Xu(h,x,this.viewRequestRespondFn,(j,C)=>console.error(`[EventManager] ${j} view request failed:`,C));this.emitToast({id:S,message:v,type:w,timestamp:S,actions:_,duration:3e4}),v=""}sr("browser")&&!document.hasFocus()&&ma("👁️ View Request",`${p} wants to view your session`,`view-request-${x}`)}else s.event==="team:view_request_approved"?(v="✅ View request approved",w="success"):s.event==="team:view_request_rejected"&&(v=`❌ ${s.targetName||"Team member"} declined your view request`,w="warning");if(v){const p=Date.now();this.emitToast({id:p,message:v,type:w,timestamp:p,targetKey:n||s.daemonId,duration:5e3})}}}const at=new Ju,Oo=new Map;function Es(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ls(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Qu(e){return!Es(e)||!Es(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function Mr(e){return!Es(e)||!Es(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function Gs(e){if(!(!Es(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function Tr(e){return Es(e)&&e.success===!1}function Zu(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const 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 em(e,s){return e&&Ls(e.currentValue)?e.currentValue:s}function tm(e,s){return Ls(s)?Ls(e)?typeof e=="string"&&e.trim()==="":!0:!1}function sm(e,s){var i,c;if((s.now??Date.now())<s.localOverrideUntil){const l=s.localValues[e];if(Ls(l))return l}const n=(i=s.controlValues)==null?void 0:i[e];if(Ls(n))return n;const a=(c=s.defaultValues)==null?void 0:c[e];return Ls(a)?a:void 0}function Gr(e,s){return e.options||s[e.id]||[]}const rm={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 nm(e,s,r){var n;return((n=rm[s])==null?void 0:n.has(r.id))===!0}function Oa(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!nm(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Pn(e,s){return{value:s}}function am(e,s,r){var a;return r?((a=Gr(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const om={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function im({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=Lt(),u=`${e}:${s||n}`,f=om[n]||"#94a3b8",[d,b]=o.useState({}),v=o.useRef({}),w=o.useRef(c);v.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 p={...m,...c||{},...Date.now()<A.current?d:{}};o.useEffect(()=>{c&&Date.now()>A.current&&b({})},[c]);const[x,h]=o.useState(Oo.get(u)||{}),[S,_]=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]),y=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]),g=o.useCallback((P,G,I)=>{const E=em(I,G);b(B=>({...B,[P.id]:E})),Zu(I==null?void 0:I.effects)},[]),$=o.useCallback((P,G)=>{b(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=Oa(i,{hostIdeType:r,providerType:n});if(L.length===0)return null;const M=async P=>{if(S===P.id){_(null);return}if(Gr(P,x).length>0){_(P.id);return}if(P.dynamic&&P.listScript){C(P.id);try{const I=await y(P.listScript,{}),E=Qu(I);if(!E){const V=Gs(I);V&&at.showToast(V,"warning");return}const B=E.options;h(V=>{const ae={...V,[P.id]:B};return Oo.set(u,ae),ae});const U=sm(P.id,{localOverrideUntil:A.current,localValues:v.current,controlValues:w.current,defaultValues:m});if(tm(U,E.currentValue)){const V=E.currentValue;b(ae=>({...ae,[P.id]:V}))}_(P.id)}catch(I){const E=I instanceof Error?I.message:`Could not load ${P.label}`;at.showToast(E,"warning")}finally{C(null)}}},R=async(P,G)=>{_(null);const I=(c==null?void 0:c[P.id])??m[P.id];b(E=>({...E,[P.id]:G})),A.current=Date.now()+5e3;try{if(!P.setScript)return;const E=await y(P.setScript,Pn(P,G)),B=Mr(E);if(B&&!B.ok||Tr(E))throw new Error((B==null?void 0:B.error)||Gs(E)||`Could not update ${P.label}`);g(P,G,B)}catch(E){$(P,I);const B=E instanceof Error?E.message:`Could not update ${P.label}`;at.showToast(B,"warning")}},O=async P=>{const G=Gr(P,x).map(ae=>ae.value);if(G.length===0)return;const I=String(p[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];b(ae=>({...ae,[P.id]:U})),A.current=Date.now()+5e3;try{if(!P.setScript)return;const ae=await y(P.setScript,Pn(P,U)),we=Mr(ae);if(we&&!we.ok||Tr(ae))throw new Error((we==null?void 0:we.error)||Gs(ae)||`Could not update ${P.label}`);g(P,U,we)}catch(ae){$(P,V);const we=ae instanceof Error?ae.message:`Could not update ${P.label}`;at.showToast(we,"warning")}},F=async P=>{const I=!p[P.id],E=(c==null?void 0:c[P.id])??m[P.id];b(B=>({...B,[P.id]:I})),A.current=Date.now()+5e3;try{if(!P.setScript)return;const B=await y(P.setScript,Pn(P,I)),U=Mr(B);if(U&&!U.ok||Tr(B))throw new Error((U==null?void 0:U.error)||Gs(B)||`Could not update ${P.label}`);g(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 y(P.invokeScript),E=Mr(I);if(E&&!E.ok||Tr(I))throw new Error((E==null?void 0:E.error)||Gs(I)||`Could not run ${P.label}`);E&&g(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:`${f}33`,background:`${f}12`,color:f},children:a}),L.map(P=>{const G=String(p[P.id]||""),I=am(P,x,G),E=S===P.id,B=j===P.id,U=Gr(P,x),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?`${f}55`:"var(--border-default)",background:E?`${f}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:()=>_(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?`${f}14`:"transparent",color:ae.value===G?"var(--text-primary)":"var(--text-secondary)",borderLeft:ae.value===G?`2px solid ${f}`:"2px solid transparent"},title:ae.description||ae.label,onMouseEnter:we=>{we.currentTarget.style.background=`${f}10`},onMouseLeave:we=>{we.currentTarget.style.background=ae.value===G?`${f}14`:"transparent"},onClick:()=>void R(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:f},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 O(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?`${f}44`:"var(--border-default)",background:G?`${f}14`:"var(--surface-tertiary)",color:G?f:"var(--text-muted)"},onClick:()=>void F(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 cm({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:f}=ec(),d=Oa(l,{hostIdeType:a,providerType:i});return!e||s||d.length===0||!f?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(im,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function lm({hasDraft:e,isBusy:s=!1}){return!e||s}const cc=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1}){const f=o.useRef(null),[d,b]=o.useState(""),{isVisible:v,toggleVisibility:w}=ec();o.useEffect(()=>{b("")},[s]),o.useEffect(()=>{var m;l&&((m=f.current)==null||m.focus())},[s,l]);const A=async()=>{const m=d.trim();if(!m||a)return;await c(m)!==!1&&b("")};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":v?"Hide controls":"Show controls","aria-pressed":v,title:v?"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:f,type:"text",placeholder:i||`Send message to ${r}...`,value:d,onChange:m=>b(m.target.value),onPaste:m=>{const p=m.clipboardData.getData("text");p&&b(x=>x+p),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 p=m.relatedTarget;if((p==null?void 0:p.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:lm({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",$s=(e,s)=>nt(e)?e.mode||"terminal":"chat",lc=(e,s)=>nt(e)&&$s(e)==="terminal",Ze=e=>e.transport==="acp";function rs(e){return e.streamSource!=="agent-stream"}function os(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function dc(e){return e.machineName||""}function br(e){return os(e)}function Wt(e){return e.agentType||""}function nn(e){return e.hostIdeType||""}function Wa(e){return e.displayPrimary||e.agentName||"Agent"}function uc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function dm(e){return e.lastMessagePreview||e.displaySecondary||""}function mc(e){return[e.displaySecondary,dc(e)].filter(Boolean)}function Ks(e){return e.agentName||dt(Wt(e))}function um(e){var s,r;if(!rs(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return dt(nn(e)||Wt(e))}function pc(e){return rs(e)?e.sessionId:e.nativeSessionId}function Wo(e){return rs(e)?"native":e.tabKey}function mm(e){return e.sessionId}function pm(e,s){if(s)return rs(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function fm(e,s){const r=Wt(e),n=rs(e),a=nt(e)||Ze(e),i=n?a?Ks(e)||(s==null?void 0:s.cliName)||dt(nn(e)||r):s!=null&&s.type?dt(s.type):dt(nn(e)||r):Ks(e);return{isNativeConversation:n,isCli:nt(e),isAcp:Ze(e),isCliTerminal:lc(e),providerType:r,displayLabel:i,targetEntry:pm(e,s)}}function hm(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function ms(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||hm(s==null?void 0:s.receivedAt)||0}function pa(e,s=0){return ms(e)||e.lastUpdated||s||0}function fc(e){return ms(e)||e.lastUpdated||0}function hc(e,s,r=fc){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 fa(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 xm(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!fa(e)&&!e.title.trim()}function bm(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(fa(r))-Number(fa(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:hc(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=bm(a);return n?i&&xm(n)?i:n:i||r[0]||null}function ns(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ha(e){return xr(e)||e.tabKey||e.routeId||null}function xc(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?Ha(a):null}function bc({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Ws(),c=os(e),l=dc(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,d=!f&&(e.transport==="pty"||e.transport==="acp"),b=Ks(e),v=um(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=Ha(e);m&&i(ns(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:v,children:[t.jsx(Pt,{size:12}),t.jsx("span",{children:v})]}):t.jsxs("span",{className:"conversation-meta-chip",title:v,children:[t.jsx(Pt,{size:12}),t.jsx("span",{children:v})]})),f&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[t.jsx(lr,{size:12}),t.jsx("span",{children:b})]}),d&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[t.jsx(lr,{size:12}),t.jsx("span",{children:b})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:l,children:[t.jsx(Qt,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(Qt,{size:12}),t.jsx("span",{children:l})]}))]})}function Dn(e,s){return`${e}:${s}`}function gm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Lr(e,s){gm()&&console.debug(`[subscription-manager] ${e}`,s)}class ym{constructor(){Ye(this,"active",new Map)}subscribe(s,r,n,a){var f;const i=Dn(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),Lr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((f=s.sendData)==null?void 0:f.call(s,r,n))??!1}const u=()=>{var v;const d=this.active.get(i);if(!d||(d.handlers.delete(a),d.handlers.size>0))return;this.active.delete(i);const b={type:"unsubscribe",topic:n.topic,key:n.key};Lr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(v=s.sendData)==null||v.call(s,r,b)};return u.initialSendAccepted=l,u}publish(s){const r=Dn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Ps.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(a=>{a(s),Ps.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}updateParams(s,r,n){const a=Dn(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;Lr("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);Lr("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 as=new ym;function vm(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 wm(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 an(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:f,childrenByParent:d}=wm(u),b=vm(i,n),v=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=f.filter(p=>p.kind==="workspace"&&p.transport==="cdp-page"),A=f.filter(p=>p.kind==="agent"&&p.transport==="pty"),m=f.filter(p=>p.kind==="agent"&&p.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...v&&{machine:v,platform:v.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(p=>!!p.cdpConnected)});for(const p of w){const x=b.get(p.id),h=er(p,x),S=(d.get(p.id)||[]).map(_=>er(_,b.get(_.id)));r.push({id:`${n}:ide:${p.id}`,sessionId:p.id,providerSessionId:p.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:p.id,workspace:h.workspace,terminals:0,childSessions:S,agents:S.map(_=>({id:_.id,name:_.providerName||_.providerType,type:_.providerType,status:_.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,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 p of A){const x=b.get(p.id),h=er(p,x);r.push({id:`${n}:cli:${p.id}`,sessionId:p.id,providerSessionId:p.providerSessionId??(x==null?void 0:x.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:p.id,cliName:h.providerName||h.providerType,mode:h.mode||(x==null?void 0:x.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 p of m){const x=b.get(p.id),h=er(p,x);r.push({id:`${n}:acp:${p.id}`,sessionId:p.id,providerSessionId:p.providerSessionId??(x==null?void 0:x.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:p.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 jm=15e3,km=15e3,Sm=6e4,Nm=1200,Ho=12,Cm=8e3,Im=4e3,En=new Map,$n=new Map,Rr=new Set,rr=new Map;function Am(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 Fo(e,s){const r=rr.get(e);!r||r.size===0||(rr.delete(e),r.forEach(n=>n(s)))}function Mm(e,s){return new Promise(r=>{const n=rr.get(e)||new Set;rr.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&rr.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function gr(){const{sendCommand:e,sendData:s}=Lt(),{injectEntries:r,getIdes:n}=cr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??Sm,l=$n.get(a)||0;if(!(i!=null&&i.force)&&Rr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=En.get(a);if(u)return u;const f=(async()=>{if(s&&!Rr.has(a)){const m=as.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},p=>{const x=n(),h=x.find(_=>_.id===a),S=an(p.status,{daemonId:a,existingDaemon:h,existingEntries:x,timestamp:p.timestamp});S.length>0&&r(S),$n.set(a,Date.now()),Fo(a,!0)});if(m.initialSendAccepted?Rr.add(a):Rr.delete(a),!(i!=null&&i.force)&&m.initialSendAccepted&&await Mm(a,Nm))return}const d=await e(a,"get_status_metadata"),b=Am(d);if(!b)return;const v=n(),w=v.find(m=>m.id===a),A=an(b,{daemonId:a,existingDaemon:w,existingEntries:v,timestamp:b.timestamp||Date.now()});A.length>0&&r(A,{authoritativeDaemonIds:[a]}),$n.set(a,Date.now()),Fo(a,!0)})().finally(()=>{En.delete(a)});return En.set(a,f),f},[n,r,e,s])}function Tm(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function Rs(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:nt(e)||Ze(e)?{agentType:Wt(e)}:e.streamSource==="agent-stream"?{agentType:Wt(e)}:s}function mr(e){return e?br(e):""}function qs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Fa(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 Lm(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 Rm=60,_m=1e3;function gc(e={}){return e.isCliLike?_m:Rm}function Pm(e={}){return gc(e)}const yr=60,Dm=1e3,Ua=12e4,Em=new Set(["generating","waiting_approval","starting","streaming","working"]),Uo=new Map;function yc(e,s){return`${e}::${s}`}function ha(e=yr){return{liveMessages:[],cursor:wc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function vc(e){return Bi(e)}function wc(e,s=yr){return{knownMessageCount:e.length,lastMessageSignature:vc(e[e.length-1]),tailLimit:s}}function _r(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 $m(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return[...e,...r];case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return[...e.slice(0,n),...r]}case"full":return r;default:return r}}class Km{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||as,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=ha(Math.max(0,s.tailLimit??yr))}updateOptions(s){if(s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId),s.tailLimit!==void 0){const r=Math.max(0,s.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length);this.snapshot={...this.snapshot,cursor:{...this.snapshot.cursor,knownMessageCount:n,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=r,a=wc(n,this.snapshot.cursor.tailLimit);_r(this.snapshot.liveMessages)===_r(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()},Dm))}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=$m(this.snapshot.liveMessages,s),n={knownMessageCount:r.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:vc(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};_r(this.snapshot.liveMessages)===_r(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 jc(e){const s=yc(e.daemonId,e.sessionId),r=Uo.get(s);if(r)return r.updateOptions(e),r;const n=new Km(e);return Uo.set(s,n),n}function Bm(e,s){return{...e,loadHistoryPage:s}}function Om(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Wm(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(Em.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??Ua)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=a:Array.isArray(e.messages)&&e.messages.length>0}function Hm(e=Ua){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Fm(e,s={}){const r=new Set,n=[];for(const a of e){if(!Wm(a,s))continue;const i=br(a),c=a.sessionId||"";if(!i||!c)continue;const l=yc(i,c);if(r.has(l))continue;r.add(l);const u=xr(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Om),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Um(e,s){const{sendData:r,sendCommand:n}=Lt(),a=(s==null?void 0:s.enabled)!==!1,i=br(e),c=e.sessionId||"",l=xr(e)||c,u=`daemon:${i}:session:${c}`,f=Math.max(0,(s==null?void 0:s.tailLimit)??yr),d=o.useMemo(()=>!a||!i||!c?null:jc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:f}),[i,a,l,r,c,u,f]),[b,v]=o.useState(()=>(d==null?void 0:d.getSnapshot())||ha(f));o.useEffect(()=>{if(!d){v(ha(f));return}d.retain(),v(d.getSnapshot());const A=d.subscribe(m=>{v(m)});return()=>{A(),d.release()}},[d,f]),o.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),v(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}),p=m&&typeof m=="object"&&"result"in m?m.result||{}:m||{};return{messages:Array.isArray(p.messages)?p.messages:[],hasMore:p.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return o.useMemo(()=>Bm(b,w),[w,b])}function zm(e,s){const{sendData:r}=Lt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??yr),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??Ua)),c=Hm(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const d=setInterval(()=>{u(b=>b+1)},c);return()=>{clearInterval(d)}},[e.length,n,c]);const f=o.useMemo(()=>Fm(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||f.descriptors.length===0)return;const d=f.descriptors.map(b=>jc({...b,sendData:r,tailLimit:a}));return d.forEach(b=>b.retain()),()=>{d.forEach(b=>b.release())}},[f.signature,n,r,a])}function Vm(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Gm(e){return Vm(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const qm=60;function xa({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:f=!1,scrollToBottomRequestNonce:d,isInputActive:b=!0}){var we,be,Y,he,W;const v=o.useRef(new Map),w=gr();hr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const A=lt.useMemo(()=>Fs(e),[e.status,e.connectionState]),m=o.useMemo(()=>fm(e,s),[e,s]),p=o.useMemo(()=>{var X;return Oa((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]),x=gc({isCliLike:m.isCli||m.isAcp}),h=Pm({isCliLike:m.isCli||m.isAcp}),S=Um(e,{enabled:!!e.sessionId,tailLimit:h}),[_,j]=o.useState(x),C=e.tabKey,k=S.historyMessages,y=S.hasMoreHistory,g=S.historyError,$=S.liveMessages.length>0?S.liveMessages:e.messages;o.useEffect(()=>{j(x)},[x,C]);const L=Math.max(0,$.length-_),M=Wa(e),R=br(e),O=Gm(e),F=Fa(e),N=a||F,P=!!F,[G,I]=o.useState(!1);o.useEffect(()=>{const X=m.targetEntry;R&&(!X||X.providerControls===void 0||X.controlValues===void 0)&&w(R,{minFreshMs:3e4}).catch(()=>{})},[R,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>_){j(X=>Math.min($.length,X+qm));return}I(!0);try{await S.loadHistoryPage()}finally{I(!1)}}},[S,G,$.length,_]),{allMessages:B,receivedAtMap:U}=o.useMemo(()=>{const X=L>0?$.slice(-_):$,oe=k.length===0?X:[...k,...X],le={};return oe.forEach((de,Se)=>{const ue=`${e.tabKey}:${sn(de,Se)}`;let ce=Tm(de)||v.current.get(ue)||0;ce||(ce=Date.now(),v.current.set(ue,ce)),le[sn(de,Se)]=ce}),{allMessages:oe,receivedAtMap:le}},[e.tabKey,L,k,$,_]),V=o.useMemo(()=>l.filter(X=>X.routeId===e.tabKey).sort((X,oe)=>X.timestamp-oe.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"&&O)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(lr,{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(Ds,{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"&&O)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(Fi,{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(Ds,{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,O,i,c,G,$.length,M,A.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&t.jsx(bc,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(iu,{messages:B,actionLogs:V,agentName:Ks(e)||M||"Agent",userName:u,isCliMode:m.isCli||m.isAcp,isWorking:A.isGenerating,contextKey:e.tabKey,receivedAtMap:U,onLoadMore:E,isLoadingMore:G,hasMoreHistory:y,hiddenLiveCount:L,loadError:g??void 0,emptyState:ae,scrollToBottomRequestNonce:d}),t.jsx(cm,{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:(W=m.targetEntry)==null?void 0:W.controlValues,isActive:b,isCliTerminal:m.isCliTerminal}),!m.isCliTerminal&&t.jsx(cc,{contextKey:e.tabKey,panelLabel:M,isSending:n,isBusy:P,statusMessage:N,onSend:r,isActive:b,showControlsToggle:p.length>0})]})}let kc=vs;function Sc(){return kc()}class Ym{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 Nc=new Ym;class Xm{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 Xm;function Jm(e){e.dashboardWS&&(Nc=e.dashboardWS),e.connectionManager&&(rt=e.connectionManager),e.useDaemonsHook&&(kc=e.useDaemonsHook)}const Cc=.6,Ic=1.15;function zo(e,s,r){return Math.min(r,Math.max(s,e))}function Qm(e,s,r={}){const n=typeof r.minScale=="number"?r.minScale:Cc,a=typeof r.maxScale=="number"?r.maxScale:Ic;if(!Number.isFinite(e)||e<=0||!Number.isFinite(s)||s<=0)return 1;if(e<=480){const l=s/760;return Number(zo(l,n,.82).toFixed(2))}const i=e/960,c=s/720;return Number(zo(Math.min(i,c),n,a).toFixed(2))}function mt(e){return Wa(e)}function ks(e){return mc(e).join(" · ")}function Ac(e){if(e.lastMessagePreview)return e.lastMessagePreview;const s=[...e.messages].reverse().find(n=>!(n!=null&&n._localId))||e.messages[e.messages.length-1],r=Pa(s==null?void 0:s.content);return r||(e.title?e.title:ks(e)||"No messages yet")}function Mc(e,s){const{isReconnecting:r,isConnecting:n}=Fs(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Zm(e,s){const r=["Chat",...mc(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ps(e){return Mc(e)||ks(e)}function ep(e){return`${mt(e)} · ${Ac(e)}`}function tp(e){const s=nn(e),r=s?dt(s):Ks(e);return`${mt(e)} — ${r||"Agent"}`}function sp(e){return Ks(e)||"CLI"}function Tc(e){return uc(e)}function Lc(e){return e?`Remote · ${mt(e)||e.workspaceName||"Session"}`:"Remote"}function rp({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var E;vs();const{sendData:u}=Lt(),[f,d]=o.useState(!1),[b,v]=o.useState(1),[w,A]=o.useState({width:0,height:0}),m=o.useRef(null),p=o.useRef(!1),x=o.useRef(0),h=o.useRef(!1),S=o.useRef(""),_=o.useRef(null),j=o.useRef(!1),C=o.useRef(null),k=e.tabKey,y=e.sessionId||"",g=e.daemonId||((E=e.routeId)==null?void 0:E.split(":")[0])||e.routeId||"",$=Fa(e),L=f?i||$:"Runtime terminal unavailable",M=Cc,R=Ic,O=()=>Qm(w.width,w.height,{minScale:M,maxScale:R}),F=()=>{var B,U;x.current=0,h.current=!1,S.current="",_.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;x.current=0,h.current=!1,S.current="",_.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,W;U>0&&x.current>=U||U===0&&h.current||(x.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&&((W=r.current)==null||W.write(B)))};return o.useEffect(()=>{F()},[y]),o.useEffect(()=>{var U;if(!y)return;const B=((U=rt.onRuntimeEvent)==null?void 0:U.call(rt,y,V=>{if(!(!V||V.sessionId!==y)){if(V.type==="runtime_snapshot"){if(!c){_.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"&&(x.current=Math.max(x.current,V.seq)),f||d(!0),typeof V.data=="string"&&G(V.data);return}if(V.type==="session_cleared"){if(!c){j.current=!0,S.current="",_.current=null;return}N()}}}))||(()=>{});return()=>{B()}},[g,y,r,c,f]),o.useEffect(()=>{var U,V,ae;if(!y)return;g&&((U=rt.getState)==null?void 0:U.call(rt,g))==="connected"&&(d(!0),(V=rt.requestRuntimeSnapshot)==null||V.call(rt,g,y).catch(()=>{}));const B=(ae=rt.onStateChange)==null?void 0:ae.call(rt,(we,be)=>{var Y;we!==g||be!=="connected"||(d(!0),(Y=rt.requestRuntimeSnapshot)==null||Y.call(rt,g,y).catch(()=>{}))});return()=>{B==null||B()}},[g,y,r]),o.useEffect(()=>{s&&F()},[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),W=Math.round(be);return Y.width===he&&Y.height===W?Y:{width:he,height:W}})});return U.observe(B),()=>U.disconnect()},[]),o.useEffect(()=>{(()=>{p.current||v(O())})()},[w.height,w.width]),o.useEffect(()=>{var U,V;if(!c)return;j.current&&(j.current=!1,N());const B=_.current;B&&(_.current=null,I(B.text,B.seq,B.cols,B.rows)),g&&y&&((U=rt.getState)==null?void 0:U.call(rt,g))==="connected"&&((V=rt.requestRuntimeSnapshot)==null||V.call(rt,g,y).catch(()=>{})),S.current&&C.current===null&&(C.current=requestAnimationFrame(P)),requestAnimationFrame(()=>{var ae;(ae=r.current)==null||ae.bumpResize()})},[g,c,y]),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!==y||f&&((ae=r.current)==null||ae.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",B),()=>{window.removeEventListener("adhdev:fit-cli-terminal",B)}},[f,y,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:()=>{p.current=!0,v(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:()=>{p.current=!0,v(B=>Math.min(R,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/b}%`,height:`${100/b}%`,transform:`scale(${b})`,transformOrigin:"top left"},children:t.jsx(qi,{ref:r,readOnly:!f||!c,sizingMode:"measured",onInput:B=>{f&&(u==null||u(g,{type:"pty_input",sessionId:y,targetSessionId:y,data:B}))}})})}),!f&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),t.jsx(cc,{contextKey:e.tabKey,panelLabel:mt(e),isSending:a,isBusy:!f||!!$,statusMessage:L,onSend:async B=>!f||$?!1:n(B),isActive:l&&c,showControlsToggle:!1})]})}function np({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 ap({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 za({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(pn,{size:n}):t.jsx(Zt,{size:n})})}function op({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 Vo({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Go({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=hn(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 ip({activeConv:e,wsStatus:s,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:f,hiddenConversations:d=[],onShowConversation:b,onShowAllHidden:v,onResetPanelsToMain:w,inboxOpen:A,onInboxOpenChange:m,hiddenOpen:p,onHiddenOpenChange:x,onOpenNewSession:h,actionShortcuts:S,notifications:_,notificationUnreadCount:j,onOpenNotification:C,onMarkNotificationRead:k,onMarkNotificationUnread:y,onDeleteNotification:g}){const{ides:$,p2pStates:L={}}=vs(),M=!!e&&nt(e)&&!Ze(e),R=!!e&&Ze(e),O=l||(e?lc(e)?"terminal":"chat":null),[F,N]=o.useState(!1),P=o.useRef(null),G=o.useRef(null),I=$.filter(W=>W.type==="adhdev-daemon"),E=op({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(()=>_.filter(W=>!W.readAt),[_]),we=o.useMemo(()=>_.filter(W=>!!W.readAt),[_]),be=o.useMemo(()=>ae.slice(0,9),[ae]),Y=j;o.useEffect(()=>{if(!A)return;const W=X=>{var oe;(oe=P.current)!=null&&oe.contains(X.target)||m(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[A,m]),o.useEffect(()=>{if(!p)return;const W=X=>{var oe;(oe=G.current)!=null&&oe.contains(X.target)||x(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[p,x]),o.useEffect(()=>{if(!p&&!A)return;const W=X=>{if(!X.altKey)return;const oe=X.code.match(/^Digit([1-9])$/);if(!oe)return;const le=Number(oe[1])-1,de=p?d[le]:void 0,Se=A?be[le]:void 0;if(!(!de&&!Se)){if(X.preventDefault(),X.stopPropagation(),de){b==null||b(de),x(!1);return}Se&&(C(Se),m(!1))}};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[d,p,A,be,x,m,C,b]);const he=W=>{if(!W)return;const X=n.find(oe=>oe.tabKey===W);X&&(f==null||f(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(Zt,{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(Kd,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(M||R||!Ze(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:ks(e)||mt(e),children:mt(e)}),(M||R)&&c&&t.jsxs(t.Fragment,{children:[M&&u&&O&&t.jsx(za,{mode:O,onChange:u,compact:!0}),t.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:R?"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(La,{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${F?" is-drop-target":""}`,ref:G,onDragEnter:W=>{W.dataTransfer.types.includes("text/tab-key")&&(W.preventDefault(),N(!0))},onDragOver:W=>{W.dataTransfer.types.includes("text/tab-key")&&(W.preventDefault(),W.dataTransfer.dropEffect="move",N(!0))},onDragLeave:W=>{W.currentTarget.contains(W.relatedTarget)||N(!1)},onDrop:W=>{const X=W.dataTransfer.getData("text/tab-key");W.preventDefault(),N(!1),he(X)},children:[t.jsxs("button",{type:"button",onClick:()=>x(!p),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(Ui,{size:16}),d.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),p&&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(Vo,{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&&v&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{v(),x(!1)},children:"Restore all"})]})]}),e&&f&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>f(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(Vo,{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(W=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{b==null||b(W),x(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:mt(W)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(W)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(W)+1]}):null,ks(W)]})]},W.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(fn,{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(W=>t.jsx(Go,{notification:W,shortcutIndex:be.indexOf(W)>=0?be.indexOf(W)+1:void 0,onOpen:()=>C(W),onMarkRead:()=>k(W.id),onMarkUnread:()=>y(W.id),onDelete:()=>g(W.id)},W.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(W=>t.jsx(Go,{notification:W,onOpen:()=>C(W),onMarkRead:()=>k(W.id),onMarkUnread:()=>y(W.id),onDelete:()=>g(W.id)},W.id))]}),_.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 cp(e,s){return String(e||"")!==String(s||"")}function lp(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&&!rc(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
32
|
-
`).includes(a)))}function dp(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 Rc(e,s={}){return dp(lp(e,s),s.sortMode||"recent")}function on(e){return e?"Resume saved history":"Start fresh"}function Va(e){return e?"Resuming saved history…":"Starting fresh…"}function up(){return"Start fresh"}function _c(e,s=!1){return e==="cli"?on(s):e==="ide"?"Start IDE":"Start ACP session"}function Pc(e,s=!1){return e==="cli"?Va(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function mp(){return"Recover hosted runtime"}function pp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function fp(){return"Open saved history"}function hp(){return"Saved History"}function Ga(){return"Use saved history when you want continuity in the same provider conversation."}function xp(){return"No saved history found yet."}function bp(){return"Refresh saved history"}function gp(){return"Refreshing saved history…"}function fs(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function hs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Bs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Os(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function qa(e){return`Resume saved history with ${e}?`}function Ya(){return"Review or change the target workspace before resuming saved history."}function yp(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 Xa({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:f,onNewChat:d,onSwitchSession:b,onRefreshHistory:v,onResumeSavedSession:w}){var y;const A=s.find(g=>g.id===e.routeId),m=(A==null?void 0:A.chats)||[],p=(y=A==null?void 0:A.activeChat)==null?void 0:y.id,x=nt(e)&&!Ze(e),[h,S]=o.useState(()=>wt()),_=l||h,j=g=>{if(u){u(g);return}S(g)},C=o.useMemo(()=>Rc(a,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.workspaceQuery,a]),k=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick:f,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[t.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:x?hp():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:tp(e)}),x&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ga()})]}),t.jsx("button",{onClick:f,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(It,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!x&&t.jsx("button",{onClick:d,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),x?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:_.textQuery,onChange:g=>j({..._,textQuery:g.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:_.workspaceQuery,onChange:g=>j({..._,workspaceQuery:g.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:_.modelQuery,onChange:g=>j({..._,modelQuery:g.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsxs("select",{value:_.sortMode,onChange:g=>j({..._,sortMode:g.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:_.resumableOnly,onChange:g=>j({..._,resumableOnly:g.target.checked})}),"Resume-ready only"]})]}),C.map(g=>{const $=e.providerSessionId===g.providerSessionId,L=$||!g.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{L||!w||w(g)},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:g.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:g.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:yp(g.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:g.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[g.workspace||"Workspace unknown",js(g.summaryMetadata)?` · ${js(g.summaryMetadata)}`:"",g.messageCount>0?` · ${g.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:$?"ACTIVE":g.canResume?c===g.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},g.id)})]}):m.map(g=>t.jsxs("div",{onClick:()=>{b(e.routeId,g.id),f()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${p===g.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${p===g.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:g.title||"Untitled Session"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[g.id.substring(0,12),"..."]}),p===g.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},g.id)),(x&&!i&&C.length===0||!x&&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(Hd,{size:32})}),t.jsx("div",{className:"text-[13px]",children:x?a.length>0?"No saved history matches these filters.":xp():"No recent chat sessions found."})]}),x&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:gp()})})]}),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:v,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(Hs,{size:13})," ",x?bp():"Refresh History"]})})})]})]});return typeof document>"u"?k:ir.createPortal(k,document.body)}const qo={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 Dc({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=qo[n.type]||qo.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 vp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function wp(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function jp(e){return e.sessionId||e.instanceId||e.agentType}function Kn(e,s){return e||s}function Ec(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=_t(r,{fallbackId:r.id}));return s}function $c(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 Ja(e,s,r={}){return kp(e,s,$c(e,r))}function kp(e,s,r={}){var b,v,w,A,m,p;const n=[],a=r.machineName,i=r.connectionState,c=wp(e),l=Iu(e.type,{agentName:e.cliName}),u=nt(e)||Ze(e)?l:dt(e.type),f=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var h,S;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||dt(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((h=x.activeChat)==null?void 0:h.messages)||[],activeModal:((S=x.activeChat)==null?void 0:S.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,surfaceHidden:x.surfaceHidden}}):[],d=vp(e);if(d){const x=e.sessionId||e.instanceId,h=l,S=(b=e.activeChat)==null?void 0:b.activeModal,_=S&&Array.isArray(S.buttons)&&S.buttons.length>0,j=St((v=e.activeChat)==null?void 0:v.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 y=(p=e.activeChat)==null?void 0:p.id,g=e.chats;if(y&&Array.isArray(g)&&g.length>0){const R=g.find(O=>O.id===y||O.id&&String(O.id)===String(y));R!=null&&R.title&&String(R.title).trim()&&(k=String(R.title).trim())}const $=(nt(e)||Ze(e),e.type),L=(nt(e)||Ze(e))&&Ko(k,h,$)?"":k,M=C.messages||[];n.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:nt(e)?e.mode||"terminal":"chat",agentName:h,agentType:$,status:j,title:L,messages:M,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:_?S.buttons:void 0,modalMessage:_?S.message:void 0,streamSource:"native",tabKey:Kn(x,e.id),machineName:a,connectionState:i})}if(d&&(nt(e)||Ze(e)))return n;for(const x of f){const h=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,S=Au(x),_=jp(x),j=`${e.id}:${_}`,C=x.title&&String(x.title).trim()||"",k=Ko(C,x.agentName,x.agentType)?"":C,y=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||y.length>0||h||k||!["idle","panel_hidden","disconnected","not_monitored"].includes(S))&&n.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:S,title:k,messages:y,hostIdeType:e.type,workspaceName:c,displayPrimary:k||c||x.agentName||u,displaySecondary:`${u} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,modalButtons:h?x.activeModal.buttons:void 0,modalMessage:h?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Kn(x.sessionId||x.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:Kn(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function Sp(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 Np(e,s){const r=Sp(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Kc=[{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:"🏄"}],Bc=[{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:"🧩"}],Oc=[{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:"🟠"}],Cp=Kc,Ip=Bc,Ap=Oc;function Ss(...e){return dd(ud(e))}function Mp({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:Ss("dashboard-header",i),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&t.jsx("div",{className:"flex gap-2",children:a})]})}function Wc({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(Mp,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:Ss("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Rt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:Ss("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",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 Hc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:Ss("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 Tp={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"},Lp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Pr({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:Ss("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Tp[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:Lp[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 Rp={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"},_p={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Pp({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:Ss("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Rp[e],r),children:[t.jsx("span",{className:Ss("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",_p[e])}),n]})}const ba="adhdev:themechange";function Dp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Is(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function As(e){return e==="system"?Dp():e}function Fc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function qr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(ba,{detail:{preference:e,theme:s}}))}function Ep(){const e=Is(),s=As(e);Fc(s),qr(e,s)}function Qa(){const[e,s]=o.useState(Is),[r,n]=o.useState(()=>As(Is()));o.useEffect(()=>{Fc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const f=u.matches?"light":"dark";n(f),qr("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const f=u.detail||{},d=f.preference,b=f.theme;s(d==="dark"||d==="light"||d==="system"?d:Is()),n(b==="dark"||b==="light"?b:As(Is()))},l=u=>{if(u.key!=="theme")return;const f=Is(),d=As(f);s(f),n(d)};return window.addEventListener(ba,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ba,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=As(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}qr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=As(l);n(u);try{localStorage.setItem("theme",l)}catch{}return qr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Yo={dark:"Dark",light:"Light",system:"System"};function $p({collapsed:e}){const{preference:s,cycleTheme:r}=Qa(),n=s==="dark"?t.jsx(Ud,{size:16}):s==="light"?t.jsx(Fd,{size:16}):t.jsx(zd,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Yo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Yo[s]})]})}function ds({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 Kp({onPrefChange:e}){const[s,r]=Ku(),[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(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(fn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:c=>i("globalEnabled",c)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(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:()=>{oc().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(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Vd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Gd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(lr,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function cn(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Bp(e,s){const r=cn(e),n=cn(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 Uc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function nr(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Bp(r,s)>=0)return!1;const n=cn(r),a=cn(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Op(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Bn(e,s){return e instanceof Error?e.message:s}function Wp({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(Hc,{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(Fp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Xo({title:e,message:s,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return ir.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),t.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function Hp(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Cp,...Ip,...Ap].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 Fp({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var O,F;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[f,d]=o.useState(null),[b,v]=o.useState("idle"),[w,A]=o.useState(""),m=e.version||null,p=((O=e.machine)==null?void 0:O.platform)||((F=e.system)==null?void 0:F.platform)||"",x=_t(e,{fallbackId:e.id}),h=p==="win32"?"🪟":p==="darwin"?"🍎":"🐧",S=s.filter(N=>N.daemonId===e.id&&N.transport==="cdp-page"),_=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=Op(await r(e.id,"daemon_upgrade",{}));N.alreadyLatest?(c("done"),u(`Already on v${N.version||"latest"}.`)):N.upgraded||N.success?(c("done"),u(`Upgrade to v${N.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(N.error||"Upgrade failed"))}catch(N){c("error"),u(Bn(N,"Connection lost during upgrade"))}}},y=async()=>{if(d(null),!!n){v("loading");try{await n(e.id),v("done"),A("Machine disconnected.")}catch(N){v("error"),A(Bn(N,"Failed to disconnect"))}}},g=async()=>{if(d(null),!!a){v("loading");try{await a(e.id),v("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(N){v("error"),A(Bn(N,"Failed to revoke token"))}}},$="0.8.97",L=Uc(e,$),M=nr(e,$),R=S.length+_.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:x}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),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:b==="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:b==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(Pp,{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&&R>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),R>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[S.map(N=>{const P=Hp(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)}),_.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"||b==="error"?"text-red-400":i==="done"||b==="done"?"text-green-400":"text-text-muted"}`,children:w||l})]}),f==="disconnect"&&t.jsx(Xo,{title:"🔌 Disconnect Machine",message:`Disconnect "${x}" from ADHDev?
|
|
33
|
-
|
|
34
|
-
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
35
|
-
|
|
36
|
-
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:y,onCancel:()=>d(null)}),f==="revoke"&&t.jsx(Xo,{title:"⚠️ Remove Machine",message:`Remove "${x}" from your dashboard?
|
|
37
|
-
|
|
38
|
-
This will:
|
|
39
|
-
• Immediately disconnect the machine
|
|
40
|
-
• Delete the machine registration
|
|
41
|
-
• Require restarting ADHDev on that machine
|
|
42
|
-
|
|
43
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:g,onCancel:()=>d(null)})]})}const Up=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function zp(){const{preference:e,setPreference:s}=Qa();return t.jsx("div",{className:"flex gap-2",children:Up.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 Vp(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 Gp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function On(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function Jo(e){const{r:s,g:r,b:n}=Gp(e);return .2126*On(s)+.7152*On(r)+.0722*On(n)}function Qo(e,s){const r=Jo(e),n=Jo(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function zc(e){const s=Vp(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return Qo(s,r)>=Qo(s,n)?r:n}const ga={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},ya={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},qp=[{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"}}}],Vc="adhdev-chat-theme",Gc="adhdev-chat-theme-custom";function Yr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Vc)||"ember"}catch{return"ember"}}function Ht(e){try{const s=localStorage.getItem(Gc);if(s){const r=JSON.parse(s);return{...e==="dark"?ga:ya,...r[e]}}}catch{}return e==="dark"?ga:ya}function Dr(e,s){try{localStorage.setItem(Gc,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 ln(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),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 Yp={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ar(e,s){var a;const r=(a=Yp[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",ln(r,24)),n.style.setProperty("--accent-on-primary",zc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${ln(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 xs(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",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",ln(e.accentColor,30)),s.style.setProperty("--accent-on-primary",zc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${ln(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 Za(){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 Xp(e){try{localStorage.setItem(Vc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=bs()?"dark":"light";xs(Ht(s))}else Za(),ar(e,bs()?"dark":"light")}function Jp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Yr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=bs()?"dark":"light";xs(Ht(s))}else Za(),ar(e,bs()?"dark":"light")}function bs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function 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 Ys({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 Qp({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 f={...u,[c]:l},b=Ht(r==="dark"?"light":"dark");return r==="dark"?Dr(f,b):Dr(b,f),xs(f),s(f),f})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(Ys,{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(Ys,{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(Ys,{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(Ys,{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(Ys,{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?ga:ya,u=Ht(e?"light":"dark");e?Dr(c,u):Dr(u,c),a(c),xs(c),s(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function Zp(){const[e,s]=o.useState(Yr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Ht("dark"));o.useEffect(()=>{n(bs());const u=new MutationObserver(()=>{const b=bs();n(b);const v=Yr();v==="custom"?xs(Ht(b?"dark":"light")):ar(v,b?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const b=bs();n(b);const v=Yr();v==="custom"?xs(Ht(b?"dark":"light")):ar(v,b?"dark":"light")};return f.addEventListener("change",d),()=>{u.disconnect(),f.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?xs(Ht(r?"dark":"light")):(Za(),ar(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Ht(r?"dark":"light"))},[r]);const c=u=>{s(u),Xp(u)},l=[...qp,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const f=e===u.id,d=r?u.preview.dark:u.preview.light,b=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:b},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[f&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&t.jsx(Qp,{dark:r,onColorsChange:u=>i(u)})]})}const eo="adhdev_mobileDashboardMode_v1",va="adhdev:mobile-dashboard-mode-change";function to(){try{return localStorage.getItem(eo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ef(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??to())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==eo||s()};return window.addEventListener(va,r),window.addEventListener("storage",n),()=>{window.removeEventListener(va,r),window.removeEventListener("storage",n)}}function tf(e){try{localStorage.setItem(eo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(va,{detail:e}))}function sf(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(to()==="chat")},[]),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Zt,{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),tf(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Wn=new Map,Zo=new Map;function rf(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 nf(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 qc(){const{sendCommand:e}=Lt(),{injectEntries:s,getIdes:r}=cr();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??km,c=Zo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Wn.get(n);if(l)return l;const u=(async()=>{const f=await e(n,"get_machine_runtime_stats"),d=rf(f);if(!d)return;const b=r().find(w=>w.id===n),v=nf(b,n,d.machine,d.timestamp||Date.now());s([v]),Zo.set(n,Date.now())})().finally(()=>{Wn.delete(n)});return Wn.set(n,u),u},[r,s,e])}function af(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 of(e,s){const{sendData:r}=Lt(),{injectEntries:n,getIdes:a}=cr(),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=>as.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},d=>{const b=a().find(w=>w.id===u),v=af(b,u,d);n([v])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function Yc(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=as.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Im):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 cf(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Xc(e){const{sendData:s}=Lt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=cf(e);if(!a||!e.sessionId||!s){n({});return}const i=as.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}),Ps.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const Jc="adhdev_hiddenTabs";function lf(){try{const e=localStorage.getItem(Jc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function Ns(e){try{localStorage.setItem(Jc,JSON.stringify([...e]))}catch{}}function Er(e){return Ea(e)}function so(e,s){return ss(s).some(r=>e.has(r))}function df(){const[e,s]=o.useState(lf),r=o.useCallback(f=>{s(d=>{const b=new Set(d);return b.has(f)?b.delete(f):b.add(f),Ns(b),b})},[]),n=o.useCallback(f=>{s(d=>{if(d.has(f))return d;const b=new Set(d);return b.add(f),Ns(b),b})},[]),a=o.useCallback(f=>{s(d=>{if(!d.has(f))return d;const b=new Set(d);return b.delete(f),Ns(b),b})},[]),i=o.useCallback(()=>{s(f=>{if(f.size===0)return f;const d=new Set;return Ns(d),d})},[]),c=o.useCallback((f,d)=>{s(b=>{const v=new Set(b);for(const w of d)v.add(w);return Ns(v),v})},[]),l=o.useCallback((f,d)=>{s(b=>{const v=new Set(b);for(const w of d)v.delete(w);return Ns(v),v})},[]),u=o.useCallback(f=>so(e,f),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function Qc(e){return e instanceof Error?e.message:String(e||"")}function ro(e){const s=Qc(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 no(e){const s=Qc(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function ei(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 uf(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=ei(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>ei(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Zc(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 mf(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))Zc(s,a)===i&&(delete n[a],r=!0);return r?n:e}function pf({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{oc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Tc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Wu(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),f={};for(const[d,b]of Object.entries(l))u-b<5e3&&(f[d]=b);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(f=>f.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function ff(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 Hn(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 hf(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 ti(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?hf(Pa(r.content)):"";return[e.id||"",e.title||"",e.status||"",s.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function xf(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||""),ti(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),ti(r.activeChat)].join(":"))].join("|")}function bf(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 gf(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 yf(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 vf(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of ss({routeId:n.routeId}))r.set(i,a);for(const i of ss({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of ss({tabKey:n.tabKey}))r.set(i,n)}return r}function wf(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function jf(e){const s=wf(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=Pa(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function kf({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>ff(e),[e]),c=o.useMemo(()=>Ec(e),[e]),l=o.useRef([]),u=o.useRef([]),f=o.useRef([]),d=o.useRef(new Map),b=o.useRef(new Map),v=o.useMemo(()=>{const j=new Map,C=[];for(const $ of i){const{connectionState:L="new",machineName:M}=$c($,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),R=gf($,r),O=xf($),F=d.current.get($.id);if(F&&F.ide===$&&F.sourceSignature===O&&F.connectionState===L&&F.machineName===M&&yf(F.localRefs,R)){j.set($.id,F),C.push(...F.conversations);continue}const N=Ja($,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),P={ide:$,sourceSignature:O,connectionState:L,machineName:M,localRefs:R,conversations:N};j.set($.id,P),C.push(...N)}d.current=j;const k=new Map,y=$=>{const L=jf($),M=b.current.get($.tabKey);if(M&&M.signature===L)return k.set($.tabKey,M),M.timestamp;const R={signature:L,timestamp:fc($)||(M==null?void 0:M.timestamp)||0};return k.set($.tabKey,R),R.timestamp},g=[...C].sort(($,L)=>hc($,L,y));return b.current=k,g},[i,r,s,c]),w=o.useMemo(()=>{const j=bf(v,n);return Hn(l.current,j)?l.current:(l.current=j,j)},[v,n]),A=o.useMemo(()=>{const j=new Map,C=Array.from(new Set(w.map(k=>k.routeId)));for(const k of C){const y=Ft(w,k);y&&j.set(k,y)}return j},[w]),m=o.useMemo(()=>{const j=new Map;for(const C of w){const k=A.get(C.routeId),y=C.streamSource==="native"&&k?k:C;for(const g of ss({providerSessionId:C.providerSessionId,sessionId:C.sessionId}))j.set(g,y)}return j},[w,A]),p=o.useMemo(()=>vf(w,A),[w,A]),x=o.useCallback(j=>{if(j)return m.get(j)},[m]),h=o.useCallback(j=>{if(j)return p.get(j)},[p]),S=o.useMemo(()=>{const j=w.filter(C=>!so(a,C));return Hn(u.current,j)?u.current:(u.current=j,j)},[w,a]),_=o.useMemo(()=>{const j=S.map(C=>C.tabKey);return Hn(f.current,j)?f.current:(f.current=j,j)},[S]);return{chatIdes:i,conversations:w,visibleConversations:S,visibleTabKeys:_,resolveConversationBySessionId:x,resolveConversationByTarget:h}}function Sf({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 Nf({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(v=>v.message===u.message&&u.timestamp-v.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 f=u.duration||5e3;setTimeout(()=>r(d=>d.filter(b=>b.id!==u.id)),f)}),c=at.onSystemMessage((u,f)=>{var w,A;const d=a(u),b=(w=f._localId)==null?void 0:w.startsWith("sys_approval_"),v=!!(d&&(d.status==="waiting_approval"||(A=d.modalButtons)!=null&&A.length||d.modalMessage));b&&v||n(m=>({...m,[u]:[...m[u]||[],f]}))}),l=at.onClearSystemMessage((u,f)=>{n(d=>{var b;return(b=d[u])!=null&&b.length?{...d,[u]:d[u].filter(v=>{var w;return!(v.role==="system"&&((w=v._localId)!=null&&w.startsWith(f)))})}:d})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=Nc.on("status_event",c=>{at.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var p;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 f=u.targetSessionId||u.targetKey||u.daemonId,d=a(f),b=(d==null?void 0:d.routeId)||u.daemonId;if(!b)return;const v=Number(u.buttonIndex),w=u.button||((p=d==null?void 0:d.modalButtons)==null?void 0:p[v])||"Approve",A=String(w).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),m=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(b,"resolve_action",{action:m?"approve":"reject",button:w,...Number.isFinite(v)&&{buttonIndex:v},...(d==null?void 0:d.sessionId)&&{targetSessionId:d.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",i)}},[a,s])}const Cf="adhdev_dashboardLayout_v1",If="adhdev_dashboardDockview_v1",Af="adhdev_dashboardDockviewHiddenRestore_v1",Xs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function ao(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function el(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function tl(e){return`${Cf}:${e}`}function Mf(e){const s=tl(e);return ao(s,null)}function Tf(e,s){try{const r=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,n=tl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function sl(e){return`${If}:${e}`}function Lf(e){const s=sl(e);return ao(s,null)}function Rf(e,s){try{const r=sl(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function rl(e){return`${Af}:${e}`}function _f(e){const s=rl(e);return ao(s,{})}function Pf(e,s){try{const r=rl(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Df(){return{groupAssignments:[...Xs.groupAssignments],focusedGroup:Xs.focusedGroup,groupActiveTabIds:{...Xs.groupActiveTabIds},groupTabOrders:{...Xs.groupTabOrders},groupSizes:[...Xs.groupSizes]}}function Ef(){const[e]=o.useState(()=>el(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[f,d]=o.useState([]),[b,v]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,A]=o.useState(!1),m=o.useCallback(()=>{if(w)return;const p=Mf(e)??Df();r(new Map(p.groupAssignments)),a(p.focusedGroup),c(p.groupActiveTabIds),u(p.groupTabOrders),d(p.groupSizes),A(!0)},[w,e]);return o.useEffect(()=>{w&&Tf(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:f})},[w,e,s,n,i,l,f]),o.useEffect(()=>{const p=window.matchMedia("(max-width: 767px)"),x=h=>v(h.matches);return p.addEventListener("change",x),()=>p.removeEventListener("change",x)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:f,setGroupSizes:d,isMobile:b,hasHydratedStoredLayout:w,hydrateStoredLayout:m}}function $f(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Da(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Kf({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:f,activeConv:d,isRefreshingHistory:b,ides:v,handleRefreshHistory:w}){const A=o.useRef(!1),m=o.useRef(!1),p=o.useRef(null),x=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(_=>({..._,[S]:h.tabKey})),l(S),A.current=!0,m.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),u(_=>{const j=new URLSearchParams(_);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(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(m.current||a)&&(i(),m.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!f){x.current=!1;return}if(!d||x.current||b)return;const h=v.find(S=>S.id===d.routeId);h&&(!h.chats||h.chats.length===0||$f(h.chats,d))&&(x.current=!0,w())},[f,d,b,v,w]),o.useEffect(()=>{if(!d)return;let h=null,S=0,_=-1,j=0;const C=()=>{h=null;const k=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(g=>g.offsetParent!==null);if(k.length===0){S<18&&(S+=1,h=requestAnimationFrame(C));return}let y=0;for(const g of k)g.scrollTop=g.scrollHeight,y+=g.scrollHeight;y===_?j+=1:(j=0,_=y),S+=1,!(j>=2||S>=18)&&(h=requestAnimationFrame(C))};return h=requestAnimationFrame(C),()=>{h!=null&&cancelAnimationFrame(h)}},[d==null?void 0:d.tabKey])}function Bf({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,f]=o.useState(null),[d,b]=o.useState(null),v=o.useMemo(()=>{if(e||!n)return null;const x=l(n);return x&&!nt(x)&&!Ze(x)?x:null},[e,n,l]),w=o.useMemo(()=>{const x=u==null?void 0:u.routeId;if(!x)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)===x?h:Ft(i,x)},[i,u,a]),A=o.useMemo(()=>{if(w)return c.find(x=>x.id===w.routeId)},[c,w]);o.useEffect(()=>{v&&(f({routeId:v.routeId,tabKey:Wo(v)}),b(v),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,v]);const m=o.useCallback(x=>{x&&(f({routeId:x.routeId,tabKey:Wo(x)}),b(x))},[]),p=o.useCallback(()=>{f(null),b(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:A,remoteDialogActiveConv:d,setRemoteDialogActiveConv:b,openRemoteDialog:m,closeRemoteDialog:p}}function Fn(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=Da(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function si({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=o.useState(!1),[f,d]=o.useState(!1),b=o.useCallback(async m=>{try{await e("standalone","launch_ide",{ideType:m,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),v=o.useCallback(async(m,p)=>{try{const x=m||(s==null?void 0:s.daemonId)||"",h=await e(x,"switch_chat",{id:p,sessionId:p,...Rs(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"?qs(a,"⚠️ Session tab not found — try refreshing history"):typeof S=="string"&&S.startsWith("error:")?qs(a,`⚠️ Switch error: ${S}`):qs(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),qs(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[s,e,a]),w=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const m=mr(s);await e(m,"new_chat",{...Rs(s)}),c(p=>({...p,[s.tabKey]:Date.now()})),i(p=>({...p,[s.tabKey]:[]}))}catch(m){console.error("New chat failed",m)}finally{u(!1)}}},[s,l,e,c,i]),A=o.useCallback(async()=>{var m,p;if(!(!s||f)){d(!0);try{const x=mr(s),h=async()=>e(x,"list_chats",{forceExpand:!0,...Rs(s)});let S=await h(),_=(S==null?void 0:S.chats)||((m=S==null?void 0:S.result)==null?void 0:m.chats);Fn(_,s)&&(await new Promise(j=>setTimeout(j,450)),S=await h(),_=(S==null?void 0:S.chats)||((p=S==null?void 0:S.result)==null?void 0:p.chats)),S!=null&&S.success&&Array.isArray(_)&&(n(s.routeId,_),Fn(_,s)&&!Fn(r,s)&&qs(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{d(!1)}}},[s,r,f,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:f,handleLaunchIde:b,handleSwitchSession:v,handleNewChat:w,handleRefreshHistory:A}}function Of(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 Wf(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function ri(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 $r(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 ni(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 Hf(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 Ff(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 ai(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 oi(e){return Array(e).fill(100/e)}function Uf({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:f}){const d=o.useRef(null),b=o.useMemo(()=>$r(e,f),[e,f]),v=b.assignments,w=o.useMemo(()=>l?1:b.groupCount,[b.groupCount,l]),A=w>1,m=o.useCallback((j,C)=>{s(k=>{const y=new Map($r(k,f).assignments);return C===0?y.delete(j):y.set(j,C),y}),n(k=>({...k,[C]:j})),r(C)},[s,f,n,r]),p=o.useCallback(j=>{s(C=>{const k=$r(C,f).assignments,y=new Map;for(const[g,$]of k)$!==j&&($>j?y.set(g,$-1):y.set(g,$));return y}),c(C=>{if(C.length<=1)return[];const k=[...C];k.splice(j,1);const y=k.reduce((g,$)=>g+$,0);return y>0?k.map(g=>g/y*100):[]}),r(0)},[s,f,c,r]),x=o.useCallback((j,C)=>{C.preventDefault();const k=d.current;if(!k)return;const y=C.clientX,g=k.offsetWidth,$=i.length===w?[...i]:oi(w),L=R=>{const F=(R.clientX-y)/g*100,N=[...$];N[j]=Math.max(15,$[j]+F),N[j+1]=Math.max(15,$[j+1]-F),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 y=k==="left"?C:C+1;s(g=>{const $=$r(g,f).assignments,L=new Map;for(const M of u){const R=$.get(M.tabKey)??0,O=R>=y?R+1:R;O>0&&L.set(M.tabKey,O)}return y>0&&L.set(j,y),L}),c(g=>{const $=g.length===w?[...g]:oi(w),L=$[C]??100/w,M=Math.max(15,L/2),R=Math.max(15,L/2),O=[...$];O[C]=M,O.splice(y,0,R);const F=O.reduce((N,P)=>N+P,0);return O.map(N=>N/F*100)}),n(g=>{const $=ai(g,y);return $[y]=j,$}),a(g=>{const $=ai(g,y);return $[y]=[j],$}),r(y)},[w,s,f,u,c,n,a,r]);o.useEffect(()=>{Of(e,v)||s(v)},[e,v,s]),o.useEffect(()=>{const{mapping:j,usedGroups:C}=b;n(k=>{const y=ni(k,j);return ri(k,y)?k:y}),a(k=>{const y=ni(k,j);return ri(k,y)?k:y}),r(k=>{const y=l?0:Hf(k,C,j);return k===y?k:y}),c(k=>{const y=l?[]:Ff(k,C,b.groupCount);return Wf(k,y)?k:y})},[b,l,n,a,r,c]);const S=o.useMemo(()=>{const j=Array.from({length:w},()=>[]);for(const C of u){const k=v.get(C.tabKey)??0,y=Math.min(k,w-1);j[y].push(C)}return j},[u,v,w]),_=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:d,normalizedGroupAssignments:v,numGroups:w,isSplitMode:A,groupedConvs:S,moveTabToGroup:m,closeGroup:p,handleResizeStart:x,splitTabRelative:h,clearAllSplits:_}}function zf({ides:e,sendDaemonCommand:s}){const r="0.8.97",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Uc(d,r)).sort((d,b)=>Number(nr(b,r))-Number(nr(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>nr(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),f=o.useCallback(async d=>{var b,v;u(w=>({...w,[d]:"upgrading"}));try{const w=await s(d,"daemon_upgrade",{});(b=w==null?void 0:w.result)!=null&&b.upgraded||(v=w==null?void 0:w.result)!=null&&v.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:f}}const wa="adhdev_dashboard_notifications_v2",ja="adhdev_dashboard_notifications_v1",vr=80;function Xr(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function oo(e){return{...e,createdAt:Xr(e.createdAt),updatedAt:Xr(e.updatedAt,e.createdAt),lastEventAt:Xr(e.lastEventAt,e.updatedAt||e.createdAt)}}function Vf(e){const s=Ea(e);return s==="unknown:"?e.id:s}function ii(e){return[e.type,Xi(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Gf(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 f=ii({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(f))!=null&&c.forceUnread),b=xn(l,s,{notificationStateBySessionId:r}),v=b.inboxBucket==="needs_attention"?"needs_attention":b.inboxBucket==="task_complete"&&b.unread||(u==null?void 0:u.inboxBucket)==="task_complete"&&d?"task_complete":null;if(!v)continue;const w=Xr(l.lastMessageAt||(u==null?void 0:u.lastUpdated)||l.lastUpdated,a),A=v==="task_complete"?f:ii({type:v,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(oo({id:A,dedupKey:A,type:v,routeId:l.routeId,machineId:l.daemonId||l.routeId,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,title:uc(l),preview:dm(l),createdAt:w,updatedAt:w,lastEventAt:w}))}return i.sort((l,u)=>u.updatedAt-l.updatedAt)}function qf(e,s=vr){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Vf(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 Yf(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 Xf(e){return new Map(e.map(s=>[s.id,s]))}function nl(e,s,r=vr){const n=new Map;for(const i of s)n.set(i.id,i);const a=e.map(i=>{const c=oo(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 qf(a,r)}function Jf(e,s,r=vr){const n=new Set(nl(s,[],r).map(a=>a.id));return e.filter(a=>n.has(a.id)).slice(0,Math.max(0,r))}function Qf(e,s,r=Date.now()){const n=e.filter(a=>a.id!==s);return n.push({id:s,readAt:r}),n}function Zf(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,forceUnread:!0}),r}function eh(e,s,r,n=Date.now()){const a=e.filter(i=>{const c=s.find(l=>l.id===i.id);return!c||!dr(c,r)});for(const i of s)dr(i,r)&&a.push({id:i.id,readAt:n});return a}function th(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,deletedAt:Date.now()}),r}function sh(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function rh(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=ss(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 nh(){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(wa),r=s?JSON.parse(s):[];if(Array.isArray(r))return r.map(e).filter(n=>!!n)}catch{}try{const s=window.localStorage.getItem(ja),r=s?JSON.parse(s):[];return Array.isArray(r)?Yf(r.map(n=>oo(n)).filter(n=>!n.deletedAt)):[]}catch{return[]}}function ah(e){if(!(typeof window>"u"))try{const s=e.filter(r=>typeof r.readAt=="number"||typeof r.deletedAt=="number"||r.forceUnread===!0).slice(0,vr);if(s.length===0){window.localStorage.removeItem(wa),window.localStorage.removeItem(ja);return}window.localStorage.setItem(wa,JSON.stringify(s)),window.localStorage.removeItem(ja)}catch{}}function oh(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 ih(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=vr}=e,[a,i]=o.useState(()=>nh()),c=o.useMemo(()=>Xf(a),[a]),l=o.useMemo(()=>Gf(s,r,void 0,c),[s,r,c]),u=o.useMemo(()=>nl(l,a,n),[l,a,n]),f=o.useMemo(()=>rh(u),[u]);o.useEffect(()=>{i(m=>{const p=Jf(m,l,n);return oh(m,p)?m:p})},[l,n]),o.useEffect(()=>{ah(a)},[a]);const d=o.useMemo(()=>sh(u),[u]),b=o.useCallback((m,p)=>{i(x=>Qf(x,m,p))},[]),v=o.useCallback(m=>{i(p=>Zf(p,m))},[]),w=o.useCallback((m,p)=>{i(x=>eh(x,u,m,p))},[u]),A=o.useCallback(m=>{i(p=>th(p,m))},[]);return{notifications:u,unreadCount:d,notificationStateBySessionId:f,markRead:b,markUnread:v,markTargetRead:w,deleteNotification:A}}function al(){return"select_session"}function ch(){return"open_panel"}function lh({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function dh(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function ci(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function li(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function io(e){return e instanceof Error?e.message:String(e||"")}function di(e){const s=io(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function ui(e,s){const r=io(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function gn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[f,d]=o.useState(null),b=o.useRef(!1),v=o.useRef(null);o.useEffect(()=>{d(null)},[s==null?void 0:s.tabKey]);const w=o.useCallback(async x=>{if(!s)return!1;const h=x.trim(),S=Fa(s);if(lh({hasMessage:!!h,blockedMessage:S,sendInFlight:b.current}))return S&&d(S),!1;const _=Date.now(),j={tabKey:s.tabKey,message:h,timestamp:_};if(dh(v.current,j))return d(null),!0;b.current=!0,u(!0),d(null),v.current=j;const C=`${_}-${Math.random().toString(36).slice(2,8)}`,k={role:"user",content:h,timestamp:_,_localId:C},y=!0;r(g=>({...g,[j.tabKey]:[...g[j.tabKey]||[],k]}));try{const g=mr(s);if(!g)return v.current=ci(v.current,j),y&&r(M=>({...M,[j.tabKey]:(M[j.tabKey]||[]).filter(R=>R._localId!==C)})),d("Unable to send message right now."),!1;const $=await e(g,"send_chat",{message:h,...Rs(s)}),L=li($);if(y&&(L!=null&&L.deduplicated))return r(M=>({...M,[j.tabKey]:(M[j.tabKey]||[]).filter(R=>R._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(R=>{const O=R[j.tabKey];if(!O)return R;const F=O.filter(N=>N.timestamp>M);return F.length===O.length?R:{...R,[j.tabKey]:F}})},6e4),d(null),!0}catch(g){const $=io(g);return $.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",$):console.warn("Send blocked/failed",g),v.current=ci(v.current,j),r(L=>({...L,[j.tabKey]:(L[j.tabKey]||[]).filter(M=>M._localId!==C)})),d(Lm(g)),!1}finally{b.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(x){console.error("Relaunch failed",x)}},[s,e]),m=o.useCallback(async x=>{if(s)try{const S=(s.modalButtons||[]).indexOf(x),_=x.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),j=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_),C=mr(s);if(!C)return;const k=await e(C,"resolve_action",{button:x,action:j?"approve":"reject",...S>=0&&{buttonIndex:S},...Rs(s)}),y=li(k);y.success||n(g=>[...g,{routeId:s.tabKey,text:ui(x,y==null?void 0:y.error),timestamp:Date.now()}])}catch(h){di(h)||console.error("[ModalButton] Error:",h),n(S=>[...S,{routeId:s.tabKey,text:di(h)?ui(x,h):`❌ **${x}** error`,timestamp:Date.now()}])}},[s,e,n]),p=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,ch(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(x){console.error("Focus agent failed",x)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:f,isFocusingAgent:i,handleSendChat:w,handleRelaunch:A,handleModalButton:m,handleFocusAgent:p}}const co=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d=null,handleFocusAgent:b,isFocusingAgent:v,actionLogs:w,userName:A,scrollToBottomRequestNonce:m,isInputActive:p=!0}){const x=Xc(s),h=x.status||x.modalMessage||x.modalButtons?{...s,...x.status?{status:x.status}:{},...x.modalMessage!==void 0?{modalMessage:x.modalMessage}:{},...x.modalButtons!==void 0?{modalButtons:x.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Zi,{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(ws,{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(rp,{activeConv:h,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,isVisible:n,isInputActive:p})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(xa,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:b,isFocusingAgent:v,actionLogs:w,userName:A,scrollToBottomRequestNonce:m,isInputActive:p})})]}):t.jsx(xa,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:b,isFocusingAgent:v,actionLogs:w,userName:A,scrollToBottomRequestNonce:m,isInputActive:p})]})},(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 uh({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:f,onOpenNativeConversation:d,onOpenMachine:b,onOpenHistory:v,onOpenRemote:w,onHideConversation:A,onStopCli:m,cliViewMode:p,onSetCliViewMode:x,handleSendChat:h,handleFocusAgent:S,handleModalButton:_,handleRelaunch:j}){const C=o.useRef(null),k=nt(e)&&!s,y=k&&p==="terminal",g=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${g} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:f,type:"button","aria-label":"Back",children:t.jsx(Ma,{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(bc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>b(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[k&&p&&t.jsx(za,{mode:p,onChange:x,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:()=>v(e),type:"button",children:t.jsx(La,{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(co,{activeConv:e,clearToken:0,isCliTerminal:y,ideEntry:n,terminalRef:C,handleModalButton:_,handleRelaunch:j,handleSendChat:h,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:S,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const Un={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 mh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function ol(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(mh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Un[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:Un[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Un[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 il({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Pt},{key:"chats",label:"Chats",icon:Zt}];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 Kr({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Cs({children:e,className:s=""}){return t.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:e})}function Js({icon:e,title:s,subtitle:r,children:n}){return t.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[t.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Br({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:f}=Fs(e.conversation),d=mt(e.conversation),b=ks(e.conversation),v=Mc(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",p=c?"text-text-muted":"text-text-secondary",x=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:Qi(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${p}`,children:[b,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${S} animate-pulse`,children:"Reconnecting…"})]}):f?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):v==="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] ${x}`,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 mi({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 ph({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:f,onShowAllHidden:d,onOpenNewSession:b,onOpenMachine:v,onOpenSettings:w,onSectionChange:A,wsStatus:m="connected",isStandalone:p=!1}){const x=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,_=e==="machines"?"Machines":"Chats",j=p?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",C=p?"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:_}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[t.jsx(fn,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:t.jsx(mn,{size:18})})]})]})}),t.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${C}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:x?t.jsx(Js,{icon:t.jsx(mi,{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(Js,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:p?"Waiting for your daemon":"Connect your machines",subtitle:p?"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:!p&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(ol,{})})}):t.jsx(Cs,{children:c.map((k,y)=>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] ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>v(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(Kr,{title:"Needs attention",className:"mb-0"}),t.jsx(Cs,{children:s.map((k,y)=>t.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{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(Kr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(Cs,{children:r.map((k,y)=>t.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{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(Kr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(Cs,{children:n.map((k,y)=>t.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{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(Kr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(Cs,{children:a.map((k,y)=>t.jsx("div",{className:y>0?"border-t border-border-subtle/70":"",children:t.jsx(Br,{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."}):x?t.jsx(Js,{icon:t.jsx(mi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(Js,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Zt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(Js,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:d,children:"Restore all"})]}),t.jsx(Cs,{className:"bg-bg-secondary/25",children:i.map((k,y)=>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 ${y>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(k),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(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:ks(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"&&b&&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:b,"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(il,{section:e,onSectionChange:A})]})}function fh(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 cl(e){const s=[e.workspace||"Workspace unknown"],r=js(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=fh(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function yn(...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 hh(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 vn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=hh(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 xh(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 bh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function wn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=bh(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(f,d)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${d}`:f==="/"||f==="\\"?`${c}${d}`:`${f.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(i,f.name)})).sort((f,d)=>f.name.localeCompare(d.name)):[];return{path:i,directories:u}}function jn({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:f}){const[d,b]=o.useState(r);o.useEffect(()=>{b(r)},[r]);const v=xh(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:()=>{!v||a||u(v)},disabled:!v||a,children:[t.jsx(Ma,{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=>b(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(Ds,{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:()=>f(w||r),disabled:!w&&!r||a,children:c})]})]})})}function lo({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:f,argsValue:d,onArgsChange:b,showModelInput:v,modelValue:w,onModelChange:A,historyProviderNode:m,onConfirm:p,onCancel:x}){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:x,"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}`)),v&&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})]}),f&&b&&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=>b(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:x,disabled:u,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:p,disabled:u,children:[t.jsx(Ra,{size:14}),u?l:c]})]})]})})}function pi(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function gs(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?"⭐ ":""}${pi(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:pi(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(f=>f.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function gh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function yh(e){return[gh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function vh(e){return e.lastLaunchedAt?hn(e.lastLaunchedAt):""}function ll(e){return{metaText:yh(e),updatedLabel:vh(e)}}function zn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function wh({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var tt,Ct,ft,st;const c=gr(),[l,u]=o.useState(!1),f=(((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]),b=e.defaultWorkspaceId||null,[v,w]=o.useState(b||((Ct=d[0])==null?void 0:Ct.id)||""),[A,m]=o.useState(""),[p,x]=o.useState(""),[h,S]=o.useState([]),[_,j]=o.useState(!1),[C,k]=o.useState(""),[y,g]=o.useState(!1),[$,L]=o.useState(zn(f,s.length,r.length)),M=o.useRef(null),[R,O]=o.useState(null),F=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,W]=o.useState(()=>wt().workspaceQuery),[X,oe]=o.useState(()=>wt().modelQuery),[le,de]=o.useState(()=>wt().resumableOnly),[Se,ue]=o.useState(()=>wt().sortMode),[ce,re]=o.useState(!1),[pe,te]=o.useState(!1),Ne=o.useRef(null),ke=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const Ae=v==="__custom__"?A.trim():((ft=d.find(Re=>Re.id===v))==null?void 0:ft.path)||"",T=v==="__custom__"&&!!Ae&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),xe=v!=="__custom__"&&((st=d.find(Re=>Re.id===v))==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);x(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__"),g(!0);const Re=vn(e.platform,yn(A.trim(),xe,ve,e.defaultWorkspacePath,(Ge=d.find(Be=>Be.id===b))==null?void 0:Ge.path,d.map(Be=>Be.path)));Q(Re)},[A,b,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,F.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(cp(ke.current,Be)){const qe=wt();Y(qe.textQuery),W(qe.workspaceQuery),oe(qe.modelQuery),de(qe.resumableOnly),ue(qe.sortMode)}ke.current=Be,O(Re),Re.providerType&&i&&(re(!0),i(Re.providerType).then(qe=>we(qe||[])).catch(qe=>console.warn("Failed to load saved sessions",qe)).finally(()=>re(!1)))},[i,e.id]),Qe=o.useMemo(()=>Rc(ae,{textQuery:be,workspaceQuery:he,modelQuery:X,resumableOnly:le,sortMode:Se}),[X,le,ae,Se,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),O(null)}))},[]),et=o.useCallback(()=>{M.current=null,O(null)},[]),pt=o.useCallback(Re=>{F.current=Re,P(Re)},[]);return o.useEffect(()=>{var Re;Ne.current!==e.id&&(Ne.current=e.id,w(b||((Re=d[0])==null?void 0:Re.id)||"__custom__"),m(""),x(""),S([]),k(""),g(!1),Y(wt().textQuery),W(wt().workspaceQuery),oe(wt().modelQuery),de(wt().resumableOnly),ue(wt().sortMode),ke.current=null,L(zn(f,s.length,r.length)))},[r.length,s.length,b,f,e.id,d]),o.useEffect(()=>{var Re;v!=="__custom__"&&(v&&d.some(Ge=>Ge.id===v)||w(b||((Re=d[0])==null?void 0:Re.id)||"__custom__"))},[b,v,d]),o.useEffect(()=>{$==="ide"&&f||$==="cli"&&s.length>0||$==="acp"&&r.length>0||L(zn(f,s.length,r.length))},[$,r.length,s.length,f]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:f,workspaceRows:d,defaultWorkspaceId:b,workspaceChoice:v,customWorkspacePath:A,browseCurrentPath:p,browseDirectories:h,browseBusy:_,browseError:C,browseDialogOpen:y,activeLauncherKind:$,launchConfirm:R,launchConfirmWorkspaceKeyRef:F,launchConfirmWorkspaceKey:N,launchConfirmArgs:G,launchConfirmModel:E,launchConfirmResumeId:U,launchConfirmSavedSessions:ae,launchConfirmTextFilter:be,launchConfirmWorkspaceFilter:he,launchConfirmModelFilter:X,launchConfirmResumableOnly:le,launchConfirmSortMode:Se,filteredLaunchConfirmSavedSessions:Qe,launchConfirmSessionsLoading:ce,launchConfirmBusy:pe,resolvedWorkspacePath:Ae,canCreateMissingWorkspace:T,openBrowseDialog:ye,loadBrowsePath:Q,handleWorkspaceChoiceChange:We,chooseCustomWorkspacePath:Pe,setCustomWorkspacePath:m,setBrowseDialogOpen:g,setActiveLauncherKind:L,openLaunchConfirm:ze,handleConfirmLaunch:it,closeLaunchConfirm:et,setWorkspaceSelectionFromOption:_e,setLaunchConfirmWorkspaceKeyAndSync:pt,setLaunchConfirmArgs:I,setLaunchConfirmModel:B,setLaunchConfirmResumeId:V,setLaunchConfirmTextFilter:Y,setLaunchConfirmWorkspaceFilter:W,setLaunchConfirmModelFilter:oe,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:ue}}function jh({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:f,showBottomNav:d,onBack:b,onSectionChange:v,onOpenConversation:w,onOpenRecent:A,onOpenMachineDetails:m,onMachineUpgrade:p,onLaunchDetectedIde:x,onAddWorkspace:h,onBrowseDirectory:S,onLaunchWorkspaceProvider:_,onListSavedSessions:j}){const C=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",k=r.slice(0,4),y=s.slice(0,3),g=wh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:S,onListSavedSessions:j}),$=o.useMemo(()=>k.map(N=>{const{metaText:P,updatedLabel:G}=ll(N);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:P,updatedLabel:G,onClick:()=>{const{options:I,selectedKey:E}=gs({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspacePath:N.workspace});g.openLaunchConfirm({title:N.kind==="ide"?fs("restart-ide",N.label):N.providerSessionId?qa(N.label):fs("start-fresh",N.label),description:N.kind==="ide"?hs("restart-ide"):N.providerSessionId?Ya():hs("start-fresh"),confirmLabel:N.kind==="ide"?Bs("restart-ide"):N.providerSessionId?on(!0):Bs("start-fresh"),busyLabel:N.kind==="ide"?Os("restart-ide"):N.providerSessionId?Va(!0):Os("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===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(B),await A({...N,workspace:(B==null?void 0:B.workspacePath)??null})})}}}),[g,A,k]),L=o.useMemo(()=>y.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:mt(N.conversation),secondary:Zm(N.conversation,{timestampLabel:N.timestamp?Qi(N.timestamp):null}),unread:N.unread,onClick:()=>w(N.conversation)})),[w,y]),M=g.showAllRecent?$:$.slice(0,4),R=$.length>0,O=L.length>0,F=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 ${F} 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:b,type:"button","aria-label":"Back",children:t.jsx(Ma,{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:[O&&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))})]}),R&&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:()=>g.setShowAllRecent(N=>!N),children:g.showAllRecent?"Show fewer":`Show ${$.length-4} more`})})]}),(g.hasIdeOptions||n.length>0||a.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:g.workspaceChoice,onChange:N=>g.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:g.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[g.workspaceRows.map(N=>t.jsxs("option",{value:N.id,children:[N.id===g.defaultWorkspaceId?"⭐ ":"",bn(N.path,N.label)||N.path]},N.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),g.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Ds,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:g.resolvedWorkspacePath||g.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:g.openBrowseDialog,children:"Select workspace…"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{g.resolvedWorkspacePath&&h(g.resolvedWorkspacePath)},disabled:!g.resolvedWorkspacePath||g.browseBusy,children:"Save as workspace"})]})]}),g.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[g.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>g.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>g.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${g.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>g.setActiveLauncherKind("acp"),children:"ACP"})]}),g.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:g.activeLauncherKind==="ide"?"Choose an IDE":g.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:g.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(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}=gs({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.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===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(I),x(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:g.resolvedWorkspacePath||"Use selected workspace"})]},N.type)):(g.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=g.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:I}=gs({machine:{workspaces:g.workspaceRows,defaultWorkspaceId:g.defaultWorkspaceId},currentWorkspaceId:g.workspaceChoice!=="__custom__"?g.workspaceChoice:null,currentWorkspacePath:g.resolvedWorkspacePath});g.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===g.launchConfirmWorkspaceKeyRef.current);g.setWorkspaceSelectionFromOption(E),_(P,N.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:g.launchConfirmArgs,model:g.launchConfirmModel,resumeSessionId:g.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[N.icon?`${N.icon} `:"",N.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:g.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,g.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>h(g.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:p,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"})]})]})]})]}),g.browseDialogOpen&&t.jsx(jn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:g.browseCurrentPath,directories:g.browseDirectories,busy:g.browseBusy,error:g.browseError,confirmLabel:"Use this folder",onClose:()=>g.setBrowseDialogOpen(!1),onNavigate:N=>{g.loadBrowsePath(N)},onConfirm:N=>{g.chooseCustomWorkspacePath(N),g.setBrowseDialogOpen(!1)}}),g.launchConfirm&&t.jsx(lo,{title:g.launchConfirm.title,description:g.launchConfirm.description,details:g.launchConfirm.details,workspaceOptions:g.launchConfirm.workspaceOptions,selectedWorkspaceKey:g.launchConfirmWorkspaceKey,onWorkspaceChange:g.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:g.launchConfirm.providerType?on(!!g.launchConfirmResumeId):g.launchConfirm.confirmLabel,busyLabel:g.launchConfirm.providerType?void 0:g.launchConfirm.busyLabel,busy:g.launchConfirmBusy,showArgsInput:g.launchConfirm.showArgsInput,argsValue:g.launchConfirmArgs,onArgsChange:g.setLaunchConfirmArgs,showModelInput:g.launchConfirm.showModelInput,modelValue:g.launchConfirmModel,onModelChange:g.setLaunchConfirmModel,historyProviderNode:g.launchConfirm.providerType&&(g.launchConfirmSessionsLoading||g.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),g.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Ga()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:g.launchConfirmTextFilter,onChange:N=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:g.launchConfirmWorkspaceFilter,onChange:N=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:g.launchConfirmModelFilter,onChange:N=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),t.jsxs("select",{value:g.launchConfirmSortMode,onChange:N=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:g.launchConfirmResumableOnly,onChange:N=>g.setLaunchConfirmResumableOnly(N.target.checked),disabled:g.launchConfirmBusy||g.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:g.launchConfirmResumeId,onChange:N=>g.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:g.launchConfirmBusy||g.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:up()}),g.filteredLaunchConfirmSavedSessions.map(N=>t.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":"(workspace missing)"]},N.providerSessionId))]}),!g.launchConfirmSessionsLoading&&g.launchConfirmSavedSessions.length>0&&g.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),g.launchConfirmResumeId&&(()=>{const N=g.filteredLaunchConfirmSavedSessions.find(G=>G.providerSessionId===g.launchConfirmResumeId);if(!N)return null;const P=cl(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:g.handleConfirmLaunch,onCancel:g.closeLaunchConfirm}),d&&t.jsx(il,{section:f,onSectionChange:v})]})}function dl(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 kh(e,s){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:js(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,f,d;const a=ur(n)?"cli":Ts(n)?"acp":"ide",i=js(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(ur(n)?n.cliName||n.type:Ts(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ts(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(f=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:f.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Sh(e,s){const r=new Map;for(const n of s){const a=os(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((b,v)=>v.timestamp-b.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ua(n),u=a.filter(b=>b.unread||b.requiresAction).length,f=dl(n),d=[n.platform||"machine",f].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?ep(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 Or(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 Nh({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:b,requestedMobileSection:v,onRequestedMobileSectionConsumed:w,setSelectedTabKey:A,setScreen:m,setSelectedMachineId:p,setSection:x,setMachineBackTarget:h,resetMachineAction:S,markNotificationTargetRead:_}){const j=o.useRef(null),C=o.useCallback(k=>{if(!(k!=null&&k.sessionId))return;const y=rn(k,c),g=Math.max(Date.now(),ms(k),y.lastUpdated||0);Or("mark_read:start",{tabKey:k.tabKey,sessionId:k.sessionId,displayPrimary:mt(k),inboxBucket:y.inboxBucket,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,activityAt:ms(k),readAt:g}),_({sessionId:k.sessionId,providerSessionId:k.providerSessionId,tabKey:k.tabKey,routeId:k.routeId},g),l(os(k)||k.routeId,"mark_session_seen",{sessionId:k.sessionId,seenAt:g}).then($=>{Or("mark_read:result",{tabKey:k.tabKey,sessionId:k.sessionId,result:$})}).catch($=>{Or("mark_read:error",{tabKey:k.tabKey,sessionId:k.sessionId,error:$ instanceof Error?$.message:String($)})})},[c,l]);return o.useEffect(()=>{var y;if(!n){m("inbox"),A(((y=e[0])==null?void 0:y.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(y=>y.tabKey===u);k&&(A(k.tabKey),m("chat"),f==null||f())},[e,f,u,m,A]),o.useEffect(()=>{if(!d)return;const k=s.find(y=>y.id===d);k&&(p(k.id),S(),x("machines"),h("inbox"),m("machine"),b==null||b())},[s,b,d,S,h,m,x,p]),o.useEffect(()=>{v&&(x(v),m("inbox"),w==null||w())},[w,v,m,x]),o.useEffect(()=>{const k=r.filter(y=>y.inboxBucket==="task_complete"||y.unread);k.length!==0&&Or("inbox_state",{screen:i,selectedTabKey:a,items:k.map(y=>{const g=rn(y.conversation,c);return{liveState:g,tabKey:y.conversation.tabKey,sessionId:y.conversation.sessionId,displayPrimary:mt(y.conversation),serverBucket:g.inboxBucket,computedBucket:y.inboxBucket,serverUnread:g.unread,computedUnread:y.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,activityAt:ms(y.conversation)}})})},[r,c,i,a]),{markConversationRead:C}}function Ch(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function fi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ih(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Ah({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,f]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),f(null)},[]),b=o.useCallback(async(h,S,_)=>{var j;try{i("loading"),l(`Launching ${S}…`);const C={ideType:S,enableCdp:!0};(j=_==null?void 0:_.workspacePath)!=null&&j.trim()&&(C.workspace=_.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]),v=o.useCallback(async(h,S,_)=>{if(S.trim())try{i("loading"),l(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const j=await e(h,"workspace_add",{path:S.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(j!=null&&j.success){i("done"),l(_!=null&&_.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,_,j,C,k,y;try{i("loading"),l("Starting daemon upgrade…");const g=await e(h,"daemon_upgrade",{});if((S=g==null?void 0:g.result)!=null&&S.alreadyLatest){i("done"),l(`Already on v${((_=g==null?void 0:g.result)==null?void 0:_.version)||"latest"}.`);return}if((j=g==null?void 0:g.result)!=null&&j.upgraded||(C=g==null?void 0:g.result)!=null&&C.success){i("done"),l(`Upgrade to v${((k=g==null?void 0:g.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((y=g==null?void 0:g.result)==null?void 0:y.error)||"Upgrade failed")}catch(g){i("error"),l(g instanceof Error?g.message:"Upgrade failed")}},[e]),A=o.useCallback(async(h,S,_,j)=>{var y,g,$;const C=Date.now(),k={machineId:h,kind:S,providerType:_,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 ${_}…`),f(k);const L={cliType:_};(y=j==null?void 0:j.workspacePath)!=null&&y.trim()?L.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(L.workspaceId=j.workspaceId),j!=null&&j.resumeSessionId&&(L.resumeSessionId=j.resumeSessionId),(g=j==null?void 0:j.args)!=null&&g.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),R=(M==null?void 0:M.result)||M,O=(R==null?void 0:R.sessionId)||(R==null?void 0:R.id);if(M!=null&&M.success&&O){f(null),i("done"),l(`${_} launched`),s(ns(O));return}if(M!=null&&M.success){i("loading"),l(`${_} launch requested — waiting for session…`);return}f(null),i("error"),l((M==null?void 0:M.error)||(R==null?void 0:R.error)||`Could not launch ${S.toUpperCase()} workspace`)}catch(L){if(Ih(L)){i("loading"),l(`${_} launch requested — waiting for session…`);return}f(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 _=await e(h,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),j=(_==null?void 0:_.result)??_;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[e]),p=o.useCallback(async(h,S)=>wn(e,h,S),[e]);o.useEffect(()=>{if(!u)return;const h=fi(u.workspacePath),S=r.find(j=>{var L,M,R,O;if(!j||j.type==="adhdev-daemon"||Ch(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 g=String(j.providerSessionId||"");if(u.resumeSessionId&&g)return g===u.resumeSessionId;if(h){const F=fi(j.workspace||j.runtimeWorkspaceLabel);return F?F===h:!1}return Number(j.lastUpdated||j._lastUpdate||j.timestamp||((O=(R=(M=(L=j.activeChat)==null?void 0:L.messages)==null?void 0:M.at)==null?void 0:R.call(M,-1))==null?void 0:O.timestamp)||0)>=u.startedAt-5e3});if(!S)return;const _=xc({entrySessionId:S.sessionId,entryInstanceId:S.instanceId,entryRouteId:S.id,conversations:n});_&&(f(null),i("done"),l(`${u.providerType} launched`),s(ns(_)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{f(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 x=o.useCallback(async(h,S)=>{if(S.kind==="ide"&&S.providerType){await b(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})},[b,A]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:b,handleAddWorkspace:v,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:A,handleListSavedSessions:m,handleBrowseDirectory:p,handleOpenRecent:x}}function Mh({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:f}){const d=o.useCallback(x=>{i(x.tabKey),c("chat"),n(x)},[n,c,i]),b=o.useCallback(x=>{const h=e.find(S=>S.routeId===x.routeId&&S.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),v=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),w=o.useCallback((x,h="inbox")=>{l(x),a(),u("machines"),f(h),c("machine")},[a,f,c,u,l]),A=o.useCallback(x=>{const h=os(x);h&&w(h,"chat")},[w]),m=o.useCallback(()=>{a(),c(r)},[r,a,c]),p=o.useCallback(x=>{u(x),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:b,backFromConversation:v,openMachine:w,openConversationMachine:A,backFromMachine:m,changeMachineSection:p}}function Th(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Wr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Lh({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:f,onRequestedActiveTabConsumed:d,requestedMachineId:b,onRequestedMachineConsumed:v,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,onOpenHistory:m,onOpenRemote:p,onStopCli:x,wsStatus:h,isConnected:S,onShowHiddenConversation:_,onShowAllHiddenConversations:j,onHideConversation:C,onOpenNewSession:k,notificationStateBySessionId:y,liveSessionInboxState:g,onMarkNotificationTargetRead:$}){const[L,M]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[R,O]=o.useState(()=>e[0]?"chat":"inbox"),[F,N]=o.useState("chats"),[P,G]=o.useState(null),[I,E]=o.useState("inbox"),B=Ws(),U="0.8.97",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:$s(V),[V]),be=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Ka),[r]),Y=o.useMemo(()=>be.find(Q=>Q.id===P)||null,[be,P]),he=gn({sendDaemonCommand:a,activeConv:V||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),W=Ah({sendDaemonCommand:a,navigate:B,ides:r,conversations:e}),X=o.useMemo(()=>e.map(Q=>{const ye=R==="chat"&&(V==null?void 0:V.tabKey)===Q.tabKey,_e=xn(Q,g,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ye,notificationStateBySessionId:y}),We=ms(Q),Pe=Ac(Q);return{conversation:Q,timestamp:We,preview:Pe,unread:_e.unread,requiresAction:_e.requiresAction,isWorking:_e.isWorking,inboxBucket:_e.inboxBucket}}),[e,g,y,R,V]),{markConversationRead:oe}=Nh({conversations:e,machineEntries:be,items:X,selectedConversation:V,selectedTabKey:L,screen:R,liveSessionInboxState:g,sendDaemonCommand:a,requestedActiveTabKey:f,onRequestedActiveTabConsumed:d,requestedMachineId:b,onRequestedMachineConsumed:v,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,setSelectedTabKey:M,setScreen:O,setSelectedMachineId:G,setSection:N,setMachineBackTarget:E,resetMachineAction:W.resetMachineAction,markNotificationTargetRead:$}),le=Mh({conversations:e,selectedConversation:V,machineBackTarget:I,markConversationRead:oe,resetMachineAction:W.resetMachineAction,setSelectedTabKey:M,setScreen:O,setSelectedMachineId:G,setSection:N,setMachineBackTarget:E}),de=o.useMemo(()=>Wr(X.filter(Q=>Q.requiresAction)),[X]),Se=o.useMemo(()=>Wr(X.filter(Q=>Q.unread&&!Q.requiresAction)),[X]),ue=o.useMemo(()=>Wr(X.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking)),[X]),ce=o.useMemo(()=>Wr(X.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[X]),re=o.useMemo(()=>Y?X.filter(Q=>os(Q.conversation)===Y.id):[],[X,Y]),pe=o.useMemo(()=>kh(Y,r),[r,Y]),te=(Y==null?void 0:Y.version)||null,Ne=!!Y&&!!te&&!0&&te!==U,ke=o.useMemo(()=>(Y==null?void 0:Y.availableProviders)||[],[Y]),Ae=o.useMemo(()=>ke.filter(Q=>Q.category==="cli"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ke]),T=o.useMemo(()=>ke.filter(Q=>Q.category==="acp"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ke]),xe=o.useMemo(()=>Sh(be,X),[X,be]),ve=o.useCallback(async Q=>{Y&&await W.handleOpenRecent(Y.id,Q)},[W,Y]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:R==="chat"&&V?t.jsx(uh,{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:p,onStopCli:x,cliViewMode:we,onSetCliViewMode:async Q=>{if(V&&we!==Q)try{await a(os(V)||V.routeId,"set_cli_view_mode",{targetSessionId:V.sessionId,cliType:Wt(V),mode:Q})}catch(ye){const _e=no(ye);ro(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}):R==="machine"&&Y?t.jsx(jh,{selectedMachineEntry:Y,selectedMachineConversations:re,selectedMachineRecentLaunches:pe,cliProviders:Ae,acpProviders:T,selectedMachineNeedsUpgrade:Ne,appVersion:U,machineAction:W.machineAction,isStandalone:l,section:F,showBottomNav:I==="inbox",onBack:le.backFromMachine,onSectionChange:le.changeMachineSection,onOpenConversation:le.openConversation,onOpenRecent:ve,onOpenMachineDetails:()=>B(`/machines/${Y.id}`),onMachineUpgrade:()=>W.handleMachineUpgrade(Y.id),onLaunchDetectedIde:(Q,ye)=>W.handleLaunchDetectedIde(Y.id,Q,ye),onAddWorkspace:(Q,ye)=>W.handleAddWorkspace(Y.id,Q,ye),onBrowseDirectory:Q=>W.handleBrowseDirectory(Y.id,Q),onLaunchWorkspaceProvider:(Q,ye,_e)=>W.handleLaunchWorkspaceProvider(Y.id,Q,ye,_e),onListSavedSessions:Q=>W.handleListSavedSessions(Y.id,Q)}):t.jsx(ph,{section:F,attentionItems:de,unreadItems:Se,workingItems:ue,completedItems:ce,hiddenConversations:s,machineCards:xe,getAvatarText:Th,onOpenConversation:le.openConversation,onShowConversation:_,onShowAllHidden:j,onOpenNewSession:k,onOpenMachine:le.openMachine,onOpenSettings:()=>B("/settings"),onSectionChange:N,wsStatus:h,isConnected:S,isStandalone:l})})}function Vn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Rh({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[f,d]=o.useState(null),b=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",b),window.addEventListener("drop",b),()=>{window.removeEventListener("dragend",b),window.removeEventListener("drop",b)}),[b]);const v=o.useCallback(p=>{p.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),w=o.useCallback(p=>{if(!p.dataTransfer.types.includes("text/tab-key"))return;if(p.preventDefault(),!Vn(s,r)){d("merge");return}const x=p.currentTarget.getBoundingClientRect(),h=p.clientX-x.left,S=x.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(p=>{c.current=0,u(!1);const x=p.dataTransfer.getData("text/tab-key"),h=x?e.some(_=>_.tabKey===x):!1,S=f;if(d(null),i(),!!x){if(p.preventDefault(),S==="split-left"&&Vn(s,r)){r==null||r(x,"split-left");return}if(S==="split-right"&&Vn(s,r)){r==null||r(x,"split-right");return}if(h){a(x);return}n==null||n(x)}},[e,f,s,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:b,handleDragEnter:v,handleDragOver:w,handleDragLeave:A,handleDrop:m}}function _h(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 Ph({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[f,d]=o.useState(null),b=o.useRef(null),v=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 y=_h(k,e);return y.length===k.length&&y.every((g,$)=>g===k[$])?k:y})},[e]);const m=o.useMemo(()=>{const k=f??l;if(k.length===0)return e;const y=new Map(k.map((g,$)=>[g,$]));return[...e].sort((g,$)=>{const L=y.get(g.tabKey)??999,M=y.get($.tabKey)??999;return L-M})},[e,f,l]);o.useEffect(()=>{var y,g;if(m.length===0){i!==null&&(c(null),(y=w.current)==null||y.call(w,null));return}if(i&&m.some($=>$.tabKey===i))return;const k=m[0].tabKey;k!==i&&(c(k),(g=w.current)==null||g.call(w,k))},[m,i]);const p=o.useMemo(()=>m.find(k=>k.tabKey===i),[m,i]),x=o.useCallback(k=>{var y;c(k),(y=w.current)==null||y.call(w,k)},[]),h=o.useCallback((k,y,g)=>{u($=>{var O;const L=$.filter(F=>F!==k),M=L.indexOf(y);if(M<0)return $;const R=g==="left"?M:M+1;return L.splice(R,0,k),(O=A.current)==null||O.call(A,L),L}),d(null)},[]),S=o.useCallback((k,y,g)=>{const L=(l.length>0?l:e.map(O=>O.tabKey)).filter(O=>O!==k),M=L.indexOf(y);if(M<0)return;const R=g==="left"?M:M+1;L.splice(R,0,k),b.current=L,d(L)},[l,e]),_=o.useCallback(()=>{var y;const k=b.current;k&&(u(k),(y=A.current)==null||y.call(A,k))},[]),j=o.useCallback(()=>{b.current=null,d(null)},[]),C=o.useCallback(k=>{u(y=>{var $;const g=y.filter(L=>L!==k);return g.push(k),($=A.current)==null||$.call(A,g),g})},[]);return{activeTabId:i,activeConv:p,sortedConversations:m,previewOrderRef:b,draggingTabRef:v,selectTab:x,handleTabReorder:h,updatePreviewOrder:S,commitPreviewOrder:_,clearPreviewOrder:j,moveTabToEnd:C,setDraggingTabKey:k=>{v.current=k}}}function Dh({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 uo({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(ol,{}),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 ul="adhdev-tab-shortcuts";function ml(){try{return JSON.parse(localStorage.getItem(ul)||"{}")}catch{return{}}}function pl({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>ml()),[l,u]=o.useState(null),f=o.useCallback(b=>{const v=[];return b.metaKey&&v.push(a?"⌘":"Meta"),b.ctrlKey&&v.push("Ctrl"),b.altKey&&v.push(a?"⌥":"Alt"),b.shiftKey&&v.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(b.key)?null:(v.push(b.key.length===1?b.key.toUpperCase():b.key),v.join("+"))},[a]),d=o.useCallback(b=>{c(b);try{localStorage.setItem(ul,JSON.stringify(b))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const b=v=>{if(v.preventDefault(),v.stopPropagation(),v.key==="Escape"){u(null);return}const w=f(v);if(!w)return;const A={...i};for(const[m,p]of Object.entries(A))p===w&&delete A[m];A[l]=w,d(A),u(null)};return window.addEventListener("keydown",b,!0),()=>window.removeEventListener("keydown",b,!0)},[e,l,i,d,f]),o.useEffect(()=>{if(!e)return;const b=v=>{if(!(!v.ctrlKey&&!v.metaKey&&!v.altKey)){for(const[w,A]of Object.entries(i))if(s.includes(w)&&f(v)===A){v.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",b),()=>window.removeEventListener("keydown",b)},[e,i,s,r,n,f]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const Eh=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:f,onConversationActivated:d,onPreviewReorder:b,onReorderTab:v,onCommitPreviewOrder:w,onClearPreviewOrder:A,onDragStateReset:m,onDragTabKeyChange:p,onReceiveTab:x,onOpenContextMenu:h,longPressTimer:S,isGroupActive:_}){const j=Fs(s),C=j.isGenerating?"agent-tab-generating":j.isWaiting?"agent-tab-waiting":"",k=j.isReconnecting,y=o.useCallback(P=>{l.current=s.tabKey,p(s.tabKey),P.dataTransfer.setData("text/tab-key",s.tabKey),P.dataTransfer.effectAllowed="move"},[s.tabKey,l,p]),g=o.useCallback(()=>{l.current=null,p(null),w(),A(),m()},[l,p,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";b(G,s.tabKey,E)}},[s.tabKey,l,b]),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)?v(G,s.tabKey,E):x&&x(G)}A()},[s.tabKey,c,v,x,A]),M=o.useCallback(P=>{P.stopPropagation(),u(),f(s.tabKey),d(s)},[s,d,u,f]),R=o.useCallback(P=>{P.preventDefault(),h(P.clientX,P.clientY,s.tabKey)},[s.tabKey,h]),O=o.useCallback(P=>{const G=P.touches[0];S.current=setTimeout(()=>{h(G.clientX,G.clientY,s.tabKey)},600)},[s.tabKey,S,h]),F=o.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),N=["adhdev-dockview-tab",C,r&&"is-active",_&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:N,draggable:!0,onDragStart:y,onDragEnd:g,onDragOver:$,onDrop:L,onClick:M,onContextMenu:R,onTouchStart:O,onTouchEnd:F,onTouchMove:F,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:ps(s)}):j.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ps(s),t.jsx("span",{className:"connecting-dots"})]}):ps(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 $h({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:b,onDragStateReset:v,onDragTabKeyChange:w,onReceiveTab:A,onHideTab:m,isGroupActive:p,allowTabShortcuts:x=!0}){const[h,S]=o.useState(null),_=o.useRef(null),j=o.useRef(null),C=o.useMemo(()=>e.map(R=>R.tabKey),[e]);hr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:k,tabShortcuts:y,shortcutListening:g,setShortcutListening:$,saveShortcuts:L}=pl({enabled:x,sortedTabKeys:e.map(R=>R.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const R=O=>{const F=document.querySelector("[data-pane-context-menu]");F&&F.contains(O.target)||S(null)};return window.addEventListener("mousedown",R,!0),()=>window.removeEventListener("mousedown",R,!0)},[h]),o.useEffect(()=>{const R=j.current;if(!R)return;const O=F=>{Math.abs(F.deltaY)<=Math.abs(F.deltaX)||(F.preventDefault(),R.scrollLeft+=F.deltaY)};return R.addEventListener("wheel",O,{passive:!1}),()=>R.removeEventListener("wheel",O)},[]);const M=o.useCallback((R,O,F)=>{S({x:R,y:O,tabKey:F})},[]);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(R=>t.jsx(Eh,{conv:R,isActive:s===R.tabKey,isDraggedTab:a.current===R.tabKey,isTaskCompleteUnread:n.has(R.tabKey),shortcut:x?y[R.tabKey]:void 0,conversationKeys:C,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:b,onDragStateReset:v,onDragTabKeyChange:w,onReceiveTab:A,onOpenContextMenu:M,longPressTimer:_,isGroupActive:p},R.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:[x&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:R=>{R.stopPropagation(),$(h.tabKey),S(null)},children:["⌨ ",y[h.tabKey]?`Change shortcut (${y[h.tabKey]})`:"Set shortcut"]}),y[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 R={...y};delete R[h.tabKey],L(R),S(null)},children:"✕ Remove shortcut"})]}),m&&t.jsxs(t.Fragment,{children:[x&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{m(h.tabKey),S(null)},children:"🚫 Hide from Dashboard"})]})]}),x&&g&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>$(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:R=>R.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 Kh({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:f,groupIndex:d,onFocus:b,isSplitMode:v,numGroups:w,onMoveTab:A,onReceiveTab:m,style:p,onActiveTabChange:x,initialActiveTabId:h,initialTabOrder:S,onTabOrderChange:_,onHideTab:j,isFocused:C,allowTabShortcuts:k=!0,notificationStateBySessionId:y,liveSessionInboxState:g}){const{sendCommand:$}=Lt(),L=o.useRef(null),{activeTabId:M,activeConv:R,sortedConversations:O,draggingTabRef:F,selectTab:N,handleTabReorder:P,updatePreviewOrder:G,commitPreviewOrder:I,clearPreviewOrder:E,moveTabToEnd:B,setDraggingTabKey:U}=Ph({conversations:e,initialActiveTabId:h,initialTabOrder:S,onActiveTabChange:x,onTabOrderChange:_}),V=gn({sendDaemonCommand:a,activeConv:R,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:ae,dropAction:we,resetDragState:be,handleDragEnter:Y,handleDragOver:he,handleDragLeave:W,handleDrop:X}=Rh({conversations:e,numGroups:w,onMoveTab:A,onReceiveTab:m,onOwnTabDrop:B,onClearPreviewOrder:E}),oe=R&&!Ze(R)&&$s(R)==="terminal",le=o.useMemo(()=>R?s.find(ce=>ce.id===R.routeId):void 0,[s,R]),de=o.useMemo(()=>R?n.filter(ce=>ce.routeId===R.tabKey):[],[n,R]),Se=o.useMemo(()=>new Set(O.filter(ce=>yu(ce,g,{isOpenConversation:ce.tabKey===M,notificationStateBySessionId:y})).map(ce=>ce.tabKey)),[M,g,O]);hr("PaneGroup",{groupIndex:d,conversationCount:e.length,activeTabId:M,dragOver:ae});const ue=o.useCallback(ce=>{ce.streamSource==="agent-stream"&&ce.agentType&&$(ce.routeId,al(),{agentType:ce.agentType,...ce.sessionId&&{targetSessionId:ce.sessionId}}).catch(()=>{})},[$]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:b,style:{...p,outline:ae?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx($h,{conversations:O,activeTabId:M,groupIndex:d,numGroups:w,unreadTabKeys:Se,draggingTabRef:F,onFocus:b,onSelectTab:N,onConversationActivated:ue,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:W,onDrop:X,children:[ae&&t.jsx(Dh,{dropAction:we,canSplit:!!(w<4&&A)}),R?t.jsx(co,{activeConv:R,clearToken:r[R.tabKey]||0,isCliTerminal:!!oe,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:de,userName:f,isInputActive:!v||!!C}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(uo,{conversationsCount:e.length,isSplitMode:v,isStandalone:l,hasRegisteredMachines:u})})]})]})}function Bh({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:f,setActionLogs:d,isStandalone:b,hasRegisteredMachines:v,userName:w,focusedGroup:A,setFocusedGroup:m,moveTabToGroup:p,splitTabRelative:x,closeGroup:h,handleResizeStart:S,groupActiveTabIds:_,setGroupActiveTabIds:j,groupTabOrders:C,setGroupTabOrders:k,toggleHiddenTab:y,allowTabShortcuts:g=!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,R)=>{const O=s&&n.length===r?`${n[R]}%`:void 0;return t.jsxs(lt.Fragment,{children:[s&&R>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:F=>S(R-1,F),onDoubleClick:()=>h(R),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(Kh,{style:s?{flexBasis:O??`${100/r}%`,flexGrow:O?0:1,flexShrink:O?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:f,setActionLogs:d,isStandalone:b,hasRegisteredMachines:v,userName:w,groupIndex:R,isFocused:s&&A===R,onFocus:()=>m(R),isSplitMode:s,numGroups:r,onMoveTab:(F,N)=>{N==="left"&&R>0?p(F,R-1):N==="right"&&R<r-1?p(F,R+1):N==="split-left"&&r<4?x(F,R,"left"):N==="split-right"&&r<4&&x(F,R,"right")},onReceiveTab:F=>p(F,R),onActiveTabChange:F=>j(N=>(N[R]??null)===(F??null)?N:{...N,[R]:F}),initialActiveTabId:_[R],initialTabOrder:C[R],onTabOrderChange:F=>k(N=>{const P=N[R]||[];return P.length===F.length&&P.every((G,I)=>G===F[I])?N:{...N,[R]:F}}),onHideTab:y,allowTabShortcuts:g,notificationStateBySessionId:$,liveSessionInboxState:L})]},R)})})}function fl({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,b)=>{if(d!==e)return;const v=new FileReader;v.onload=()=>i(v.result),v.readAsDataURL(b)}):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,(b,v)=>{b===e&&v!=null&&v.screenshotUsage&&l(v.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const f=e?rt.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&s?f.startScreenshots(s):f.stopScreenshots(s),()=>{f.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(f,d)=>{const b=e?rt.get(e):null;return!b||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):b.sendInput(f,d,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const hl="adhdev-dashboard-action-shortcuts",Oh=1200,Wh={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Hh(){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 xl(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 ka(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function dn(e){const s=Object.fromEntries(xl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(hl)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Wh))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function bl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Fh({enabled:e=!0,onTrigger:s}){const r=Hh(),[n,a]=o.useState(()=>dn(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),f=o.useRef({parts:[],timer:null}),d=o.useCallback(m=>{const p=[];return m.metaKey&&p.push(r?"⌘":"Meta"),m.ctrlKey&&p.push("Ctrl"),m.altKey&&p.push(r?"⌥":"Alt"),m.shiftKey&&m.key.length!==1&&p.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(p.push(bl(m.key)),p.join("+"))},[r]),b=o.useCallback(m=>{a(m);try{localStorage.setItem(hl,JSON.stringify(m))}catch{}},[]);o.useEffect(()=>{const m=dn(r),p=Object.entries(n),x=Object.entries(m);p.length===x.length&&p.every(([h,S])=>m[h]===S)||b(m)},[n,r,b]);const v=o.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),w=o.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},Oh))},[]);o.useEffect(()=>{if(!i)return;const m=p=>{if(p.preventDefault(),p.stopPropagation(),p.key==="Escape"){c(null),u([]);return}const x=d(p);if(!x)return;const S=!(p.metaKey||p.ctrlKey||p.altKey)&&/^[A-Z0-9]$/.test(x);if(l.length===0&&S){u([x]);return}const j=[...l,x].slice(0,2).join(" "),C={...n};for(const[k,y]of Object.entries(C))y===j&&delete C[k];C[i]=j,b(C),c(null),u([])};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[n,d,b,i,l]),o.useEffect(()=>{if(!e||i)return;const m=p=>{if(p.defaultPrevented)return;const x=d(p);if(!x)return;const h=p.metaKey||p.ctrlKey||p.altKey;if(ka(p.target)&&!h)return;const S=f.current.parts,_=h?[x]:[...S.slice(-1),x].slice(-2),j=_.join(" "),C=_[_.length-1],k=Object.entries(n).filter(([,M])=>!!M),y=k.find(([,M])=>M===j);if(y){p.preventDefault(),v(),s(y[0]);return}if(k.some(([,M])=>M.startsWith(`${j} `))){p.preventDefault(),f.current.parts=_,w();return}const $=k.find(([,M])=>M===C);if($){p.preventDefault(),v(),s($[0]);return}if(k.some(([,M])=>M.startsWith(`${C} `))){p.preventDefault(),f.current.parts=[C],w();return}v()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[n,w,e,d,s,v,i]),o.useEffect(()=>()=>v(),[v]);const A=o.useMemo(()=>xl(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:b}}function Uh({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 gl(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function hi({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!gl(n):!0}function zh({previousVisibleConversationCount:e,visibleConversationCount:s,ides:r}){return s>0||e<=0?!1:gl(r)}const yl=o.createContext(null);function kn(){const e=o.useContext(yl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Jr(e){return mt(e)||e.tabKey}function Vh(e){return`remote:${e}`}function Ot(e){return e.startsWith("remote:")}function xi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Gn(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 Hr(e,s){e.classList.remove(oa.className,ia.className),e.classList.add(s==="light"?oa.className:ia.className)}function bi(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 Gh(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 qh(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const f of l){const d=e.addPanel({id:f.tabKey,component:"conversation",title:Jr(f),params:{kind:"conversation",tabKey:f.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function gi(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!==Jr(n)&&a.api.setTitle(Jr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Jr(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 yi(e,s,r){var u,f;const n=r?Vh(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=Lc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((f=e.panels.find(d=>!Ot(d.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Yh({params:e,api:s}){var b;const r=kn(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=gn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const v=[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 v)w.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(v=>v.id===c.routeId):void 0,[r.ides,c]),f=o.useMemo(()=>c?r.actionLogs.filter(v=>v.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(uo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const d=!Ze(c)&&$s(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(co,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((b=r.scrollToBottomRequest)==null?void 0:b.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function Xh({params:e}){var u;const s=kn(),r=o.useMemo(()=>Ft([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>s.ides.find(f=>f.id===e.routeId),[s.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=fl({doId:a,targetSessionId:r?pc(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(Yi,{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 Jh(){const e=kn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(uo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Qh(e){var w,A;Gh(e);const s=kn(),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),p=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,x=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${x?" 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=xn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,f=c.isGenerating,d=c.isWaiting,b=c.unread,v=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 p;m.preventDefault(),r(m),s.openTabContextMenu({x:m.clientX,y:m.clientY,tabKey:n.tabKey,sourceDocument:((p=m.target)==null?void 0:p.ownerDocument)??document})},children:[b&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?t.jsx("div",{className:"tab-spinner"}):d?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:mt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ps(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ps(n)}):t.jsx("span",{children:ps(n)})})]}),v&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:v,children:v})]})}function Zh({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:f,userName:d,toggleHiddenTab:b,actionShortcuts:v,registerActionHandlers:w,onActiveTabChange:A,onRequestScrollToBottom:m,requestedActiveTabKey:p,requestedRemoteIdeId:x,onRequestedActiveTabConsumed:h,scrollToBottomRequest:S,notificationStateBySessionId:_,liveSessionInboxState:j}){var De,$e,ot;const{theme:C}=Qa(),{sendCommand:k}=Lt(),y=o.useRef(null),g=o.useRef(null),$=o.useRef(!1),L=o.useRef(!1),M=o.useRef(!1),R=o.useRef(null),O=o.useRef([]),[F,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(()=>el(typeof window<"u"?window.innerWidth:1280),[]),we=o.useRef(typeof window>"u"?{}:_f(ae)),be=o.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),Y=o.useMemo(()=>{const K=y.current;return K?K.groups.some(H=>{try{const z=H.model.location.type;return z!=="floating"&&z!=="popout"?!1:H.panels.some(q=>be.has(q.id))}catch{return!1}}):!1},[be,B,e]),he=o.useCallback(()=>{var K;(K=y.current)==null||K.focus()},[]),W=o.useCallback((K,H)=>{m==null||m(K,H)},[m]),X=o.useCallback(K=>{const H=document,z=K.document;for(const Ie of H.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 H.querySelectorAll("style")){const Oe=z.createElement("style");Oe.textContent=Ie.textContent,z.head.appendChild(Oe)}const q=[];for(const Ie of H.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 se=H.documentElement.getAttribute("data-theme");se&&z.documentElement.setAttribute("data-theme",se),z.documentElement.style.colorScheme=se==="light"?"light":"dark",z.body.className=H.body.className;const Ce=H.documentElement.getAttribute("style");Ce&&z.documentElement.setAttribute("style",Ce);const Te=z.getElementById("dv-popout-window");Te instanceof HTMLElement&&(Te.classList.add("adhdev-dockview"),Hr(Te,C))},[C]),oe=o.useCallback(()=>{var H;const K=y.current;if(K)for(const z of K.groups)try{const q=(H=z.element)==null?void 0:H.ownerDocument;if(!q||q===document)continue;const se=q.getElementById("dv-popout-window");se instanceof HTMLElement&&(se.classList.add("adhdev-dockview"),Hr(se,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 H;const K=y.current;if(K)for(const z of K.groups)try{const q=(H=z.element)==null?void 0:H.ownerDocument;if(!q||q===document)continue;const se=q.getElementById("dv-popout-window");if(!(se instanceof HTMLElement))continue;se.classList.add("adhdev-dockview"),Hr(se,C),se.classList.toggle("is-showing-dockview-overlay",I),se.classList.toggle("is-dragging-dockview",P)}catch{}},[P,I,C]),de=o.useCallback(K=>{const H=y.current;if(!H)return;const z=H.getPanel(K);z&&H.addPopoutGroup(z,{popoutUrl:"/popout.html",onDidOpen:({window:q})=>{X(q),Ae();const se=be.get(K);q.document.title=se?`${mt(se)} — ADHDev`:"ADHDev — Popout"}})},[be,X]),Se=o.useCallback(K=>{const H=y.current,z=H==null?void 0:H.getPanel(K);if(!H||!z)return;const q=H.groups.filter(se=>{var Ce;try{return((Ce=se.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()},[]),ue=o.useCallback(K=>{var q;const H=y.current;if(!H)return!1;const z=H.getPanel(K);if(!z)return!1;try{return((q=z.group.element)==null?void 0:q.ownerDocument)!==document}catch{return!1}},[]),ce=o.useCallback(K=>{ue(K)&&Se(K),b(K)},[ue,Se,b]),re=o.useCallback(K=>{const H=y.current,z=H==null?void 0:H.getPanel(K);!H||!z||H.addFloatingGroup(z,{width:600,height:500})},[]),pe=o.useCallback(K=>{var z;const H=(z=y.current)==null?void 0:z.getPanel(K);if(!H)return!1;try{return H.group.model.location.type==="floating"}catch{return!1}},[]),te=o.useCallback(()=>{var H,z;const K=(z=(H=y.current)==null?void 0:H.activePanel)==null?void 0:z.id;return!K||Ot(K)?null:be.has(K)?K:null},[be]),Ne=o.useCallback(K=>{const H=y.current,z=H==null?void 0:H.getPanel(K);if(!H||!z)return;const q=H.groups.filter(se=>{try{return se.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()},[]),ke=o.useCallback(()=>{var Ce;const K=y.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 se=K.activePanel;se&&(se.group.model.openPanel(se),se.api.setActive()),Gn(document)},[]),Ae=o.useCallback(()=>{var H,z;const K=y.current;if(K)for(const q of K.groups){const se=(H=q.element)==null?void 0:H.ownerDocument;if(!se||se===document)continue;const Ce=se.getElementById("dv-popout-window");if(!(Ce instanceof HTMLElement))continue;let Te=null,Ie=se.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=Lc(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?ps(Fe):"Dockview panel"}se.title=`${Ie} — ADHDev`;let J=se.getElementById("adhdev-popout-header");J instanceof HTMLElement||(J=se.createElement("div"),J.id="adhdev-popout-header",se.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;">${xi(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;">${xi(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&&Se(Te),(Fe=se.defaultView)==null||Fe.focus()})}},[be,Se]),T=o.useCallback(K=>{var q;const H=y.current,z=H==null?void 0:H.getPanel(K);if(!(!H||!z)){z.group.model.openPanel(z),z.api.setActive(),W(K,"dockview-shortcut");try{const se=z.group.model.location;se.type==="popout"?se.getWindow().focus():Gn((q=z.group.element)==null?void 0:q.ownerDocument)}catch{}}},[W]),xe=o.useCallback(K=>{const H=y.current,z=H==null?void 0:H.activePanel,q=(H==null?void 0:H.activeGroup)||(z==null?void 0:z.group);if(!H||!z||!q)return;const se=q.panels||[];if(se.length<=1)return;const Ce=se.findIndex(Oe=>Oe.id===z.id);if(Ce<0)return;const Te=(Ce+K+se.length)%se.length,Ie=se[Te];Ie&&(Ie.group.model.openPanel(Ie),Ie.api.setActive(),Ot(Ie.id)||W(Ie.id,"dockview-shortcut"))},[W]),ve=o.useCallback(K=>{var Ve;const H=y.current,z=(H==null?void 0:H.activeGroup)||((Ve=H==null?void 0:H.activePanel)==null?void 0:Ve.group);if(!H||!z)return;const q=H.groups||[],se=q.find(Fe=>Fe.id===z.id);if(!se)return;const Ce=se.element.getBoundingClientRect(),Te=Ce.left+Ce.width/2,Ie=Ce.top+Ce.height/2,Oe=(Fe,D,ee,ie)=>Math.max(0,Math.min(D,ie)-Math.max(Fe,ee)),Ue=Fe=>{const D=Fe.element.getBoundingClientRect(),ee=D.left+D.width/2,ie=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(ie-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(ie-Ie),Ee=Oe(Ce.top,Ce.bottom,D.top,D.bottom)):K==="above"?(Xe=ie<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=ie>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===se.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 H=ve(K);if(!H)return;const z=H.activePanel||H.panels[0];z&&(H.model.openPanel(z),z.api.setActive(),Ot(z.id)||W(z.id,"dockview-focus"),Gn((q=H.element)==null?void 0:q.ownerDocument))},[ve,W]),ye=o.useCallback((K,H)=>{const z=y.current,q=z==null?void 0:z.activePanel,se=(z==null?void 0:z.activeGroup)||(q==null?void 0:q.group);if(!z||!q||!se)return;let Ce=ve(K);!Ce&&(H!=null&&H.createGroupIfMissing)&&(Ce=z.addGroup({referenceGroup:se,direction:K})),Ce&&(q.api.moveTo({group:Ce,position:"center"}),q.group.model.openPanel(q),q.api.setActive(),Ot(q.id)||W(q.id,H!=null&&H.createGroupIfMissing?"dockview-split":"dockview-move"))},[ve,W]),{isMac:_e,tabShortcuts:We,shortcutListening:Pe,setShortcutListening:ze,saveShortcuts:Qe}=pl({sortedTabKeys:e.map(K=>K.tabKey),onFocus:he,onSelectTab:T}),it=o.useCallback(()=>{var z;const K=y.current;if(!K)return;const H=K.activePanel;if(H){if(Ot(H.id)){const q=((z=H.params)==null?void 0:z.routeId)||H.id.slice(7),se=Ft(e,q);se!=null&&se.tabKey&&ze(se.tabKey);return}be.has(H.id)&&ze(H.id)}},[be,T,ze,e]),et=o.useCallback(K=>{const H=[];return K.metaKey&&H.push(_e?"⌘":"Meta"),K.ctrlKey&&H.push("Ctrl"),K.altKey&&H.push(_e?"⌥":"Alt"),K.shiftKey&&K.key.length!==1&&H.push(_e?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(K.key)?null:(H.push(bl(K.key)),H.join("+"))},[_e]),pt=o.useCallback(K=>{var H,z;switch(K){case"splitActiveTabRight":ye("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":ye("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const q=te();q&&re(q);return}case"popoutActiveTab":{const q=te();q&&de(q);return}case"dockActiveTab":{const q=te();if(!q)return;ue(q)?Se(q):pe(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=(H=y.current)==null?void 0:H.activePanel)==null?void 0:z.id;q&&!Ot(q)&&ce(q);return}default:return}},[xe,Ne,Q,re,te,ce,pe,ue,Se,ye,de,it]);o.useEffect(()=>{if(!F)return;const K=F.sourceDocument,H=K.defaultView??window,z=q=>{const se=K.querySelector("[data-dockview-tab-context-menu]");se&&se.contains(q.target)||N(null)};return H.addEventListener("mousedown",z,!0),H!==window&&window.addEventListener("mousedown",()=>N(null),!0),()=>{H.removeEventListener("mousedown",z,!0),H!==window&&window.removeEventListener("mousedown",()=>N(null),!0)}},[F]);const tt=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:be,hasDetachedConversationPanels:Y,ides:r,isStandalone:l,hasRegisteredMachines:u,liveSessionInboxState:j,notificationStateBySessionId:_,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:ce,userName:d,scrollToBottomRequest:S,tabShortcuts:We,openTabContextMenu:({x:K,y:H,tabKey:z,sourceDocument:q})=>N({x:K,y:H,tabKey:z,sourceDocument:q??document}),popoutTab:de,moveTabBackToMain:Se,isTabInPopout:ue,floatTab:re,isTabFloating:pe}),[n,s,be,Y,r,l,u,j,_,a,c,i,ce,d,S,We,de,Se,ue,re,pe]),Ct=F?Uh({isTabInPopout:ue(F.tabKey),isTabFloating:pe(F.tabKey),tabShortcut:We[F.tabKey],actionShortcuts:v}):[],ft=o.useCallback(K=>{var q;const H=y.current;if((((q=H==null?void 0:H.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,H="requested-tab")=>{if(!K)return!1;const z=y.current;if(!z)return!1;const q=z.getPanel(K);return q?(ft(q),W(K,H),h==null||h(),!0):!1},[ft,h,W]),Re=o.useCallback(()=>{if(M.current)return!1;const K=st(R.current,"stored-layout-restore");return K&&(M.current=!0),K},[st]),Ge=o.useCallback(()=>{var H;const K=y.current;K&&Rf(ae,{activeTabId:((H=K.activePanel)==null?void 0:H.id)??null,layout:K.toJSON()})},[ae]),Be=o.useCallback(()=>{Pf(ae,we.current)},[ae]),qe=o.useCallback(K=>{var q,se,Ce,Te;const H=y.current;if(!H)return{kind:"grid"};const z=H.toJSON();for(const Ie of z.floatingGroups||[])if((se=(q=Ie.data)==null?void 0:q.views)!=null&&se.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 H=y.current;if(!H)return;const z=H.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"){H.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:ke,activatePreviousTabInGroup:()=>xe(-1),activateNextTabInGroup:()=>xe(1),floatActiveTab:()=>{const K=te();K&&re(K)},popoutActiveTab:()=>{const K=te();K&&de(K)},dockActiveTab:()=>{const K=te();K&&(ue(K)?Se(K):pe(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,re,Q,te,pe,ue,ye,Se,de,w,ke,At,T,it]);const bt=o.useCallback(()=>{const K=g.current;if(!K)return;const H=K.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const z of H)z.setAttribute("data-adhdev-force-hidden","true")},[]),jt=o.useCallback(()=>{const K=g.current;if(!K)return;const H=K.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const z of H)z.removeAttribute("data-adhdev-force-hidden")},[]),gt=o.useCallback(()=>{const K=g.current;if(!K)return;const H=K.querySelectorAll(".dv-drop-target-container");for(const se of H)se.remove();const z=K.querySelectorAll(".dv-drop-target-dropzone");for(const se of z)se.remove();const q=K.querySelectorAll(".dv-drop-target");for(const se of q)se.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;y.current=K.api;const H=Lf(ae);if(R.current=(H==null?void 0:H.activeTabId)??null,H!=null&&H.layout&&K.api.fromJSON(H.layout,{reuseExistingPanels:!1}),L.current=hi({hasStoredLayout:!!(H!=null&&H.layout),initialDataLoaded:f,visibleConversationCount:e.length,ides:r}),L.current||(gi(K.api,e),yi(K.api,e,x)),K.api.totalPanels===0&&e.length>0){const q=qh(K.api,e,p);if(q){const se=K.api.getPanel(q);se&&ft(se)}}else!L.current&&!st(p)&&Re();$.current=!0,K.api.onDidActivePanelChange(q=>{var Ce;if(R.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 se=be.get(q.id);(se==null?void 0:se.streamSource)==="agent-stream"&&se.agentType&&k(se.routeId,al(),{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.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 se,Ce;try{const Te=(se=q.element)==null?void 0:se.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)},[ft,st,Mt,jt,be,r,f,ae,bt,A,Ge,p,x,k,Ae,e]);o.useLayoutEffect(()=>{const K=y.current;if(!K||!$.current||L.current&&hi({hasStoredLayout:!0,initialDataLoaded:f,visibleConversationCount:e.length,ides:r}))return;L.current&&(L.current=!1);const H=O.current,z=new Set(H),q=e.map(J=>J.tabKey),se=new Set(q),Ce=zh({previousVisibleConversationCount:H.length,visibleConversationCount:e.length,ides:r});let Te=!1;for(const J of H)se.has(J)||Ce||(we.current[J]=qe(J),Te=!0);Te&&Be(),Ce||(gi(K,e),yi(K,e,x));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(),O.current=q,p&&st(p))return;!K.activePanel&&K.panels[0]&&ft(K.panels[0]),!!(K.activePanel&&K.getPanel(K.activePanel.id))||Re()},[ft,st,Re,r,f,Be,qe,p,x,e]),o.useEffect(()=>{$.current&&st(p)},[st,p]),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 se=q.querySelector("[data-tab-key]")||q.closest("[data-tab-key]");if(se){const Ce=se.getAttribute("data-tab-key");if(Ce&&z.dataTransfer){const Te=q.closest(".dv-tab")||se.closest(".dv-tab")||se;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 H=bi(y.current);for(const z of H)z.addEventListener("dragstart",K);return()=>{window.removeEventListener("dragstart",K);for(const z of H)z.removeEventListener("dragstart",K)}},[B]),o.useEffect(()=>{var H;const K=(H=g.current)==null?void 0:H.querySelector(".adhdev-dockview");K instanceof HTMLElement&&Hr(K,C),oe(),Ae(),le()},[Ae,le,oe,C]),o.useEffect(()=>{Ae(),le()},[Ae,le]),o.useEffect(()=>{const K=H=>{if(H.defaultPrevented||Pe)return;const z=et(H);if(!z)return;const q=H.metaKey||H.ctrlKey||H.altKey;ka(H.target)&&!q||dn(_e).setActiveTabShortcut!==z||(H.preventDefault(),H.stopPropagation(),it())};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[et,_e,Pe,it]),o.useEffect(()=>{const K=g.current;if(!K)return;const H=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 se=Math.abs(z.deltaX),Ce=Math.abs(z.deltaY),Te=se>Ce?z.deltaX:z.deltaY;q.dispatchEvent(new WheelEvent("wheel",{deltaY:Te,deltaMode:z.deltaMode,bubbles:!1,cancelable:!0}))};return K.addEventListener("wheel",H,{passive:!1,capture:!0}),()=>K.removeEventListener("wheel",H,{capture:!0})},[]),o.useEffect(()=>{const K=bi(y.current);if(K.length===0)return;const H=K.map(z=>{let q=[],se=null;const Ce=()=>{se!=null&&z.clearTimeout(se),se=null,q=[]},Te=()=>{se!=null&&z.clearTimeout(se),se=z.setTimeout(()=>{se=null,q=[]},1200)},Ie=Ue=>{if(!Ue.ctrlKey&&!Ue.metaKey&&!Ue.altKey)return;const J=et(Ue);if(!J)return;const Me=ml();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(ka(Ue.target)&&!Me)return;const Ve=dn(_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(" "),ie=D[D.length-1],Ke=Fe.find(([,je])=>je===ee);if(Ke){Ue.preventDefault(),Ce(),pt(Ke[0]);return}if(Fe.some(([,je])=>je.startsWith(`${ee} `))){Ue.preventDefault(),q=D,Te();return}const Ee=Fe.find(([,je])=>je===ie);if(Ee){Ue.preventDefault(),Ce(),pt(Ee[0]);return}if(Fe.some(([,je])=>je.startsWith(`${ie} `))){Ue.preventDefault(),q=[ie],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 H)z()}},[et,_e,B,T,Pe,pt,e]);const Dt=C==="light"?oa:ia,Z=((ot=($e=(De=y.current)==null?void 0:De.activePanel)==null?void 0:$e.group.element)==null?void 0:ot.ownerDocument)??document;return t.jsxs(yl.Provider,{value:tt,children:[t.jsx("div",{ref:g,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(md,{className:`h-full min-h-0 min-w-0 adhdev-dockview${P?" is-dragging-dockview":""}${I?" is-showing-dockview-overlay":""}`,components:{conversation:Yh,remote:Xh},defaultTabComponent:Qh,watermarkComponent:Jh,onReady:Tt,singleTabMode:"default",tabAnimation:"smooth",theme:Dt,popoutUrl:"/popout.html"})}),F&&ir.createPortal(t.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:F.x,top:F.y},children:Ct.map(K=>{if(K.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},K.id);let H=t.jsx(Qd,{size:13,className:"shrink-0 opacity-70"}),z=()=>{};switch(K.id){case"dockInWindow":case"dockBackToGrid":H=t.jsx(eu,{size:13,className:"shrink-0 opacity-70"}),z=()=>{Ne(F.tabKey),N(null)};break;case"moveBackToMain":H=t.jsx(Jd,{size:13,className:"shrink-0 opacity-70"}),z=()=>{Se(F.tabKey),N(null)};break;case"floatAsPanel":H=t.jsx(Zd,{size:13,className:"shrink-0 opacity-70"}),z=()=>{re(F.tabKey),N(null)};break;case"openInNewWindow":H=t.jsx(Xd,{size:13,className:"shrink-0 opacity-70"}),z=()=>{de(F.tabKey),N(null)};break;case"setShortcut":z=q=>{q.stopPropagation(),ze(F.tabKey),N(null)};break;case"removeShortcut":H=t.jsx(It,{size:13,className:"shrink-0 opacity-70"}),z=()=>{const q={...We};delete q[F.tabKey],Qe(q),N(null)};break;case"hideTab":H=t.jsx(Ui,{size:13,className:"shrink-0 opacity-70"}),z=()=>{ce(F.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:[H,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)})}),F.sourceDocument.body),Pe&&ir.createPortal(t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>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 vl="adhdev-recent-launch-args-v1",ex=8;function tx(e){return String(e||"").trim().replace(/\s+/g," ")}function wl(e,s){return`${e.trim()}::${s.trim()}`}function jl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(vl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function sx(e){if(!(typeof window>"u"))try{window.localStorage.setItem(vl,JSON.stringify(e))}catch{}}function kl(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=jl().byKey[wl(r,n)])==null?void 0:i.items)||[]}function Sl(e,s,r){var d;const n=String(e||"").trim(),a=String(s||"").trim(),i=tx(r);if(!n||!a||!i)return;const c=jl(),l=wl(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],f=[i,...u.filter(b=>b!==i)].slice(0,ex);c.byKey[l]={items:f},sx(c)}function rx(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 mo(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 Nl(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=mo((i==null?void 0:i.meta)||void 0),u=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?s.push(i):(c==="stopped"||c==="failed")&&(u||l)?r.push(i):n.push(i)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function Cl(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function _s(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function qn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function nx(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function vi(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function wi(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 ax(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ox(e){switch(e){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-[#ffffff0a] text-text-muted"}}function ix(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 cx({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),[f,d]=o.useState(""),[b,v]=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]),p=o.useMemo(()=>r.filter(I=>{if(I.type==="adhdev-daemon"||I.transport!=="pty")return!1;const E=nx(I.daemonId||I.id);return!!(m!=null&&m.id)&&E===m.id}),[m==null?void 0:m.id,r]),x=Yc(m==null?void 0:m.id,{enabled:!!(m!=null&&m.id),includeSessions:!0,limit:6,intervalMs:1e4}),h=x.diagnostics,S=x.loading,_=x.applyDiagnostics,j=o.useMemo(()=>{const I=new Map;for(const E of p){const B=s.find(U=>U.sessionId===E.sessionId||U.routeId===E.id);E.sessionId&&B&&I.set(E.sessionId,B)}return I},[p,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=qn(I);if(!(E!=null&&E.success))throw new Error((E==null?void 0:E.error)||"Could not load hosted runtime diagnostics");_(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,_,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}`;v(B);try{const U=await a(m.id,I,{sessionId:E.sessionId}),V=qn(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{v(U=>U===B?null:U)}},[m==null?void 0:m.id,C,a]),y=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.`))){v("session_host_prune_duplicate_sessions");try{const E=await a(m.id,"session_host_prune_duplicate_sessions",{}),B=qn(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{v(E=>E==="session_host_prune_duplicate_sessions"?null:E)}}},[m==null?void 0:m.id,C,a]),g=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)||[]}:Nl(g),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,g]),L=$.liveRuntimes,M=$.recoverySnapshots,R=$.inactiveRecords,O=o.useMemo(()=>ix(L),[L]),F=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,oe;const B=j.get(I.sessionId),U=p.find(le=>le.sessionId===I.sessionId),V=b===`session_host_resume_session:${I.sessionId}`,ae=b===`session_host_restart_session:${I.sessionId}`,we=b===`session_host_stop_session:${I.sessionId}`,be=mo(I.meta),Y=typeof((X=I.meta)==null?void 0:X.runtimeRecoveryError)=="string"?String(I.meta.runtimeRecoveryError):"",he=E==="recovery"?"Recover":"Resume",W=Cl(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 ${ox(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:((oe=I.writeOwner)==null?void 0:oe.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ax(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(Ta,{size:11})," ",I.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",wi(I.lastActivityAt),I.osPid?` · pid ${I.osPid}`:"",` · Next: ${W}`]}),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:!!b,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:!!b,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:!!b,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(Qt,{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(Hs,{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:[f&&!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(ws,{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:f})]})]})}),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:wi(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:vi(h.hostStartedAt)})]})]}),F&&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(ws,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:F.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(pn,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[O>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:b==="session_host_prune_duplicate_sessions",onClick:()=>{y()},children:b==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${O}`}),t.jsxs("div",{className:"text-[11px] text-text-secondary",children:[p.length," dashboard session",p.length===1?"":"s"]})]})]}),t.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:_s("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:_s("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"))})]}),R.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:_s("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:R.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=g.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:vi(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]})]})]})]})})}function Il(e){return!e.hasLoadedInitialResults&&!e.isLoading}function tr({title:e,description:s,action:r,children:n,className:a="",contentClassName:i=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),s&&t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:s})]}),r?t.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?t.jsx("div",{className:s||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function Al({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?cl(n):null;return t.jsxs(tr,{title:"Saved history",description:Ga(),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:fp()})]}),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 Yn(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 Fr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function lx({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:u,sendDaemonCommand:f,onOpenConversation:d}){var Tt,Dt;const b=gr(),v=o.useMemo(()=>[...e].sort(Ka),[e]),[w,A]=o.useState(((Tt=v[0])==null?void 0:Tt.id)||""),m=o.useMemo(()=>v.find(Z=>Z.id===w)||v[0],[w,v]),p=o.useMemo(()=>((m==null?void 0:m.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[m]),x=(m==null?void 0:m.defaultWorkspaceId)||null,[h,S]=o.useState(""),[_,j]=o.useState(""),[C,k]=o.useState(Yn(v[0])),[y,g]=o.useState(""),[$,L]=o.useState(""),[M,R]=o.useState([]),[O,F]=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,W]=o.useState(!1),[X,oe]=o.useState(null),[le,de]=o.useState(!1),[Se,ue]=o.useState(""),[ce,re]=o.useState(!1),[pe,te]=o.useState(""),[Ne,ke]=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=v[0])!=null&&Z.id)&&A(v[0].id)},[w,v]),o.useEffect(()=>{!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||b(m.id,{minFreshMs:3e4}).catch(()=>{})},[b,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(x||((De=p[0])==null?void 0:De.id)||"__home__"),j(""),k(Yn(m)),g(""),L(""),F(""),P([]),B(!1),V(""),Y(wt()),ue("");return}S($e=>{var ot;return $e==="__custom__"||$e==="__home__"||p.some(K=>K.id===$e)?$e:x||((ot=p[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:Yn(m))},[ze.length,Pe.length,x,Qe.length,m,p]),o.useEffect(()=>{var Z;C&&(it.some(De=>De.id===y)||g(((Z=it[0])==null?void 0:Z.id)||""))},[C,it,y]);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]),pt=o.useCallback((Z,De)=>{R(kl(Z,De))},[]);o.useEffect(()=>{We.current+=1,F(""),Y(wt()),!m||!y||C==="ide"?R([]):pt(m.id,y),B(!1),P([]),V(""),I(!1)},[C,pt,et,m,y]),o.useEffect(()=>{if(!O)return;const Z=N.find(De=>De.providerSessionId===O);Z!=null&&Z.canResume||F("")},[N,O]);const tt=h==="__custom__"?_.trim():h==="__home__"?"":((Dt=p.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]),ft=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=p.find(ot=>Fr(ot.path)===Fr(De));if($e){S($e.id),j("");return}S("__custom__"),j(De)},[p]),Re=o.useCallback(Z=>{const De=String(Z.workspace||"").trim();if(!De)return{workspaceId:null,workspacePath:null};const $e=p.find(ot=>Fr(ot.path)===Fr(De));return $e?{workspaceId:$e.id,workspacePath:null}:{workspaceId:null,workspacePath:De}},[p]),Ge=o.useMemo(()=>N.find(Z=>Z.providerSessionId===O)||null,[N,O]),Be=o.useMemo(()=>{var De;if(C!=="cli"||!m||!y)return null;const Z=((De=Pe.find($e=>$e.type===y))==null?void 0:De.displayName)||y;return{routeId:m.id,daemonId:m.id,providerSessionId:O||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:y,status:"idle",title:Z,messages:[],ideType:y,workspaceName:tt,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${m.id}:${y}`,machineName:_t(m,{fallbackId:m.id})}},[C,Pe,tt,m,O,y]),qe=o.useCallback(()=>{var De;if(!m)return;S("__custom__"),re(!0),ve("");const Z=vn(m.platform,yn(_.trim(),tt,Ct,ft,m.defaultWorkspacePath,(De=p.find($e=>$e.id===x))==null?void 0:De.path,p.map($e=>$e.path)));T(!0),a(m.id,Z).then($e=>{te($e.path),j($e.path),ke($e.directories)}).catch($e=>{ve($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>T(!1))},[_,x,ft,Ct,a,tt,m,p]),At=o.useCallback(Z=>{m&&(T(!0),ve(""),a(m.id,Z).then(De=>{te(De.path),j(De.path),ke(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),ue("");const Z=await i(m.id,tt);if(ye(!1),!Z.ok){ue(Z.error||"Could not save workspace");return}ue("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,tt,m]),jt=o.useCallback(async()=>{if(!m||!C||!y)return;de(!0),ue("");const Z=$.trim()?$.trim().split(/\s+/).filter(Boolean):[],De=C==="ide"?await c(m.id,y,{workspacePath:tt||null}):await l(m.id,C,y,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&tt||null,resumeSessionId:C==="cli"&&O?O:null,cliArgs:Z});if(de(!1),!De.ok){ue(De.error||"Could not start session");return}C!=="ide"&&$.trim()&&(Sl(m.id,y,$),pt(m.id,y)),n()},[C,$,pt,n,c,l,tt,m,O,y,h]),gt=C?_c(C,C==="cli"&&!!O):"Start",Mt=C?Pc(C,C==="cli"&&!!O):"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(tr,{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:v.map(Z=>t.jsx("option",{value:Z.id,children:_t(Z,{fallbackId:Z.id})},Z.id))})}),C==="cli"&&t.jsx(tr,{title:"Hosted runtimes",description:"Review live runtimes, recovery snapshots, and recover or restart options without leaving this launch flow.",action:t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:le||!m,onClick:()=>W(!0),children:[t.jsx(Qt,{size:14}),mp()]})}),t.jsxs(tr,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:qe,disabled:le,children:"Browse…"}),children:[t.jsxs("select",{value:h,onChange:Z=>{const De=Z.target.value;S(De),De==="__custom__"?qe():ue("")},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"}),p.map(Z=>t.jsxs("option",{value:Z.id,children:[Z.id===x?"⭐ ":"",bn(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(Ds,{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 ${y===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>g(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(tr,{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(Al,{busy:le,savedSessionsLoading:G,savedSessionsError:U,selectedSession:Ge,onRefresh:()=>{!m||!y||et(m.id,y)},onOpenHistory:()=>{!m||!y||(we(!0),Il({hasLoadedInitialResults:E,isLoading:G})&&et(m.id,y))},onClearSelection:()=>F("")}),Se&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${Se.includes("saved")||Se.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:Se})]}),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||!y||h==="__custom__"&&!tt,children:[t.jsx(Ra,{size:14}),le?Mt:gt]})]})]})}),ce&&t.jsx(jn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:pe,directories:Ne,busy:Ae,error:xe,onClose:()=>re(!1),onNavigate:At,onConfirm:Z=>{j(Z),te(Z),S("__custom__"),re(!1)}}),ae&&Be&&t.jsx(Xa,{activeConv:Be,ides:[],isCreatingChat:!1,isRefreshingHistory:G,savedSessions:N,isSavedSessionsLoading:G,isResumingSavedSessionId:X,savedHistoryFilters:be,onSavedHistoryFiltersChange:Y,onClose:()=>we(!1),onNewChat:()=>{F(""),we(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!m||!y||et(m.id,y)},onResumeSavedSession:Z=>{if(!m||!y||X||!Z.canResume)return;const De=Re(Z);F(Z.providerSessionId),st(Z),oe(Z.providerSessionId),we(!1),de(!0),ue(""),l(m.id,"cli",y,{workspaceId:De.workspaceId,workspacePath:De.workspacePath,resumeSessionId:Z.providerSessionId}).then($e=>{if(!$e.ok){ue($e.error||"Could not resume session");return}n()}).finally(()=>{de(!1),oe($e=>$e===Z.providerSessionId?null:$e)})}}),he&&m&&t.jsx(cx,{machineCards:[{id:m.id,label:_t(m,{fallbackId:m.id}),subtitle:[m.platform||"machine",dl(m)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:m.id,sendDaemonCommand:f,onOpenConversation:Z=>{W(!1),n(),d(Z)},onClose:()=>W(!1)})]}):null}function dx(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 ux(e){return e instanceof Error?e.message:String(e||"")}function mx(e){const s=ux(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function px({showMobileChatMode:e,isMobile:s,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:f,mobileChatConversations:d,hiddenConversations:b,ides:v,actionLogs:w,sendDaemonCommand:A,setLocalUserMessages:m,setActionLogs:p,isStandalone:x,initialDataLoaded:h,userName:S,requestedMobileTabKey:_,onRequestedMobileTabConsumed:j,requestedMachineId:C,onRequestedMachineConsumed:k,requestedMobileSection:y,onRequestedMobileSectionConsumed:g,containerRef:$,isSplitMode:L,numGroups:M,groupSizes:R,groupedConvs:O,clearedTabs:F,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:W,onDesktopActiveTabChange:X,onRequestScrollToBottom:oe,onHideConversation:le,onShowHiddenConversation:de,onShowAllHiddenConversations:Se,scrollToBottomRequest:ue,machineEntries:ce,onBrowseMachineDirectory:re,onSaveMachineWorkspace:pe,onLaunchMachineIde:te,onLaunchMachineProvider:Ne,onListMachineSavedSessions:ke,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),[pt,tt]=lt.useState(!1),[Ct,ft]=lt.useState(!1),st=lt.useCallback(J=>{var Me;ir.flushSync(()=>{de(J)}),(Me=Pe.current)==null||Me.restoreHiddenTabToSavedLocation(J.tabKey)},[de]),Re=lt.useCallback(J=>{var Ve;const Me=d.find(Fe=>dr(Fe,J))||b.find(Fe=>dr(Fe,J));Me&&(b.some(Fe=>Fe.tabKey===Me.tabKey)&&st(Me),X(Me.tabKey),(Ve=Pe.current)==null||Ve.activateConversationTab(Me.tabKey),oe(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,b,d,X,Q,We,oe]),[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=mr(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,...Rs(r)})}catch(ie){mx(ie)||console.error("[Shortcut approval] Failed:",ie)}},[r,A]),{isMac:$e,actionDefinitions:ot,actionShortcuts:K,shortcutListening:H,shortcutListeningDraft:z,setShortcutListening:q,setShortcutListeningDraft:se,saveShortcuts:Ce}=Fh({enabled:gt&&!pt,onTrigger:J=>{var Me,Ve,Fe,D,ee,ie,Ke,Le,Ee,Xe,je,ut,es,Us,zs,wr;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"){(ie=Pe.current)==null||ie.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"){(es=Pe.current)==null||es.moveActiveTabToDownPane();return}if(J==="triggerPrimaryApprovalAction"){De(0);return}if(J==="triggerSecondaryApprovalAction"){De(1);return}if(J==="triggerTertiaryApprovalAction"){De(2);return}if(J==="setActiveTabShortcut"){(Us=Pe.current)==null||Us.setShortcutForActiveTab();return}if(J==="selectPreviousGroupTab"){(zs=Pe.current)==null||zs.activatePreviousTabInGroup();return}if(J==="selectNextGroupTab"){(wr=Pe.current)==null||wr.activateNextTabInGroup();return}!r||!nt(r)||Ze(r)||J==="toggleCliView"&&f(u==="chat"?"terminal":"chat")}}),Te=lt.useCallback(()=>{tt(!1),q(null),se([])},[q,se]),Ie=lt.useMemo(()=>bt==="all"?ot:ot.filter(J=>dx(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(!pt||H)return;const J=Me=>{Me.key==="Escape"&&(Me.preventDefault(),Te())};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[Te,pt,H]),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(ip,{activeConv:r,wsStatus:n,isConnected:a,conversations:Y,hiddenConversations:b,onOpenHistory:i,onHideConversation:le,onShowConversation:st,onShowAllHidden:Se,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:()=>ft(!0),actionShortcuts:K,onOpenRemote:()=>{!r||nt(r)||Ze(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:f}),e?t.jsx(Lh,{conversations:d,hiddenConversations:b,ides:v,actionLogs:w,sendDaemonCommand:A,setLocalUserMessages:m,setActionLogs:p,isStandalone:x,userName:S,requestedActiveTabKey:_,onRequestedActiveTabConsumed:j,requestedMachineId:C,onRequestedMachineConsumed:k,requestedMobileSection:y,onRequestedMobileSectionConsumed:g,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowHiddenConversation:st,onShowAllHiddenConversations:Se,onOpenNewSession:()=>ft(!0),notificationStateBySessionId:xe,liveSessionInboxState:ve,onMarkNotificationTargetRead:We}):s?t.jsx(Bh,{containerRef:$,isSplitMode:L,numGroups:M,groupSizes:R,groupedConvs:O,clearedTabs:F,ides:v,actionLogs:w,sendDaemonCommand:A,setLocalUserMessages:m,setActionLogs:p,isStandalone:x,hasRegisteredMachines:ce.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(Zh,{visibleConversations:Y,clearedTabs:F,ides:v,actionLogs:w,sendDaemonCommand:A,setLocalUserMessages:m,setActionLogs:p,isStandalone:x,hasRegisteredMachines:ce.length>0,initialDataLoaded:h,userName:S,toggleHiddenTab:be,actionShortcuts:K,registerActionHandlers:J=>{Pe.current=J},notificationStateBySessionId:xe,liveSessionInboxState:ve,onActiveTabChange:X,requestedActiveTabKey:he,onRequestedActiveTabConsumed:W,onRequestScrollToBottom:oe,scrollToBottomRequest:ue}),Ct&&t.jsx(lx,{machines:ce,conversations:d,ides:v,onClose:()=>ft(!1),onBrowseDirectory:re,onSaveWorkspace:pe,onLaunchIde:te,onLaunchProvider:Ne,onListSavedSessions:ke,sendDaemonCommand:A,onOpenConversation:J=>{ft(!1),de(J),X(J.tabKey),oe(J.tabKey,"conversation-open")}}),pt&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick: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 ${H===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:H===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),se([])},children:H===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 Xn=[{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 fx({onClose:e}){const[s,r]=o.useState(0),n=Xn[s],a=s===Xn.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:Xn.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 hx({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 xx({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),u=o.useMemo(()=>Ec(s),[s]),f=o.useMemo(()=>e?Ja(e,n,{machineNames:u,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,u,r]),d=o.useMemo(()=>f.find(p=>p.streamSource==="native"),[f]),b=o.useMemo(()=>f.filter(p=>p.streamSource==="agent-stream"),[f]),v=o.useMemo(()=>e?Ft(f,e.id):null,[f,e]);o.useEffect(()=>{i&&l(i)},[i]),o.useEffect(()=>{if(i||!v)return;const p=v.streamSource==="native"?"native":v.tabKey;!p||c===p||c==="native"&&l(p)},[c,v,i]),o.useEffect(()=>{var p;c!=="native"&&(b.some(x=>x.tabKey===c)||l(((p=b[0])==null?void 0:p.tabKey)||"native"))},[c,b]),o.useEffect(()=>{c==="native"&&(d||b[0]&&l(b[0].tabKey))},[c,d,b]);const w=o.useMemo(()=>c==="native"&&d?d:b.find(p=>p.tabKey===c)||v||d||b[0],[c,d,v,b]),A=o.useMemo(()=>b.map(p=>({tabKey:p.tabKey,title:Tc(p)||a,status:p.status})),[b,a]),m=o.useCallback(p=>{if(p)return f.find(x=>dr(x,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[f]);return{activeChatTab:c,setActiveChatTab:l,activeConv:w,conversations:f,extensionTabs:A,hasExtensions:A.length>0,resolveConversationByTarget:m}}function bx({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:u,isStandalone:f,userName:d,onOpenHistory:b,onConversationChange:v,onClose:w}){const[A,m]=o.useState("split"),[p,x]=o.useState(()=>rs(e)?"native":e.tabKey),h=o.useRef(null),S=o.useMemo(()=>s||r.find(I=>I.id===e.routeId),[e.routeId,s,r]),_=o.useMemo(()=>dt((S==null?void 0:S.type)||""),[S==null?void 0:S.type]),{conversations:j,extensionTabs:C,hasExtensions:k}=xx({ideData:S,allIdes:r,connectionStates:n,localUserMessages:i,ideName:_||"IDE",preferredTabKey:rs(e)?void 0:e.tabKey}),y=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(rs(e)){x("native");return}x(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(p==="native"){if(j.some(I=>I.streamSource==="native"))return;(y==null?void 0:y.streamSource)==="agent-stream"&&x(y.tabKey);return}if(!j.some(I=>I.tabKey===p)){if((y==null?void 0:y.streamSource)==="agent-stream"){x(y.tabKey);return}x("native")}},[j,p,y]);const g=o.useMemo(()=>p==="native"?j.find(I=>I.streamSource==="native")||e:j.find(I=>I.tabKey===p)||e,[e,j,p]),$=Xc(g),L=o.useMemo(()=>$.status||$.modalMessage||$.modalButtons?{...g,...$.status?{status:$.status}:{},...$.modalMessage!==void 0?{modalMessage:$.modalMessage}:{},...$.modalButtons!==void 0?{modalButtons:$.modalButtons}:{}}:g,[g,$]),M=br(L),R=gn({sendDaemonCommand:c,activeConv:L,setLocalUserMessages:l,setActionLogs:u,isStandalone:f}),{connScreenshot:O,screenshotUsage:F,handleRemoteAction:N}=fl({doId:M,targetSessionId:pc(L),connState:L.connectionState||"new",viewMode:A}),P=o.useMemo(()=>a.filter(I=>I.routeId===L.tabKey),[a,L.tabKey]);o.useEffect(()=>{v==null||v(L)},[L,v]),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:Wa(g)||"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($d,{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:()=>b(g),title:"Chat History",children:[t.jsx(La,{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(hx,{hasExtensions:k,ideName:_||"IDE",activeChatTab:p,extensionTabs:C,onSelectTab:x}),t.jsx(Zi,{activeConv:L,onModalButton:R.handleModalButton}),t.jsx(xa,{activeConv:L,ideEntry:S,showMetaChips:!1,handleSendChat:R.handleSendChat,isSendingChat:R.isSendingChat,sendFeedbackMessage:R.sendFeedbackMessage,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.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(Yi,{addLog:()=>{},connState:L.connectionState||"new",connScreenshot:O,screenshotUsage:F,transportType:L.transport,onAction:N})})]})]})})}function gx({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=sp(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 yx({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:a,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:u,onNewHistoryChat:f,onSwitchHistorySession:d,onRefreshHistory:b,onResumeSavedHistorySession:v,remoteDialogConv:w,remoteDialogIdeEntry:A,connectionStates:m,actionLogs:p,localUserMessages:x,sendDaemonCommand:h,setLocalUserMessages:S,setActionLogs:_,isStandalone:j,userName:C,onOpenRemoteHistory:k,onRemoteConversationChange:y,onCloseRemoteDialog:g,cliStopDialogOpen:$,cliStopTargetConv:L,onCancelCliStop:M,onStopCliNow:R,onSaveCliAndStop:O,toasts:F,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(Xa,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:E,onSavedHistoryFiltersChange:B,onClose:u,onNewChat:f,onSwitchSession:d,onRefreshHistory:b,onResumeSavedSession:v}),w&&t.jsx(bx,{activeConv:w,ideEntry:A,ides:r,connectionStates:m,actionLogs:p,localUserMessages:x,sendDaemonCommand:h,setLocalUserMessages:S,setActionLogs:_,isStandalone:j,userName:C,onOpenHistory:k,onConversationChange:y,onClose:g}),$&&L&&(nt(L)||Ze(L))&&t.jsx(gx,{activeConv:L,canSaveAndStop:nt(L)&&!Ze(L)&&!!((U=L.resume)!=null&&U.supported),onCancel:M,onStopNow:R,onSaveAndStop:O}),t.jsx(Dc,{toasts:F,onDismiss:N,onClickToast:P}),G&&t.jsx(fx,{onClose:I})]})}function vx({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(Hs,{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],f=c.version||c.daemonVersion||"unknown",d=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:l}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",f]}),d&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):t.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:d?"Update now":"Upgrade"})]},c.id)})]}),!r&&t.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:t.jsx(It,{size:16})})]})}function wx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function jx(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 kx(e,s,r=Date.now()){return!e||!jx(s)?null:{tabKey:e,nonce:r}}function Sx(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 Nx(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 Cx(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function ji(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ix(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Ax(){var vo,wo,jo,ko,So;const{sendCommand:e}=Lt(),s=gr(),r=qc(),n=Aa(),a=Ws(),[i,c]=pd(),l=i.get("activeTab"),u=((vo=n.state)==null?void 0:vo.openRemoteForTabKey)||null,f=((wo=n.state)==null?void 0:wo.openMachineId)||null,d=((jo=n.state)==null?void 0:jo.mobileSection)||null,b=Sc(),v=b.ides||[],w=b.initialLoaded??!0,{updateRouteChats:A,setToasts:m}=b,[p,x]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),h=b.toasts||[],S=b.wsStatus||"connected",_=b.isConnected??!0,j=b.connectionStates||{},C=b.showReconnected||!1,{groupAssignments:k,setGroupAssignments:y,focusedGroup:g,setFocusedGroup:$,groupActiveTabIds:L,setGroupActiveTabIds:M,groupTabOrders:R,setGroupTabOrders:O,groupSizes:F,setGroupSizes:N,isMobile:P,hasHydratedStoredLayout:G,hydrateStoredLayout:I}=Ef(),[E,B]=o.useState(!1),[U,V]=o.useState(!1),[ae,we]=o.useState(null),[be,Y]=o.useState([]),[he,W]=o.useState(!1),[X,oe]=o.useState(null),[le,de]=o.useState(()=>to());o.useEffect(()=>ef(de),[]);const Se=o.useMemo(()=>wx({isMobile:P,mobileViewMode:le}),[P,le]),[ue,ce]=o.useState([]),[re,pe]=o.useState({}),[te,Ne]=o.useState({}),[ke,Ae]=o.useState({}),[T,xe]=o.useState(null),[ve,Q]=o.useState(null),[ye,_e]=o.useState(null),We=o.useRef(null);hr("Dashboard",{ideCount:v.length,toastCount:h.length,focusedGroup:g,groupCount:Object.keys(k).length,localMessageTabs:Object.keys(re).length,actionLogCount:ue.length});const Pe=o.useMemo(()=>v.filter(ne=>ne.type==="adhdev-daemon").sort(Ka),[v]),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,pt=(ze==null?void 0:ze.id)||null,tt=o.useMemo(()=>uf(v,te),[v,te]),{hiddenTabs:Ct,hideTab:ft,toggleTab:st,showTab:Re,showAllTabs:Ge}=df(),{conversations:Be,visibleConversations:qe,visibleTabKeys:At,resolveConversationBySessionId:bt,resolveConversationByTarget:jt}=kf({ides:tt,connectionStates:j,localUserMessages:re,clearedTabs:ke,hiddenTabs:Ct}),gt=o.useMemo(()=>new Map(Be.map(ne=>[ne.tabKey,Er(ne)])),[Be]),Mt=o.useCallback(ne=>{const fe=gt.get(ne)||Er({tabKey:ne});ft(fe)},[gt,ft]),Tt=o.useCallback(ne=>{const fe=gt.get(ne)||Er({tabKey:ne});st(fe)},[gt,st]),Dt=o.useCallback(ne=>{const fe=gt.get(ne)||Er({tabKey:ne});Re(fe)},[gt,Re]);zm(qe,Se),o.useEffect(()=>{Object.keys(te).length!==0&&Ne(ne=>mf(ne,v))},[v,te]);const Z=o.useMemo(()=>gu(v),[v]),{notifications:De,unreadCount:$e,notificationStateBySessionId:ot,markRead:K,markUnread:H,markTargetRead:z,deleteNotification:q}=ih({conversations:Be,liveSessionInboxState:Z}),se=o.useCallback(ne=>{const fe=De.find(me=>me.id===ne),ge=Math.max(Date.now(),(fe==null?void 0:fe.updatedAt)||0);K(ne,ge),fe!=null&&fe.sessionId&&e(fe.machineId||fe.routeId,"mark_session_seen",{sessionId:fe.sessionId,seenAt:ge}).catch(()=>{})},[K,De,e]),Ce=o.useCallback(ne=>{const fe=De.find(ge=>ge.id===ne);H(ne),fe!=null&&fe.sessionId&&e(fe.machineId||fe.routeId,"mark_notification_unread",{sessionId:fe.sessionId,notificationId:fe.id}).catch(()=>{})},[H,De,e]),Te=o.useCallback(ne=>{const fe=De.find(ge=>ge.id===ne);q(ne),fe!=null&&fe.sessionId&&e(fe.machineId||fe.routeId,"delete_notification",{sessionId:fe.sessionId,notificationId:fe.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:ie,moveTabToGroup:Ke,closeGroup:Le,handleResizeStart:Ee,splitTabRelative:Xe}=Uf({groupAssignments:k,setGroupAssignments:y,setFocusedGroup:$,setGroupActiveTabIds:M,setGroupTabOrders:O,groupSizes:F,setGroupSizes:N,isMobile:P,visibleConversations:qe,visibleTabKeys:At}),je=o.useMemo(()=>{var fe,ge;if(!P){if(T){const me=Be.find(Je=>Je.tabKey===T);if(me)return me}return qe[0]}const ne=L[g];if(ne){const me=Be.find(Je=>Je.tabKey===ne);if(me)return me}return((fe=ie[g])==null?void 0:fe[0])||((ge=ie[0])==null?void 0:ge[0])},[T,P,L,g,Be,ie,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 fe=rn(je,Z),ge=Nx({tabKey:je.tabKey,historySessionId:xr(je)||"",lastMessageHash:je.lastMessageHash||"",lastMessageAt:Number(je.lastMessageAt||0),timestamp:ms(je),liveState:fe}),me=ge.autoReadKey,Je=Sx({autoReadKey:me,shouldMarkSeen:ge.shouldMarkSeen,completedKey:Ie.current,pendingKey:Oe.current});if(!ge.shouldMarkSeen){Je.shouldCancelPending&&ne(),Ie.current=me;return}if(!Je.shouldSchedule)return;Je.shouldCancelPending&&ne();const xt=Ji(je),Et=()=>{if(document.visibilityState!=="visible"||Ie.current===me)return;Ie.current=me,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 qt=()=>{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=qt,document.addEventListener("visibilitychange",qt)},[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:es,consumeRequestedActiveTab:Us}=Sf({isMobile:P,urlActiveTab:l,resolveConversationBySessionId:bt,setSearchParams:c}),{remoteDialogConv:zs,remoteDialogIdeEntry:wr,remoteDialogActiveConv:Pl,setRemoteDialogActiveConv:Cn,openRemoteDialog:Dl,closeRemoteDialog:El}=Bf({isMobile:P,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:ut,conversations:Be,ides:v,resolveConversationByTarget:jt}),ht=Pl||zs||je,Ut=!!ht&&nt(ht)&&!Ze(ht),jr=o.useMemo(()=>{if(!ht||!Ut)return null;const ne=ht.daemonId||ht.routeId||"",fe=Wt(ht);return`${ne}:${fe}`},[ht,Ut]),$l=o.useMemo(()=>qe,[qe]),kr=P&&le==="chat",Kl=o.useMemo(()=>Be.filter(ne=>so(Ct,ne)),[Be,Ct]),Sr=o.useCallback(ne=>{const fe=new URLSearchParams(i);fe.set("activeTab",ne),c(fe,{replace:!0})},[i,c]),Bl=o.useCallback(async(ne,fe)=>wn(e,ne,fe),[e]),Ol=o.useCallback(async(ne,fe)=>{if(!fe.trim())return{ok:!1,error:"Choose a workspace path first."};try{const ge=await e(ne,"workspace_add",{path:fe.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]),Wl=o.useCallback(async(ne,fe,ge)=>{var me;try{const Je={ideType:fe,enableCdp:!0};(me=ge==null?void 0:ge.workspacePath)!=null&&me.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:fe,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]),Hl=o.useCallback(async(ne,fe,ge,me)=>{var xt,Et,qt;const Je=Date.now();try{const yt={cliType:ge};(xt=me==null?void 0:me.workspacePath)!=null&&xt.trim()?yt.dir=me.workspacePath.trim():me!=null&&me.workspaceId&&(yt.workspaceId=me.workspaceId),(Et=me==null?void 0:me.resumeSessionId)!=null&&Et.trim()&&(yt.resumeSessionId=me.resumeSessionId.trim()),Array.isArray(me==null?void 0:me.cliArgs)&&me.cliArgs.length>0&&(yt.cliArgs=me.cliArgs),(qt=me==null?void 0:me.initialModel)!=null&&qt.trim()&&(yt.initialModel=me.initialModel.trim());const vt=await e(ne,"launch_cli",yt),$t=(vt==null?void 0:vt.result)||vt,Vs=($t==null?void 0:$t.sessionId)||($t==null?void 0:$t.id);return vt!=null&&vt.success&&Vs?(Sr(Vs),{ok:!0}):vt!=null&&vt.success?(_e({machineId:ne,kind:fe,providerType:ge,workspacePath:(me==null?void 0:me.workspacePath)||null,resumeSessionId:(me==null?void 0:me.resumeSessionId)||null,startedAt:Je}),{ok:!0}):{ok:!1,error:(vt==null?void 0:vt.error)||($t==null?void 0:$t.error)||`Could not launch ${fe.toUpperCase()} session`}}catch(yt){return Ix(yt)?(_e({machineId:ne,kind:fe,providerType:ge,workspacePath:(me==null?void 0:me.workspacePath)||null,resumeSessionId:(me==null?void 0:me.resumeSessionId)||null,startedAt:Je}),{ok:!0}):{ok:!1,error:yt instanceof Error?yt.message:`Could not launch ${fe.toUpperCase()} session`}}},[Sr,e]),Fl=o.useCallback(async(ne,fe)=>{if(!ne||!fe)return[];try{const ge=await e(ne,"list_saved_sessions",{providerType:fe,kind:"cli",limit:30}),me=(ge==null?void 0:ge.result)??ge;return Array.isArray(me==null?void 0:me.sessions)?me.sessions:[]}catch(ge){return console.error("List saved sessions failed",ge),[]}},[e]);o.useEffect(()=>{if(!ye)return;const ne=ji(ye.workspacePath),fe=v.find(me=>{var yt,vt,$t,Vs;if(!me||me.type==="adhdev-daemon"||Cx(me.daemonId||me.id)!==ye.machineId||(ur(me)?"cli":Ts(me)?"acp":"ide")!==ye.kind||String(me.agentType||me.type||"")!==ye.providerType)return!1;if(ye.resumeSessionId)return String(me.providerSessionId||"")===ye.resumeSessionId;if(ne){const An=ji(me.workspace||me.runtimeWorkspaceLabel);return An?An===ne:!1}return Number(me.lastUpdated||me._lastUpdate||me.timestamp||((Vs=($t=(vt=(yt=me.activeChat)==null?void 0:yt.messages)==null?void 0:vt.at)==null?void 0:$t.call(vt,-1))==null?void 0:Vs.timestamp)||0)>=ye.startedAt-5e3});if(!fe)return;const ge=xc({entrySessionId:fe.sessionId,entryInstanceId:fe.instanceId,entryRouteId:fe.id,conversations:Be});ge&&(_e(null),Sr(ge))},[Be,Sr,v,ye]),o.useEffect(()=>{if(!ye)return;const ne=window.setTimeout(()=>{_e(fe=>!fe||fe.startedAt!==ye.startedAt?fe:null)},45e3);return()=>window.clearTimeout(ne)},[ye]),pf({visibleConversations:qe,clearedTabs:ke,setClearedTabs:Ae,setActionLogs:ce}),Nf({ides:v,sendDaemonCommand:e,setToasts:m,setLocalUserMessages:pe,resolveConversationByTarget:jt});const{isRefreshingHistory:Ul,handleRefreshHistory:zl}=si({sendDaemonCommand:e,activeConv:je,chats:(ko=v.find(ne=>ne.id===(je==null?void 0:je.routeId)))==null?void 0:ko.chats,updateRouteChats:A,setToasts:m,setLocalUserMessages:pe,setClearedTabs:Ae}),{isCreatingChat:Vl,isRefreshingHistory:Gl,handleSwitchSession:ql,handleNewChat:Yl,handleRefreshHistory:Xl}=si({sendDaemonCommand:e,activeConv:ht,chats:(So=v.find(ne=>ne.id===(ht==null?void 0:ht.routeId)))==null?void 0:So.chats,updateRouteChats:A,setToasts:m,setLocalUserMessages:pe,setClearedTabs:Ae}),In=o.useCallback(async()=>{if(!(!ht||!Ut||he)){W(!0);try{const ne=ht.daemonId||ht.routeId,fe=Wt(ht),ge=await e(ne,"list_saved_sessions",{agentType:fe,providerType:fe,kind:"cli",limit:50}),me=(ge==null?void 0:ge.result)??ge;Y(Array.isArray(me==null?void 0:me.sessions)?me.sessions:[])}catch(ne){console.error("Refresh saved sessions failed",ne),Y([])}finally{W(!1)}}},[ht,he,Ut,e]);o.useEffect(()=>{if(!E){We.current=null;return}if(!Ut){We.current=null,Y([]),W(!1);return}!jr||he||We.current!==jr&&(We.current=jr,In())},[In,E,he,Ut,jr]);const Jl=o.useCallback(async ne=>{if(!ht||!Ut||!ne.providerSessionId||!ne.workspace)return;const fe=ht.daemonId||ht.routeId,ge=Wt(ht);try{oe(ne.providerSessionId);const me=await e(fe,"launch_cli",{cliType:ge,dir:ne.workspace,resumeSessionId:ne.providerSessionId,initialModel:nc(ne.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Je=(me==null?void 0:me.result)??me,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 qt=new URLSearchParams(Et);return qt.set("activeTab",xt),qt},{replace:!0}),B(!1)}catch(me){console.error("Resume saved session failed",me)}finally{oe(null)}},[ht,Ut,e,c]);Kf({urlActiveTab:P&&!kr?l:null,conversations:Be,resolveConversationBySessionId:bt,normalizedGroupAssignments:Fe,hasHydratedStoredLayout:P&&!kr?G:!0,hydrateStoredLayout:P&&!kr?I:()=>{},setGroupActiveTabIds:M,setFocusedGroup:$,setSearchParams:c,historyModalOpen:E,activeConv:je,isRefreshingHistory:Ul,ides:v,handleRefreshHistory:zl});const ho=o.useCallback(async(ne,fe)=>{const ge=fe||ae||je;if(!ge||!nt(ge)&&!Ze(ge))return;const me=Wt(ge),Je=ge.routeId||ge.daemonId||"";try{await e(Je,"stop_cli",{cliType:me,targetSessionId:ge.sessionId,mode:ne})}catch(xt){console.error("Stop CLI failed:",xt)}},[je,ae,e]),Ql=o.useCallback(async ne=>{const fe=ne||je;!fe||!nt(fe)&&!Ze(fe)||(we(fe),V(!0))},[je]),Zl=o.useMemo(()=>!je||!nt(je)||Ze(je)?null:$s(je),[je]),ed=o.useCallback(async ne=>{if(!je||!nt(je)||Ze(je))return;const fe=$s(je);if(fe===ne)return;const ge=je.sessionId;ge&&Ne(me=>({...me,[ge]:ne}));try{await e(os(je)||je.routeId,"set_cli_view_mode",{targetSessionId:je.sessionId,cliType:Wt(je),mode:ne})}catch(me){const Je=no(me);ge&&!Je&&Ne(xt=>{const Et={...xt};return fe===Zc(v,ge)?delete Et[ge]:Et[ge]=fe,Et}),ro(me)?console.warn(Je?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",me instanceof Error?me.message:String(me)):console.error("Failed to switch CLI view mode:",me)}},[je,v,e]),{versionMismatchDaemons:td,hasRequiredVersionDaemons:xo,appVersion:sd,versionBannerDismissed:rd,setVersionBannerDismissed:nd,upgradingDaemons:ad,handleBannerUpgrade:od}=zf({ides:v,sendDaemonCommand:e}),bo=o.useCallback(ne=>{xe(ne.tabKey),c(fe=>{const ge=new URLSearchParams(fe),me=mm(ne);return me?ge.set("activeTab",me):ge.delete("activeTab"),ge},{replace:!0})},[c]),go=o.useCallback(ne=>{Dt(ne.tabKey),bo(ne)},[bo,Dt]),id=o.useCallback(ne=>{Mt(ne.tabKey)},[Mt]),yo=o.useCallback((ne,fe)=>{const ge=kx(ne,fe);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(np,{wsStatus:S,showReconnected:C}),t.jsx(ap,{terminalBackend:it,isStandalone:Qe,machineLabel:et,machineKey:pt}),(!rd||xo)&&t.jsx(vx,{daemons:td,targetVersion:sd,required:xo,upgradingDaemons:ad,onUpgrade:od,onDismiss:()=>nd(!0)}),t.jsx(px,{showMobileChatMode:kr,isMobile:P,activeConv:je,wsStatus:S,isConnected:_,onOpenHistory:ne=>{ne&&Cn(ne),B(!0)},onOpenRemote:Dl,onStopCli:Ql,activeCliViewMode:Zl,onSetActiveCliViewMode:ed,mobileChatConversations:$l,ides:v,actionLogs:ue,sendDaemonCommand:e,setLocalUserMessages:pe,setActionLogs:ce,isStandalone:Qe,initialDataLoaded:w,userName:b.userName,requestedMobileTabKey:es,onRequestedMobileTabConsumed:Us,requestedMachineId:f,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ve,isSplitMode:ee,numGroups:D,groupSizes:F,groupedConvs:ie,clearedTabs:ke,focusedGroup:g,setFocusedGroup:$,moveTabToGroup:Ke,splitTabRelative:Xe,closeGroup:Le,handleResizeStart:Ee,groupActiveTabIds:L,setGroupActiveTabIds:M,groupTabOrders:R,setGroupTabOrders:O,toggleHiddenTab:Tt,visibleConversations:qe,hiddenConversations:Kl,requestedDesktopTabKey:ut,onRequestedDesktopTabConsumed:Us,onDesktopActiveTabChange:xe,onRequestScrollToBottom:yo,onHideConversation:id,onShowHiddenConversation:go,onShowAllHiddenConversations:Ge,scrollToBottomRequest:ve,machineEntries:Pe,onBrowseMachineDirectory:Bl,onSaveMachineWorkspace:Ol,onLaunchMachineIde:Wl,onLaunchMachineProvider:Hl,onListMachineSavedSessions:Fl,notifications:De,notificationUnreadCount:$e,notificationStateBySessionId:ot,liveSessionInboxState:Z,onMarkNotificationRead:se,onMarkNotificationUnread:Ce,onDeleteNotification:Te,onMarkNotificationTargetRead:z}),t.jsx("style",{children:`
|
|
60
|
-
body { overflow: hidden; overscroll-behavior: none; }
|
|
61
|
-
`}),t.jsx(yx,{historyModalOpen:E,historyTargetConv:ht,ides:v,isHistoryCreatingChat:Vl,isHistoryRefreshingHistory:Ut?!1:Gl,savedHistorySessions:be,isSavedHistoryLoading:he,isResumingSavedHistorySessionId:X,onCloseHistory:()=>B(!1),onNewHistoryChat:Yl,onSwitchHistorySession:ql,onRefreshHistory:Ut?In:Xl,onResumeSavedHistorySession:Jl,remoteDialogConv:zs,remoteDialogIdeEntry:wr,connectionStates:j,actionLogs:ue,localUserMessages:re,sendDaemonCommand:e,setLocalUserMessages:pe,setActionLogs:ce,isStandalone:Qe,userName:b.userName,onOpenRemoteHistory:ne=>{ne&&Cn(ne),B(!0)},onRemoteConversationChange:Cn,onCloseRemoteDialog:El,cliStopDialogOpen:U,cliStopTargetConv:ae,onCancelCliStop:()=>{V(!1),we(null)},onStopCliNow:async()=>{V(!1),await ho("hard",ae),we(null)},onSaveCliAndStop:async()=>{V(!1),await ho("save",ae),we(null)},toasts:h,onDismissToast:ne=>m(fe=>fe.filter(ge=>ge.id!==ne)),onClickToast:ne=>{if(ne.targetKey){const fe=jt(ne.targetKey);fe&&($(Fe.get(fe.tabKey)??0),go(fe),yo(fe.tabKey,"toast-open"))}},showOnboarding:p,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}x(!1)}})]})}function Mx({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[f,d]=o.useState(null),[b,v]=o.useState(!1),[w,A]=o.useState(null),[m,p]=o.useState(!1),[x,h]=o.useState(""),S=o.useRef(null),_=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]),y=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,W=(B==null?void 0:B.trim())||(U?"(saved id)":V?"(default workspace)":ae?"(home)":"");j("info",`Launching ${E}${W?` in ${W}`:""}${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 oe=await r(e,"launch_cli",X),le=(oe==null?void 0:oe.result)||oe;return oe!=null&&oe.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: ${(oe==null?void 0:oe.error)||(le==null?void 0:le.error)}`,!0),(oe==null?void 0:oe.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]),g=o.useCallback(async(I,E,B,U)=>e?I?E.trim()?y({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,y]),$=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]),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]),O=o.useCallback(async I=>{if(!e||!I.trim())return!1;v(!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{v(!1)}},[e,j,r]),F=o.useCallback(async I=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){v(!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{v(!1)}}},[e,j,r]),N=o.useCallback(async I=>{var E;if(e){v(!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{v(!1)}}},[e,j,r]),P=o.useCallback(async I=>{var B;if(!e||!I.trim())return;const E=I.trim();v(!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{v(!1)}},[e,j,r]),G=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:x}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:x})}catch(I){j("warn",`Live nickname updated, but account sync failed: ${I.message}`)}j("info",`Nickname set to "${x||"(cleared)"}"`),p(!1)}catch(I){j("error",`Failed: ${I.message}`)}},[e,x,s,j,n,r]);return{logs:i,launchingIde:l,launchingAgentType:f,workspaceBusy:b,launchPick:w,setLaunchPick:A,editingNickname:m,setEditingNickname:p,nicknameInput:x,setNicknameInput:h,addLog:j,handleLaunchIde:k,runLaunchCliCore:y,handleLaunchCli:g,handleStopCli:$,handleRestartIde:L,handleStopIde:M,handleDetectIdes:R,handleWorkspaceAdd:O,handleWorkspaceRemove:F,handleWorkspaceSetDefault:N,handleWorkspaceResumePath:P,handleSaveNickname:G,setOnDefaultWorkspaceChanged:_}}function Tx({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var L;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:f,handleWorkspaceSetDefault:d}=i,[b,v]=o.useState(!1),[w,A]=o.useState(""),[m,p]=o.useState([]),[x,h]=o.useState(!1),[S,_]=o.useState(""),j=o.useCallback(async M=>{h(!0),_("");try{const R=await wn(c,e,M);A(R.path),p(R.directories)}catch(R){_(R instanceof Error?R.message:"Could not load folder")}finally{h(!1)}},[e,c]),C=o.useCallback(()=>{v(!0);const M=[...r.map(O=>O.workspace),...n.map(O=>O.workspace),...a.map(O=>O.workspace)],R=vn(s.platform,yn(M,s.defaultWorkspacePath,(s.workspaces||[]).map(O=>O.path)));j(R)},[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,y=s.availableMem??s.freeMem??s.totalMem,g=k&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-y)/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(Ar,{icon:t.jsx(zi,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?ju(s.uptime):"Waiting…"}),t.jsx(Ar,{icon:t.jsx(Pt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(Ar,{icon:t.jsx(pn,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(Ar,{icon:t.jsx(Od,{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(Po,{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(Po,{value:g,max:100,label:"Memory",color:"#3b82f6",detail:k?`${_n(s.totalMem-y)} / ${_n(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${_n(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(Ds,{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:bn(M.path,M.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:M.path,children:M.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void f(M.id),children:"Remove"})]},M.id))})]}),b&&t.jsx(jn,{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:x,error:S,confirmLabel:"Add workspace",onClose:()=>v(!1),onNavigate:M=>{j(M)},onConfirm:M=>{(async()=>{if(!M)return;await u(M)&&v(!1)})()}})]})}function Lx(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 Rx(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 Jn(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 ki(e){if(!e||typeof e!="object")return null;if(Jn(e))return e;const s=e,r=s.result;return Jn(r)?r:Jn(s.sourceConfig)?s.sourceConfig:null}function _x(e){const s=e.trim();return s||null}const Si=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Px=[{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 Dx({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,f]=o.useState([]),[d,b]=o.useState(""),[v,w]=o.useState([]),[A,m]=o.useState(""),p=o.useRef(null),x=o.useRef(null),h=y=>{f(g=>g.includes(y)?g.filter($=>$!==y):[...g,y])},S=()=>f([...Si]),_=()=>f([]);o.useEffect(()=>{var y;(y=p.current)==null||y.scrollIntoView({behavior:"smooth"})},[v]),o.useEffect(()=>()=>{x.current&&clearInterval(x.current)},[]);const j=o.useCallback(()=>{x.current&&clearInterval(x.current),x.current=setInterval(async()=>{try{const y=await r(e,"provider_auto_fix_status",{providerType:s.type});(y==null?void 0:y.running)===!1&&a==="running"&&(i("done"),w(g=>[...g,`
|
|
64
|
-
✅ Auto-fix completed!`]),x.current&&clearInterval(x.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 y=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...d?{comment:d}:{}});y!=null&&y.success&&(y!=null&&y.started||y!=null&&y.running)?(w(g=>[...g,"✅ Agent started. Monitoring progress..."]),j()):(i("error"),m((y==null?void 0:y.error)||"Failed to start auto-fix"))}catch(y){i("error"),m((y==null?void 0:y.message)||"Connection failed")}}},k=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),w(y=>[...y,`
|
|
65
|
-
⚠️ Auto-fix cancelled.`]),i("done"),x.current&&clearInterval(x.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:y=>y.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:Px.map(y=>t.jsxs("button",{onClick:()=>l(y.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===y.value?y.color+"66":"var(--border-subtle)",background:c===y.value?y.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===y.value?y.color:"var(--text-primary)"},children:y.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:y.desc})]},y.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:_,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Si.map(y=>t.jsxs("button",{onClick:()=>h(y),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(y)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(y)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(y)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(y)?"☑ ":"☐ ",y]},y))})]}),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:y=>b(y.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:[v.map((y,g)=>t.jsx("div",{className:y.startsWith("✅")?"text-green-400":"",style:y.startsWith("❌")||y.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:y},g)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:p})]}),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 Ex({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,f]=o.useState(""),[d,b]=o.useState(""),[v,w]=o.useState(!1),[A,m]=o.useState(""),[p,x]=o.useState(!1),h=C=>{const k=C.toLowerCase().replace(/[^a-z0-9-]/g,"");f(k),(!d||d===S(u))&&b(S(k))},S=C=>C.split("-").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(" "),_=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?(x(!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:p?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=>b(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:p?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:_,disabled:!u||!d||v,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||v?.4:1},children:v?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function $x({machineId:e,providers:s,sendDaemonCommand:r}){var L;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[f,d]=o.useState("all"),[b,v]=o.useState(null),[w,A]=o.useState(!1),[m,p]=o.useState(null),[x,h]=o.useState("normal"),[S,_]=o.useState(""),[j,C]=o.useState(!1),k=o.useCallback(async()=>{if(e)try{const M=await r(e,"get_provider_source_config",{}),R=ki(M);R&&(p(R),h(R.sourceMode),_(R.explicitProviderDir||""))}catch{}},[e,r]),y=o.useCallback(async()=>{if(e){c(!0);try{const M=await r(e,"get_provider_settings",{}),R=Lx(M);if(R){const O=Rx(R,s);O.sort((F,N)=>F.category.localeCompare(N.category)||F.displayName.localeCompare(N.displayName)),a(O)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&y(),m||k()},[]);const g=async(M,R,O)=>{u(`${M}.${R}`),a(F=>F.map(N=>N.type===M?{...N,values:{...N.values,[R]:O}}:N));try{const F=await r(e,"set_provider_setting",{providerType:M,key:R,value:O});F!=null&&F.success||y()}catch{y()}u(null)},$=async()=>{C(!0);try{const M=await r(e,"set_provider_source_config",{providerSourceMode:x,providerDir:_x(S)}),R=ki(M);R?(p(R),h(R.sourceMode),_(R.explicitProviderDir||"")):await k(),await y()}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 ${f===M?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.toUpperCase()},M))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>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:y,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:x,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=>_(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…"]})]})]}),f!=="all"&&n.filter(M=>M.category===f).length>1&&(()=>{const M=n.filter(N=>N.category===f),R=new Map;for(const N of M)for(const P of N.schema){if(P.type!=="boolean")continue;const G=R.get(P.key),I=!!(N.values[P.key]??P.default);G?(G.onCount+=I?1:0,G.total+=1):R.set(P.key,{label:P.label||P.key,onCount:I?1:0,total:1})}const O=[...R.entries()].filter(([,N])=>N.total===M.length);if(O.length===0)return null;const F=async(N,P)=>{for(const G of M)await g(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 ",f.toUpperCase()," providers (",M.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:O.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 F(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 F(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=>f==="all"||M.category===f).map(M=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:M.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:M.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:M.category==="acp"?"rgba(139,92,246,0.08)":M.category==="cli"?"rgba(59,130,246,0.08)":M.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:M.category==="acp"?"#a78bfa":M.category==="cli"?"#60a5fa":M.category==="ide"?"#86efac":"var(--status-warning)"},children:M.category}),M.category==="ide"&&t.jsx("button",{onClick:()=>v(s.find(R=>R.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(R=>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:[R.label||R.key,l===`${M.type}.${R.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),R.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:R.description})]}),t.jsx("div",{className:"shrink-0",children:R.type==="boolean"?t.jsx("button",{onClick:()=>g(M.type,R.key,!(M.values[R.key]??R.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:M.values[R.key]??R.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[R.key]??R.default?21:3}})}):R.type==="number"?t.jsx("input",{type:"number",value:Number(M.values[R.key]??R.default??0)||0,min:R.min,max:R.max,onChange:O=>{const F=parseInt(O.target.value)||0;R.min!==void 0&&F<R.min||R.max!==void 0&&F>R.max||g(M.type,R.key,F)},className:"machine-input w-20 text-center text-[11px]"}):R.type==="select"&&R.options?t.jsx("select",{value:String(M.values[R.key]??R.default??""),onChange:O=>g(M.type,R.key,O.target.value),className:"machine-input text-[11px]",children:R.options.map(O=>t.jsx("option",{value:O,children:O},O))}):t.jsx("input",{type:"text",value:String(M.values[R.key]??R.default??""),onBlur:O=>g(M.type,R.key,O.target.value),className:"machine-input w-[120px] text-[11px]"})})]},R.key))})]},M.type))}),b&&t.jsx(Dx,{machineId:e,provider:b,sendDaemonCommand:r,onClose:()=>v(null)}),w&&t.jsx(Ex,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>A(!1),onCreated:()=>{A(!1),y()}})]})}const Kx=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Bx({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Ox(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Wx(e){return e.trim().toLowerCase()}function Sn(e,s){const r=Wx(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function po(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function pr(e,s=220){const r=po(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function Hx(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 Ml(e,s){return e.filter(r=>Sn([r.level,r.message],s))}function Fx(e,s){return e.split(`
|
|
66
|
-
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Sn([r],s))}function Tl(e,s){return e.filter(r=>Sn([r.level,r.category,r.stage,r.interactionId,po(r.payload)],s))}function Ll(e,s){return e.filter(r=>Sn([r.kind,r.topic,r.interactionId,po(r.payload)],s))}function Ni(e){return e==="warn"||e==="error"}function Ux({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=>Ni(a.level)).length+r.filter(a=>Ni(a.level)).length}}function zx({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} ${pr(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}`:""} ${pr(i.payload,500)}`.trim())].join(`
|
|
70
|
-
`)),a.join(`
|
|
71
|
-
|
|
72
|
-
`)}function Vx({daemonLogs:e,trace:s,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=Ml(e,c),u=Tl(s,c),f=Ll(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})),b=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:pr(w.payload,320)||`${w.category}.${w.stage}`})),v=[...d,...b].sort((w,A)=>A.timestamp-w.timestamp);return{daemonCount:l.length,traceCount:u.length,webCount:f.length,issueCount:v.length,latestIssue:v[0]||null,hasAnyData:n==="text"||l.length>0||u.length>0||f.length>0,hasBlockingError:!!(a||i)}}function Ci(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Ii(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 Qn(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 Gx({machineId:e,sendDaemonCommand:s}){var ke,Ae;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,f]=o.useState([]),[d,b]=o.useState([]),[v,w]=o.useState(0),[A,m]=o.useState(0),[p,x]=o.useState(null),[h,S]=o.useState(!0),[_,j]=o.useState("info"),[C,k]=o.useState("info"),[y,g]=o.useState("all"),[$,L]=o.useState(""),[M,R]=o.useState(!0),[O,F]=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(()=>Ox(u,y),[u,y]),Y=o.useMemo(()=>Ml(r,$),[r,$]),he=o.useMemo(()=>Fx(c,$),[c,$]),W=o.useMemo(()=>Tl(be,$),[be,$]),X=o.useMemo(()=>Ll(d,$),[d,$]),oe=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]),de=o.useMemo(()=>C==="issues"?W.filter(T=>T.level==="warn"||T.level==="error"):C==="info"?W.filter(T=>T.level!=="debug"):W,[W,C]),Se=o.useMemo(()=>C==="issues"?[]:X,[X,C]),ue=o.useMemo(()=>Ux({daemonLogs:Y,daemonRawLines:he,trace:W,webEvents:X}),[Y,he,W,X]),ce=o.useMemo(()=>Vx({daemonLogs:r,trace:be,webEvents:d,daemonLogKind:a,daemonFetchError:N,traceFetchError:G,searchQuery:$}),[N,a,r,be,$,G,d]),re=o.useCallback(async()=>{if(!e)return;const[T,xe]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:_,since:v}),s(e,"get_debug_trace",Bx({count:120,since:A,category:y}))]);if(T.status==="fulfilled"){const ve=T.value,Q=(ve==null?void 0:ve.result)||ve,ye=Hx(Q);if(R(!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=>(v>0?[...We,...ye.entries]:ye.entries).slice(-300));const _e=ye.entries.reduce((We,Pe)=>Math.max(We,Number(Pe.timestamp||0)),v);_e>v&&w(_e)}else ye.kind!=="structured"&&v===0&&n([])}else R(!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(""),f(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(""),f([]);F(!1)}else F(!1),I(xe.reason instanceof Error?xe.reason.message:"Could not load daemon trace");b(Ps.list({limit:120})),x(Date.now())},[v,A,_,e,s,y]);o.useEffect(()=>{if(!e||(re(),!h))return;const T=setInterval(()=>{re()},3e3);return()=>clearInterval(T)},[h,re,e,E]),o.useEffect(()=>{if(h&&(oe.length>0||le.length>0||de.length>0||Se.length>0)){const T=we.current?"smooth":"instant";setTimeout(()=>{var xe;(xe=ae.current)==null||xe.scrollIntoView({behavior:T}),we.current=!0},50)}},[oe.length,le.length,de.length,Se.length,h]),o.useEffect(()=>{f([]),m(0),F(!0)},[y]);const pe=((ke=ce.latestIssue)==null?void 0:ke.level)==="error"?"danger":((Ae=ce.latestIssue)==null?void 0:Ae.level)==="warn"?"warning":"good",te=N||G?"danger":h?"good":"neutral",Ne=o.useCallback(async()=>{var xe;const T=zx({daemonLogs:oe,daemonRawLines:le,trace:de,webEvents:Se});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")}},[oe,le,de,Se]);return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"Level"}),["debug","info","warn","error"].map(T=>t.jsx("button",{onClick:()=>{j(T),n([]),l(""),i("empty"),w(0),R(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${_===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"}),Kx.map(T=>t.jsx("button",{onClick:()=>g(T.value),className:`machine-btn text-[10px] px-2 py-0.5 ${y===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+ (${ue.info})`},{id:"issues",label:`Issues (${ue.issues})`},{id:"all",label:`All (${ue.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"),f([]),b([]),w(0),m(0),x(null),P(""),I(""),R(!0),F(!0),Ps.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${Qn(ce.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 ",oe.length+le.length," · trace ",de.length," · web ",Se.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 ${Qn(pe)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),ce.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[ce.latestIssue.source," · ",ce.latestIssue.label]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:ce.latestIssue.detail}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[ce.issueCount," warn/error signal(s) · ",Ci(ce.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 ${Qn(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: ",Ci(p)]}),(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`:`${oe.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&&!ce.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"&&oe.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"&&oe.map((T,xe)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Ii(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",y==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[de.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:[O&&de.length===0&&!G&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!O&&G&&de.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:G}),!O&&de.length===0&&!G&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:$.trim()?"No trace entries match the current search.":y==="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."}),de.map(T=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ii(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:pr(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:[Se.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:[Se.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."}),Se.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:pr(T.payload,360)||"No payload"})]},T.id))]})]})]}),t.jsx("div",{ref:ae})]})}function Zn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function ea(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ai(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 qx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Yx(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 Xx(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 Jx({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),f=Yc(e,{enabled:!!e,includeSessions:!0,limit:Ho,intervalMs:Cm}),d=f.diagnostics,b=f.loading,v=f.applyDiagnostics,w=o.useMemo(()=>rx({diagnostics:d,loading:b,refreshing:l,error:n}),[d,b,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:Ho}),M=Zn(L);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Could not load hosted runtime diagnostics");v(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)}}},[v,e,r]);o.useEffect(()=>{!e||d||b||l||m()},[d,b,e,m,l]);const p=o.useCallback(async(L,M)=>{const R=`${L}:${M.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${M.displayName}?
|
|
73
|
-
This will terminate the hosted runtime.`))){c(R);try{const O=await r(e,L,{sessionId:M.sessionId}),F=Zn(O);if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.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(O){const F=O instanceof Error?O.message:"Session host action failed";at.showToast(F,"warning"),a(F)}finally{c(O=>O===R?null:O)}}},[e,m,r]),x=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",{}),R=Zn(M);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Duplicate prune failed");const O=R.result||{},F=Array.isArray(O.prunedSessionIds)?O.prunedSessionIds.length:0,N=typeof O.duplicateGroupCount=="number"?O.duplicateGroupCount:0;at.showToast(`Pruned ${F} duplicate runtime(s) across ${N} group(s)`,"success"),await m()}catch(M){const R=M instanceof Error?M.message:"Duplicate prune failed";at.showToast(R,"warning"),a(R)}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)||[]}:Nl(h),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,h]),_=S.liveRuntimes,j=S.recoverySnapshots,C=S.inactiveRecords,k=o.useMemo(()=>Xx(_),[_]),y=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),g=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[d==null?void 0:d.recentLogs]),$=(L,M)=>{var B;const R=i===`session_host_resume_session:${L.sessionId}`,O=i===`session_host_restart_session:${L.sessionId}`,F=i===`session_host_stop_session:${L.sessionId}`,N=mo(L.meta),P=A.get(L.sessionId),G=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,I=M==="recovery"?"Recover":"Resume",E=Cl(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 ${Yx(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:qx(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(Ta,{size:11})," ",G]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Ai(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:()=>{p("session_host_resume_session",L)},children:R?`${I}ing…`:I}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{p("session_host_restart_session",L)},children:O?"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:()=>{p("session_host_stop_session",L)},children:F?"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(Qt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:pp()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[k>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{x()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${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:b||l,children:[t.jsx(Hs,{size:13}),b||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(ws,{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:Ai(d.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:ea(d.hostStartedAt)})]})]}),g&&t.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(ws,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:g.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[ea(g.timestamp),g.sessionId?` · ${g.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(pn,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:_s("live")}),_.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:_.map(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(Qt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:_s("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:_s("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"}),y.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:y.map(L=>{var R;const M=h.find(O=>O.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)||((R=A.get(L.sessionId))==null?void 0:R.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:ea(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 Qx({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 ta({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 sa({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 Zx({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=nr(e,"0.8.97");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(ta,{icon:t.jsx(Zt,{size:13}),children:"Current Chats"}),t.jsx(sa,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(b=>{const v=pa(b);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(b),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(b)}),v>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:hn(v)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ks(b)})]},b.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ta,{icon:t.jsx(zi,{size:13}),children:"Recent Launches"}),t.jsx(sa,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(b=>{const{metaText:v,updatedLabel:w}=ll(b);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(b),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:b.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:v})]},b.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ta,{icon:t.jsx(ws,{size:13}),children:"Daemon Update"}),t.jsx(sa,{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(Hs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function eb(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const tb={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 Ur(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ra({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:f}){const d=Ws(),{handleLaunchIde:b,handleStopCli:v,handleRestartIde:w,handleStopIde:A,handleDetectIdes:m,launchingIde:p,launchingAgentType:x,addLog:h}=c,[S,_]=o.useState(null),j=o.useCallback(D=>{D&&d(ns(D))},[d]),C=tb[e],k=e==="ide",y=e==="acp",g=o.useMemo(()=>n.filter(D=>D.category===e&&(e==="ide"||D.installed!==!1)),[e,n]),$=o.useMemo(()=>new Map(g.map(D=>[D.type,D.displayName||D.type])),[g]),[L,M]=o.useState(""),[R,O]=o.useState(""),[F,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(""),[W,X]=o.useState(!1),[oe,le]=o.useState(()=>wt()),[de,Se]=o.useState(null),[ue,ce]=o.useState(f?"__custom__":u||s.defaultWorkspaceId||""),[re,pe]=o.useState(f||""),[te,Ne]=o.useState([]),[ke,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__"),[pt,tt]=o.useState("__home__"),[Ct,ft]=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&&!ue&&ce(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(f){ce("__custom__"),pe(f);return}u&&(ce(u),pe(""))},[u,f]),o.useEffect(()=>{k||L&&(g.some(D=>D.type===L)||(M(""),E("")))},[g,k,L]);const Be=(()=>{if(ue==="__custom__")return re.trim();if(!ue)return"";const D=(s.workspaces||[]).find(ee=>ee.id===ue);return(D==null?void 0:D.path)||""})(),qe=o.useCallback(D=>{const ee=Ge.current[D];ee&&(clearTimeout(ee),delete Ge.current[D]),Ne(ie=>ie.includes(D)?ie.filter(Ke=>Ke!==D):ie)},[]),At=o.useRef(new Set),bt=o.useCallback(async D=>{if(l){_e(!0),Pe("");try{const ee=await wn(l,r,D);xe(ee.path),pe(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;ce("__custom__"),Ae(!0);const D=a.map(ie=>ie.workspace),ee=vn(s.platform,yn(re.trim(),Be,f,D,s.defaultWorkspacePath,(s.workspaces||[]).map(ie=>ie.path)));bt(ee)},[re,f,bt,s.defaultWorkspacePath,s.platform,s.workspaces,a,Be,l]),gt=o.useCallback(D=>{const ee=String(D.workspace||"").trim();if(!ee)return;const ie=(s.workspaces||[]).find(Ke=>Ur(Ke.path)===Ur(ee));if(ie){ce(ie.id),pe("");return}ce("__custom__"),pe(ee)},[s.workspaces]),Mt=o.useCallback(D=>{const ee=String(D.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const ie=(s.workspaces||[]).find(Ke=>Ur(Ke.path)===Ur(ee));return ie?{workspaceId:ie.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 ie=await l(r,"list_saved_sessions",{providerType:D,kind:"cli",limit:30});if(st.current!==ee)return;const Ke=(ie==null?void 0:ie.result)??ie;U(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(ie){if(st.current!==ee)return;U([]),he(ie instanceof Error?ie.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(kl(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&&(ft(!0),ze.current().finally(()=>{ze.current=null,ft(!1),it(null)}))},[]),K=o.useCallback(D=>{if(!D)return;Ne(ie=>ie.includes(D)?ie:[...ie,D]);const ee=Ge.current[D];ee&&clearTimeout(ee),Ge.current[D]=setTimeout(()=>{Ne(ie=>ie.includes(D)?ie.filter(Ke=>Ke!==D):ie),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[H,z]=o.useState({}),[q,se]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const ee=await l(r,"get_ide_extensions",{}),ie=(ee==null?void 0:ee.result)||ee;ie!=null&&ie.success&&(ie!=null&&ie.ideExtensions)&&z(ie.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,ie=(D==null?void 0:D.workspacePath)??Be;if(k){await b(ee,ie?{workspace:ie}:void 0)&&K(ee);return}const Ke=await c.runLaunchCliCore({cliType:ee,dir:D!=null&&D.workspaceId?void 0:ie||void 0,workspaceId:(D==null?void 0:D.workspaceId)||void 0,useHome:(D==null?void 0:D.useHome)||!(D!=null&&D.workspaceId)&&!ie,argsStr:(D==null?void 0:D.argsStr)??(R||void 0),model:(D==null?void 0:D.model)??(y&&P||void 0),resumeSessionId:(D==null?void 0:D.resumeSessionId)||!y&&e==="cli"&&ee===L&&I||void 0});if(Ke.success||Ke.pending){const Le=(D==null?void 0:D.argsStr)??R;!k&&(Le!=null&&Le.trim())&&(Sl(r,ee,Le),Z(ee)),K(ee),Ke.success&&Ke.sessionId&&j(Ke.sessionId)}},[c,b,y,k,R,P,Z,K,r,j,Be,I,L]),Oe=_c(k?"ide":y?"acp":"cli",!k&&!y&&!!I),Ue=Pc(k?"ide":y?"acp":"cli",!k&&!y&&!!I),J=()=>{var Le;const D=k?dt(L):$.get(L)||L,ee=!k&&!y&&!!I,{options:ie,selectedKey:Ke}=gs({machine:s,currentWorkspaceId:ue&&ue!=="__custom__"?ue:null,currentWorkspacePath:Be});$e({title:ee?qa(D):fs("start-fresh",D),description:ee?Ya():hs("start-fresh"),confirmLabel:Oe,busyLabel:Ue,workspaceOptions:ie,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&&R.trim()?[{label:"Arguments",value:R.trim()}]:[],...y&&P.trim()?[{label:"Model",value:P.trim()}]:[]]},async()=>{const Ee=ie.find(Xe=>Xe.key===et.current);Ee!=null&&Ee.workspaceId?(ce(Ee.workspaceId),pe("")):Ee!=null&&Ee.workspacePath?(ce("__custom__"),pe(Ee.workspacePath)):(ce(""),pe("")),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):v(D.type,D.workspace,D.id)},Ve=o.useCallback(async(D,ee,ie=!1)=>{if(D.mode===ee){ie&&D.sessionId&&j(D.sessionId);return}if(!l||!D.sessionId){ie&&D.sessionId&&j(D.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:D.sessionId,cliType:D.type,mode:ee}),ie&&j(D.sessionId)}catch(Ke){const Le=no(Ke);ro(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:ue,onChange:D=>{const ee=D.target.value;if(ce(ee),ee==="__custom__"&&l){jt();return}ee!=="__custom__"&&pe("")},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?"⭐ ":"",bn(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…"})]})}),ue==="__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:re,onChange:D=>pe(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:ue==="__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:ue===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"),ie=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(ns(Xe),{state:{openRemoteForTabKey:Xe}}):d("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Le||M(Xe=>Xe===(D.type||"")?"":D.type||"")},disabled:!!p||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:p&&p!==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)}),ie&&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(Dd,{size:14})," Scan System"]})]}):g.length>0?g.map(D=>{const ee=L===D.type,ie=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 ${ie?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:ie?"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):g.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:[!y&&e==="cli"&&t.jsx(Al,{busy:!!x||!!p||te.includes(L),savedSessionsLoading:V,savedSessionsError:Y,selectedSession:De,onRefresh:()=>void Tt(L),onOpenHistory:()=>{L&&(X(!0),Il({hasLoadedInitialResults:we,isLoading:V})&&Tt(L))},onClearSelection:()=>E("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[y&&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:R,onChange:D=>O(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"}),F.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:F.map(D=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>O(D),title:D,children:D},D))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:J,disabled:!!x||!!p||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:x===L||p===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:x===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,ie=!k&&!y?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||"—"}),(ie==null?void 0:ie.mode)&&t.jsx("span",{className:ie.mode==="chat"?"text-violet-400":"text-text-secondary",children:ie.mode==="chat"?"Chat view":"Terminal view"})]}),ie&&(ie.runtimeKey||ie.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ie.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ie.runtimeKey]}),t.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Le;(Le=navigator.clipboard)==null||Le.writeText(`adhdev attach ${ie.runtimeKey}`),_(ie.runtimeKey||null),window.setTimeout(()=>{_(Ee=>Ee===ie.runtimeKey?null:Ee)},1200)},children:S===ie.runtimeKey?"Copied":"Copy"})]}),ie.runtimeWriteOwner&&t.jsx("span",{style:{color:ie.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ie.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:eb(ie.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${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(ns(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}=gs({machine:s,currentWorkspacePath:Le});$e({title:fs("restart-ide",dt(D.type)),description:hs("restart-ide"),confirmLabel:Bs("restart-ide"),busyLabel:Os("restart-ide"),workspaceOptions:Ee,selectedWorkspaceKey:Xe,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:dt(D.type)}]},async()=>{const je=Ee.find(es=>es.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(Hs,{size:14})})]}),y&&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(Zt,{size:14})}),ie&&Ke!=="stopped"&&t.jsxs(t.Fragment,{children:[ie.mode&&t.jsx(za,{mode:ie.mode,onChange:Le=>void Ve(ie,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:ie.mode==="chat"?t.jsx(Zt,{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}=gs({machine:s,currentWorkspacePath:Le});$e({title:fs("restart-stopped",Ee),description:hs("restart-stopped"),confirmLabel:Bs("restart-stopped"),busyLabel:Os("restart-stopped"),workspaceOptions:Xe,selectedWorkspaceKey:je,details:[{label:"Mode",value:C.label},{label:"Provider",value:Ee}]},async()=>{const ut=Xe.find(es=>es.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(Ra,{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] ${tc(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&&(H[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:(H[ee.type]||[]).map(Le=>t.jsxs("button",{disabled:q===`${ee.type}.${Le.type}`,onClick:async()=>{const Ee=`${ee.type}.${Le.type}`;se(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{se(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)})]}),ke&&l&&t.jsx(jn,{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=>{pe(D),ce("__custom__"),Ae(!1)}}),Qe&&t.jsx(lo,{title:Qe.title,description:Qe.description,details:Qe.details,workspaceOptions:Qe.workspaceOptions,selectedWorkspaceKey:pt,onWorkspaceChange:D=>{et.current=D,tt(D)},confirmLabel:Qe.confirmLabel,busyLabel:Qe.busyLabel,busy:Ct,onConfirm:ot,onCancel:()=>{ze.current=null,it(null)}}),W&&Dt&&t.jsx(Xa,{activeConv:Dt,ides:[],isCreatingChat:!1,isRefreshingHistory:V,savedSessions:B,isSavedSessionsLoading:V,isResumingSavedSessionId:de,savedHistoryFilters:oe,onSavedHistoryFiltersChange:le,onClose:()=>X(!1),onNewChat:()=>{E(""),X(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Tt(L)},onResumeSavedSession:D=>{if(!D.canResume||de)return;const ee=Mt(D);E(D.providerSessionId),gt(D),Se(D.providerSessionId),X(!1),Ie({type:D.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:D.providerSessionId}).finally(()=>{Se(ie=>ie===D.providerSessionId?null:ie)})}})]})}const Mi=[{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 sb({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:f,initialWorkspacePath:d,sendDaemonCommand:b}){var m;const[v,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:Mi.map(p=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${v===p.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>w(p.id),children:[t.jsx("span",{children:p.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${v===p.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[p.id]})]},p.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(m=Mi.find(p=>p.id===v))==null?void 0:m.helper})]}),v==="ide"&&t.jsx(ra,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:b,initialWorkspaceId:f,initialWorkspacePath:d}),v==="cli"&&t.jsx(ra,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:b,initialWorkspaceId:f,initialWorkspacePath:d}),v==="acp"&&t.jsx(ra,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:b,initialWorkspaceId:f,initialWorkspacePath:d})]})}function rb({onNicknameSynced:e}={}){var Se,ue,ce,re,pe,te,Ne,ke,Ae;const{id:s}=fd(),r=Ws(),n=Aa(),{sendCommand:a}=Lt(),i=gr(),c=qc(),l=Sc(),u=l.ides||[],f=l.initialLoaded??!0,d=u.find(T=>T.id===s&&T.type==="adhdev-daemon"),b=u.some(T=>T.type==="adhdev-daemon"),[v,w]=o.useState("workspace"),[A,m]=o.useState("ide"),p=o.useRef(null),[x,h]=o.useState(null),S=o.useRef("__home__"),[_,j]=o.useState("__home__"),[C,k]=o.useState(!1),y=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||v!=="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(()=>{})},[v,c,d,s]),of(s&&v==="overview"?[s]:[],{enabled:v==="overview",intervalMs:jm});const g=()=>{if(b){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},$=Mx({machineId:s,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:y});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 R=T=>M[T]||"",O=d?{id:d.id,hostname:sc(d,{fallbackId:d.id}),platform:((Se=d.machine)==null?void 0:Se.platform)||"unknown",arch:((ue=d.machine)==null?void 0:ue.arch)||"",cpus:((ce=d.machine)==null?void 0:ce.cpus)||0,totalMem:((re=d.machine)==null?void 0:re.totalMem)||0,freeMem:(pe=d.machine)==null?void 0:pe.freeMem,availableMem:(te=d.machine)==null?void 0:te.availableMem,loadavg:(Ne=d.machine)==null?void 0:Ne.loadavg,uptime:(ke=d.machine)==null?void 0:ke.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,F=u.filter(T=>T.daemonId===s&&T.type!=="adhdev-daemon").filter(T=>!ur(T)&&!Ts(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:Mu(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&&ur(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&&Ts(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=[...F.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:js(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:js(T.summaryMetadata)||T.workspace||void 0,workspace:T.workspace,summaryMetadata:T.summaryMetadata,lastLaunchedAt:T.lastLaunchedAt})):Y,W=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=>Ja(ve,{},{connectionStates:s&&T?{[s]:T}:void 0,defaultConnectionState:T})).filter(ve=>!(ve.transport==="pty"&&ve.mode==="terminal")).sort((ve,Q)=>pa(Q)-pa(ve))},[u,l.connectionStates,s]),X=o.useCallback(T=>{const xe=Ha(T);xe&&r(ns(xe))},[r]),oe=o.useCallback(()=>{p.current&&(k(!0),p.current().finally(()=>{p.current=null,k(!1),h(null)}))},[]),le=o.useCallback(T=>{if(!O)return;const{options:xe,selectedKey:ve}=gs({machine:O,currentWorkspacePath:T.workspace}),Q=async()=>{m(T.kind),w("workspace")};p.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"&&nc(T.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:T.providerSessionId});return}await Q()},S.current=ve,j(ve),h({title:T.kind==="ide"?fs("restart-ide",T.label):T.providerSessionId?qa(T.label):fs("start-fresh",T.label),description:T.kind==="ide"?hs("restart-ide"):T.providerSessionId?Ya():hs("start-fresh"),confirmLabel:T.kind==="ide"?Bs("restart-ide"):T.providerSessionId?on(!0):Bs("start-fresh"),busyLabel:T.kind==="ide"?Os("restart-ide"):T.providerSessionId?Va(!0):Os("start-fresh"),workspaceOptions:xe,details:[{label:"Mode",value:T.kind.toUpperCase()},...T.providerType?[{label:"Provider",value:T.providerType}]:[]]})},[$,O]);if(o.useEffect(()=>{w(we)},[I,we,s]),o.useEffect(()=>{be&&m(be)},[be,s]),!O)return f?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:g,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const de=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Pt,{size:14})," Workspace"]}),count:F.length+N.length+P.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Qt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(mn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ed,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(_d,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:g,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[$.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(O.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:[O.platform," · ",O.arch]}),t.jsxs("span",{children:[O.cpus," cores"]}),(d==null?void 0:d.version)&&t.jsxs("span",{children:["v",d.version]}),O.p2p.available&&t.jsxs("span",{children:["P2P ",O.p2p.state==="connected"?"connected":O.p2p.state]}),O.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:O.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:de.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 ${v===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 ${v===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:[v==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Zx,{machineEntry:d,providers:L,recentLaunches:he,currentConversations:W,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:le,onOpenConversation:X}),t.jsx(sb,{machine:O,machineId:s,providers:L,ideSessions:F,cliSessions:N,acpSessions:P,actions:$,getIcon:R,initialCategory:A,initialWorkspaceId:V,initialWorkspacePath:ae,sendDaemonCommand:a})]}),v==="providers"&&t.jsx($x,{machineId:s,providers:L,sendDaemonCommand:a}),v==="overview"&&t.jsx(Tx,{machineId:s,machine:O,ideSessions:F,cliSessions:N,acpSessions:P,actions:$,sendDaemonCommand:a}),v==="session-host"&&t.jsx(Jx,{machineId:s,cliSessions:N,sendDaemonCommand:a}),v==="logs"&&t.jsx(Gx,{machineId:s,sendDaemonCommand:a})]})})}),$.launchPick&&O&&t.jsx(Qx,{machine:O,launchPick:$.launchPick,actions:$}),x&&t.jsx(lo,{title:x.title,description:x.description,details:x.details,workspaceOptions:x.workspaceOptions,selectedWorkspaceKey:_,onWorkspaceChange:T=>{S.current=T,j(T)},confirmLabel:x.confirmLabel,busyLabel:x.busyLabel,busy:C,onConfirm:oe,onCancel:()=>{p.current=null,h(null)}}),t.jsx(Dc,{toasts:l.toasts||[],onDismiss:T=>l.setToasts(xe=>xe.filter(ve=>ve.id!==T)),onClickToast:T=>{T.targetKey&&r(ns(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 fo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function nb(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=fo();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(nb(e),{credentials:"same-origin",...s})}function Rl(){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 ab{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 Yt=new ab;function ob(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=fo();return r?`${s}?token=${encodeURIComponent(r)}`:s}const zr=ob(),Ti=3e3,ib=3e4;let Vt=null,cb=0;const un=new Map;let ls=null,or=null;function Li(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Qs(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function lb(e){return e==="connected"?"connected":e}async function Qr(e,s,r){const n=Np(e,r||{}),a=Vt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++cb}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{un.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);un.set(i,{resolve:f=>{clearTimeout(u),c(f)},reject:f=>{clearTimeout(u),l(f)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function Sa(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 db{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 Qr(this.daemonId,s,r)}async sendInput(s,r){return Qr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,ls&&(clearInterval(ls),ls=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Qr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Yt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ls=setInterval(r,2e3)}stopScreenshots(s){ls&&(clearInterval(ls),ls=null)}}let Bt=null;function ub(e){return(!Bt||Bt.daemonId!==e)&&(Bt=new db(e)),Bt}function mb({children:e}){const s=o.useRef(cr()),r=cr();s.current=r;const{setUserName:n}=vs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((m,p)=>{l(m),or==null||or(m,p)},[]),f=o.useRef(null),d=o.useRef(),b=o.useRef(Ti),v=o.useRef(!0),w=o.useRef(!1),A=o.useRef("initial_connect");return o.useEffect(()=>{v.current=!0,w.current=!1;function m(){var h,S;if(!v.current||((h=f.current)==null?void 0:h.readyState)===WebSocket.OPEN||((S=f.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${zr}...`),Qs("connect_attempt",{url:zr,reason:A.current,delayMs:b.current});let x;try{x=new WebSocket(zr)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),p();return}f.current=x,x.onopen=()=>{if(!v.current){x.close();return}u("connected"),b.current=Ti,Qs("open",{url:zr,reason:A.current}),as.resubscribeAll({sendData:Sa}),console.log("[Standalone WS] Connected")},Vt=x,x.onmessage=_=>{var j,C;try{const k=JSON.parse(_.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const y=un.get(k.requestId);y&&(un.delete(k.requestId),k.type==="error"?y.reject(new Error(((j=k.data)==null?void 0:j.message)||"Command failed")):y.resolve(k.data));return}if(k.type==="session_output"){const y=k.sessionId||k.cliId||k.cliType;y&&Yt.emitSessionOutput(y,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Yt.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 y=k.update;y&&as.publish(y);return}if(k.type==="status"||k.type==="initial_state"){const y=k.data;if(!y)return;const{injectEntries:g,markLoaded:$,getIdes:L}=s.current,M=y.instanceId||"standalone",R=L().find(N=>N.id===M),O=ub(M);Yt.register(M,O),Yt.setState(M,"connected"),u("connected",M),Yt.emitStatus(M,y);const F=an(y,{daemonId:M,existingDaemon:R,existingEntries:L()});Li("ws_status",{type:k.type,daemonId:M,sessions:(y.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:(y.recentLaunches||[]).map(N=>({id:N.id,providerType:N.providerType,kind:N.kind,workspace:N.workspace,lastLaunchedAt:N.lastLaunchedAt}))}),Li("entries",{daemonId:M,entries:F.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}))}),F.length>0&&g(F,{authoritativeDaemonIds:[M]}),$(),c.current!==M&&((C=i.current)==null||C.call(i),c.current=M,i.current=as.subscribe({sendData:Sa},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=an(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)}},x.onclose=_=>{v.current&&(Bt==null||Bt.stopScreenshots(),Bt&&Yt.setState(Bt.daemonId,"disconnected"),u("disconnected"),f.current=null,A.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,Qs("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),p())},x.onerror=_=>{w.current||!v.current||(A.current="error",Qs("error",{message:_ instanceof Event?"event":String(_),readyState:x.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function p(){if(!v.current)return;clearTimeout(d.current);const x=b.current;console.log(`[Standalone WS] Reconnecting in ${x}ms...`),Qs("schedule_reconnect",{reason:A.current,delayMs:x}),d.current=setTimeout(()=>{b.current=Math.min(b.current*1.5,ib),m()},x)}return m(),()=>{var x;v.current=!1,w.current=!0,(x=i.current)==null||x.call(i),i.current=null,c.current=null,clearTimeout(d.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,Vt=null),Bt&&(Bt.stopScreenshots(),Yt.unregister(Bt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function pb({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(or=(c,l)=>{r(c),l&&a(l)},()=>{or=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=lb(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(kd,{connectionOverrides:i,children:t.jsx(mb,{children:e})})}const _l="adhdev_standalone_font_preferences",ys={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Nn=[{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"}],fr=[{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"}],fb=new Set(Nn.map(e=>e.id)),hb=new Set(fr.map(e=>e.id));function Gt(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Zr("chat",s.chat),code:Zr("code",s.code),terminal:Zr("terminal",s.terminal)}}function Zr(e,s){const r=ys[e],n=s&&typeof s=="object"&&!Array.isArray(s)?s:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?fb:hb).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function en(e,s){var a;const r=Zr(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Nn:fr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function xb(e){const s=Gt(e),r=en("chat",s.chat),n=en("code",s.code),a=en("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function us(e,s=document.documentElement){const r=Gt(e),n=xb(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))s.style.setProperty(a,i);return r}function Na(e){const s=Gt(e);try{localStorage.setItem(_l,JSON.stringify(s))}catch{}return s}function bb(){try{const e=localStorage.getItem(_l);if(e)return Gt(JSON.parse(e))}catch{}return ys}function gb(){return us(bb())}function Zs(e,s){var n;const r=e==="chat"?Nn:fr;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const yb=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Oi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Qt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(mn,{}),label:"Settings"}];function vb({children:e}){const s=Ws(),r=Aa(),[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 b=!d;try{localStorage.setItem("sidebar-collapsed",b?"1":"0")}catch{}return b})},f=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:yb.map(d=>t.jsxs("div",{className:f(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(Wi,{})}),!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(Hi,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.97"]}),t.jsx($p,{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 wb=[{icon:t.jsx(Qt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Zt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Fi,{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(lr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Wi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],jb=[{icon:t.jsx(Bd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Oi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(fn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Rd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(Ta,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Pd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],kb=[{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 Sb(){return t.jsxs(Wc,{icon:t.jsx(Hi,{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.97"]}),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:wb.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:Kc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Oc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Bc.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:jb.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:kb.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(Hc,{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(Yd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function na(e,s,r){return{...e,[s]:r}}function aa({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:en(e,n)})]})]})]})}function Nb({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const f=JSON.stringify(e)!==JSON.stringify(s);return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&t.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&t.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),t.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[t.jsx(aa,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Nn,onChange:d=>i(na(e,"chat",d))}),t.jsx(aa,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:fr,onChange:d=>i(na(e,"code",d))}),t.jsx(aa,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:fr,onChange:d=>i(na(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: ",Zs("chat",e.chat.preset)," · Code: ",Zs("code",e.code.preset)," · Terminal: ",Zs("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Zs("chat",ys.chat.preset)," / ",Zs("code",ys.code.preset)]})]}),t.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:t.jsxs("div",{className:"chat-container-content",children:[t.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:t.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[t.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[t.jsx("span",{className:"chat-sender",children:"Hermes"}),t.jsx("span",{className:"chat-time",children:"now"})]}),t.jsxs("div",{className:"chat-markdown",children:[t.jsxs("p",{children:["Readable prose, ",t.jsx("strong",{children:"bold text"}),", and ",t.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),t.jsx("pre",{children:t.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),t.jsxs("div",{className:"chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"▸"}),t.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),t.jsxs("div",{className:"chat-msg-terminal",children:[t.jsx("div",{className:"chat-msg-header",children:"Terminal"}),t.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:c,disabled:r||!f,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),t.jsx("button",{type:"button",onClick:l,disabled:r||!f,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),t.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function Cb(){const{ides:e}=vs(),s=e.find(W=>W.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Lt(),{userName:a}=vs(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[f,d]=o.useState(null),[b,v]=o.useState(ys),[w,A]=o.useState(!1),[m,p]=o.useState(""),[x,h]=o.useState(""),[S,_]=o.useState("127.0.0.1"),[j,C]=o.useState(""),[k,y]=o.useState(""),[g,$]=o.useState(""),[L,M]=o.useState(""),[R,O]=o.useState(""),[F,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),_(X.standaloneBindHost);const oe=Gt(X.standaloneFontPreferences);v(oe),us(oe),Na(oe)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([P(),G()]).catch(W=>{M(W instanceof Error?W.message:String(W))})},[]),o.useEffect(()=>{us(b)},[b]);const I=W=>{const X=W.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=W=>{B(W);try{localStorage.setItem("adhdev_sound",W?"1":"0")}catch{}},V=async()=>{p(""),h(""),A(!0);try{const W=Gt(b),X=await zt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:W})}),oe=await X.json();if(!X.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save standalone font preferences");const le=Gt(oe.standaloneFontPreferences);d(oe),v(le),us(le),Na(le),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(W){p(W instanceof Error?W.message:String(W))}finally{A(!1)}},ae=()=>{const W=Gt(f==null?void 0:f.standaloneFontPreferences);p(""),h(""),v(W),us(W)},we=()=>{p(""),h(""),v(ys),us(ys)},be=async()=>{M(""),O(""),N(!0);try{const W=await zt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:S})}),X=await W.json();if(!W.ok)throw new Error((X==null?void 0:X.error)||"Failed to save standalone network preference");d(X),_(X.standaloneBindHost),O(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(W){M(W instanceof Error?W.message:String(W))}finally{N(!1)}},Y=async()=>{if(M(""),O(""),k.trim().length<4){M("Password must be at least 4 characters.");return}if(k!==g){M("New password and confirmation do not match.");return}N(!0);try{const W=await zt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,newPassword:k})}),X=await W.json();if(!W.ok)throw new Error((X==null?void 0:X.error)||"Failed to save password");u(X),await G(),C(""),y(""),$(""),O(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Rl()}catch(W){M(W instanceof Error?W.message:String(W))}finally{N(!1)}},he=async()=>{M(""),O(""),N(!0);try{const W=await zt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,clear:!0})}),X=await W.json();if(!W.ok)throw new Error((X==null?void 0:X.error)||"Failed to clear password");u(X),await G(),C(""),y(""),$(""),O("Standalone password disabled.")}catch(W){M(W instanceof Error?W.message:String(W))}finally{N(!1)}};return t.jsxs(Wc,{icon:t.jsx(mn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Pr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&t.jsx(Pr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),t.jsx(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.97"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(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:()=>_("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:()=>_("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:F,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:F?"Saving…":"Save default network mode"}),t.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(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(Pr,{variant:"error",children:L}),R&&t.jsx(Pr,{variant:"success",children:R}),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:W=>C(W.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:W=>y(W.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:g,onChange:W=>$(W.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{Y()},disabled:F,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:F?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{he()},disabled:F,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(W=>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 ${W.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:W.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:W.type})]},W.type))})}),t.jsx(Rt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Wp,{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(zp,{})]}),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(Zp,{})]}),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(Nb,{value:b,savedValue:Gt(f==null?void 0:f.standaloneFontPreferences),saving:w,error:m,notice:x,onChange:v,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(sf,{})]})]})}),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(Kp,{}),t.jsx(ds,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(qd,{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(Ld,{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:W=>c(W.target.value),onBlur:I,onKeyDown:W=>{W.key==="Enter"&&W.currentTarget.blur()}})]})})})]})}Ep();Jp();gb();const Ib=$i({baseUrl:"",getToken:fo});function Ab({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[f,d]=o.useState(!1),b=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(()=>{b()},[]),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 p=Gt(m.standaloneFontPreferences);us(p),Na(p)}catch{}})(),()=>{w=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const v=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(""),Rl()}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:v,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:f||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:f?"Signing in…":"Unlock dashboard"})]}):t.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&t.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):t.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function Ri(){const{ides:e,initialLoaded:s}=vs();if(!s)return t.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?t.jsx(ca,{to:`/machines/${r.id}`,replace:!0}):t.jsx(ca,{to:"/dashboard",replace:!0})}function Mb(){const e=o.useMemo(()=>({sendCommand:Qr,sendData:Sa}),[]);return t.jsx(hd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Cd,{client:Ib,children:t.jsx(Ab,{children:t.jsx(pb,{children:t.jsx(Ad,{value:e,children:t.jsx(vb,{children:t.jsxs(xd,{children:[t.jsx(is,{path:"/dashboard",element:t.jsx(Ax,{})}),t.jsx(is,{path:"/machine",element:t.jsx(Ri,{})}),t.jsx(is,{path:"/machines/:id",element:t.jsx(rb,{})}),t.jsx(is,{path:"/machines",element:t.jsx(Ri,{})}),t.jsx(is,{path:"/about",element:t.jsx(Sb,{})}),t.jsx(is,{path:"/settings",element:t.jsx(Cb,{})}),t.jsx(is,{path:"*",element:t.jsx(ca,{to:"/dashboard",replace:!0})})]})})})})})})})}Jm({connectionManager:Yt});bd(document.getElementById("root")).render(t.jsx(Mb,{}));
|