@adhdev/daemon-standalone 0.9.70 → 0.9.71
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 +137 -24
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-CVquu5qt.css +1 -0
- package/public/assets/index-DM3XHNI_.js +94 -0
- package/public/assets/{terminal-DbJP_JGY.js → terminal-BeBmUW3m.js} +1 -1
- package/public/assets/{vendor-BRZ4K-AC.js → vendor-CLec0455.js} +5 -5
- package/public/index.html +3 -3
- package/vendor/mcp-server/index.js +143 -26
- package/vendor/mcp-server/index.js.map +1 -1
- package/vendor/mcp-server/package.json +1 -1
- package/public/assets/index-BtTmBSZB.js +0 -101
- package/public/assets/index-rYYK5iTn.css +0 -1
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-DbJP_JGY.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var fd=Object.defineProperty;var pd=(e,s,r)=>s in e?fd(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Je=(e,s,r)=>pd(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as Ra,a as hd,b as xd,c as bd,u as xs,R as Nt,d as rr,t as gd,e as yd,D as vd,f as ca,g as la,h as La,i as wd,k as jd,B as kd,l as Sd,m as Vt,N as da,n as Nd}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 Cd(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 Ts=Cd();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 Td(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function Md(e,s){return Object.prototype.hasOwnProperty.call(e,s)}function Ei(e,s){if(!e)return s??null;if(!s)return e??null;const r=Md(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:s.messages,a={...s,...e,activeModal:e.activeModal??null,inputContent:e.inputContent??s.inputContent};return r?{...a,messages:n}:a}function qs(e,s){const r=Td(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerSessionId:e.providerSessionId??(s==null?void 0:s.providerSessionId),providerName:r??(s==null?void 0:s.providerName)??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerName??e.providerType,title:e.title??(s==null?void 0:s.title)??r??(s==null?void 0:s.providerName)??e.providerName??e.providerType,workspace:e.workspace??(s==null?void 0:s.workspace)??null,mode:e.mode??(s==null?void 0:s.mode),capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??(s==null?void 0:s.capabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),activeChat:Ei(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 $i(e,s,r){if(!(s!=null&&s.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(s)?s:e;if(!(e!=null&&e.length))return s;const n=s.map(a=>{const i=e.find(c=>c.id===a.id);return i?qs(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(s.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function Co(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:Co(i)?String(i.text||""):"").join(r):Co(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Ms(e){return _a(e,{normalizeWhitespace:!0})}const Bi=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,connectionRetryStatuses:void 0}),Ki=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function To(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 Wi(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,d=s.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),d&&(n.versionUpdateReason=d),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 Ad(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 jn(e){if(!e||typeof e!="object")return"";const s=e,r=Ad(Ms(s.content).slice(0,512));return[String(s.id||""),String(s._localId||""),String(s._turnKey||""),String(s.index??""),String(s.role||""),String(s.receivedAt??s.timestamp??""),r].join(":")}function Id(e,s){if(!Array.isArray(e))return e;if(s!=null&&s.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=jn(n);for(let i=0;i<a.length;i+=1)r^=a.charCodeAt(i),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:jn(e[0]),last:jn(e[e.length-1])}}function ua(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function ma(e,s,r){if(!e||!s||typeof e!="object"||typeof s!="object")return;if(ua(e)&&ua(s)){const c=e.messages;Array.isArray(c)&&c===s.messages&&r.add(c)}if(Array.isArray(e)&&Array.isArray(s)){const c=Math.min(e.length,s.length);for(let l=0;l<c;l+=1)ma(e[l],s[l],r);return}const n=e,a=s,i=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of i)c!=="messages"&&ma(n[c],a[c],r)}function Xs(e,s){return Array.isArray(e)?e.map(r=>Xs(r,s)):!e||typeof e!="object"?e:ua(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?Id(a,s):Xs(a,s)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,Xs(n,s)]))}function Rd(e,s){try{const r=new WeakSet;return ma(e,s,r),JSON.stringify(Xs(e,r))===JSON.stringify(Xs(s,r))}catch{return!1}}function fa(e,s,r){return Rd(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function Oi(e){var s;return e.daemonId||((s=e.id)==null?void 0:s.split(":")[0])||e.id}function Ld(e,s,r){s[r]!==void 0&&(e[r]=s[r])}function Mo(e,s,r,n){var l;const a=(l=s.chats)!=null&&l.length?s.chats:e.chats,i=$i(e.childSessions,s.childSessions,{preserveMissing:n}),c=Ei(s.activeChat,e.activeChat);return Wi(e,s,{...e,...s,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function _d(e,s,r){var a,i;const n={};s.status&&s.status!==e.status&&(n.status=s.status),s.cdpConnected!==void 0&&(n.cdpConnected=s.cdpConnected),s.childSessions!==void 0&&(n.childSessions=$i(e.childSessions,s.childSessions,{preserveMissing:r})),(a=s.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=s.chats);for(const c of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion"])Ld(n,s,c);return s.machineNickname!==void 0&&s.machineNickname!==e.machineNickname&&(n.machineNickname=s.machineNickname),s.versionMismatch===!0&&(n.versionMismatch=!0),n}function Pd(e,s,r,n){const a=_d(e,s,n),i=Object.keys(a).length>0?Wi(e,s,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return fa(e,i,r)}function Dd(e){const s=new Set(e.map(i=>i.id)),r=new Set,n=new Set,a=new Set;for(const i of e){const c=Oi(i);c&&r.add(c),c&&i.type!=="adhdev-daemon"&&n.add(c),c&&i.type==="adhdev-daemon"&&i._sessionListAuthoritative&&a.add(c)}return{incomingIds:s,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function Ed(e,s,r,n,a,i){return!a.has(s)||!i.has(s)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function $d(e,s,r,n,a){return e.transport?r.has(s)&&!n.has(s)?!0:a.has(s):!1}function Bd(e,s,r){var u,f;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(b=>({...b,_lastUpdate:n}));const i=new Map;for(const b of s)i.set(b.id,b);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=Dd(e);for(const b of e){const S=i.get(b.id);if(!S){i.set(b.id,{...b,_lastUpdate:n});continue}const g=To(b),h=To(S),k=Oi(b),p=!a.has(k);if(g>h){const N=Mo(S,b,n,p);i.set(b.id,fa(S,N,n));continue}if(g<h){i.set(b.id,Pd(S,b,n,p));continue}const x=b.timestamp||n,y=S._lastUpdate||S.timestamp||0;if(x>=y){const N=Mo(S,b,n,p);i.set(b.id,fa(S,N,n));continue}(u=b.chats)!=null&&u.length&&!((f=S.chats)!=null&&f.length)&&i.set(b.id,{...S,chats:b.chats})}for(const[b,S]of i){const g=S.daemonId||b.split(":")[0];if(!l.has(g))continue;if(a.has(g)&&m.has(g)&&!c.has(b)){i.delete(b);continue}const h=n-(S._lastUpdate||S.timestamp||0);Ed(S,g,h,c,a,d)&&i.delete(b)}for(const[b,S]of i){const g=S.daemonId||b.split(":")[0];if($d(S,g,l,d,i))continue;n-(S._lastUpdate||S.timestamp||0)>3e5&&S.status!=="online"&&i.delete(b)}return Array.from(i.values())}function Kd(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 Wd({children:e,connectionOverrides:s}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[d,m]=o.useState(void 0),u=o.useRef(r);o.useEffect(()=>{u.current=r},[r]);const f=o.useCallback((p,x)=>{n(y=>{let N=!1;const j=y.map(I=>I.id!==p||I.chats===x?I:(N=!0,{...I,chats:x}));return N?j:y})},[]),b=o.useCallback((p,x)=>{n(y=>{const N=y.length===0?p:Bd(p,y,x),j=!Kd(y,N);return j&&Ts.record({kind:"dashboard.entries_applied",payload:{incoming:No(p),next:No(N)}}),j?N:y})},[]),S=o.useCallback(()=>i(!0),[]),g=o.useMemo(()=>({injectEntries:b,markLoaded:S,getIdes:()=>u.current}),[b,S]),h=s,k=o.useMemo(()=>({ides:r,updateRouteChats:f,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(h==null?void 0:h.wsStatus)??"connected",isConnected:(h==null?void 0:h.isConnected)??!0,connectionStates:(h==null?void 0:h.connectionStates)??{},connectionTransports:(h==null?void 0:h.connectionTransports)??{},showReconnected:(h==null?void 0:h.showReconnected)??!1,retryConnection:h==null?void 0:h.retryConnection,retryServerConnection:h==null?void 0:h.retryServerConnection,connectionLoginUrl:h==null?void 0:h.connectionLoginUrl,isP2PActive:(h==null?void 0:h.isP2PActive)??!1,p2pStates:(h==null?void 0:h.p2pStates)??{},userRole:h==null?void 0:h.userRole,connectionRetryStatuses:h==null?void 0:h.connectionRetryStatuses,userName:d,setUserName:m}),[r,f,a,c,h==null?void 0:h.wsStatus,h==null?void 0:h.isConnected,h==null?void 0:h.connectionStates,h==null?void 0:h.connectionTransports,h==null?void 0:h.showReconnected,h==null?void 0:h.retryConnection,h==null?void 0:h.retryServerConnection,h==null?void 0:h.connectionLoginUrl,h==null?void 0:h.isP2PActive,h==null?void 0:h.p2pStates,h==null?void 0:h.userRole,h==null?void 0:h.connectionRetryStatuses,d]);return t.jsx(Ki.Provider,{value:g,children:t.jsx(Bi.Provider,{value:k,children:e})})}function Xt(){return o.useContext(Bi)}function nr(){return o.useContext(Ki)}function Fi(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 d=r==null?void 0:r(),m=a(l),u=l.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!l.startsWith("http")&&!s?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function c(l,d={}){const m={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(m.Authorization=`Bearer ${u}`);const f=a(l),b=new AbortController,S=setTimeout(()=>b.abort(),15e3);try{const g=await fetch(f,{...d,headers:m,signal:b.signal});if(g.status===401)throw n==null||n(),new Error("Unauthorized");if(!g.ok){const h=await g.json().catch(()=>({error:g.statusText}));throw new Error(h.error||`API Error: ${g.status}`)}return g.json()}finally{clearTimeout(S)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,d,m={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),execTerminal:(l,d,m)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:m})}),sendAgentMessage:(l,d,m)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:m})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,d,m)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:m?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,d,m={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Od=Fi({baseUrl:"http://localhost:3847"}),Fd=o.createContext(Od);function Hd({client:e,children:s}){return t.jsx(Fd.Provider,{value:e,children:s})}const Ud={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Hi=o.createContext(Ud);function zd({value:e,children:s}){return t.jsx(Hi.Provider,{value:e,children:s})}function xt(){return o.useContext(Hi)}function Vd(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)s^=n.charCodeAt(a),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function Gd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function qd(e){return e?Vd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Gd(e.content)]):""}const We={size:18};function Ui({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Pa({size:e=We.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polyline",{points:"15 18 9 12 15 6"})})}function ds({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),t.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),t.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),t.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function zi({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"9",cy:"7",r:"4"}),t.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),t.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Yd({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Xd({size:e=We.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Vi({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),t.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),t.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),t.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Jd({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"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 on({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Gi({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Qd({size:e=We.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Ht({size:e=We.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Tt({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Da({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t.jsx("polyline",{points:"14 2 14 8 20 8"}),t.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),t.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Zd({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function us({size:e=We.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function cr({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 ar({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function As({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M12 22v-5"}),t.jsx("path",{d:"M9 8V2"}),t.jsx("path",{d:"M15 8V2"}),t.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function vr({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"5",r:"2"}),t.jsx("circle",{cx:"5",cy:"19",r:"2"}),t.jsx("circle",{cx:"19",cy:"19",r:"2"}),t.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),t.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),t.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function qi({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),t.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Ea({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),t.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),t.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Yi({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function eu({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),t.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),t.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function $a({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function tu({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function cn({size:e=We.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Xi({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function su({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),t.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),t.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),t.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function ru({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),t.jsx("path",{d:"M12 2v6"}),t.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function nu({size:e=We.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function au({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),t.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function ln({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 ou({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"5"}),t.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),t.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),t.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),t.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),t.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),t.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),t.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),t.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function iu({size:e=We.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function cu({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function lu({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),t.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function du({size:e=We.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function uu({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),t.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function mu({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),t.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),t.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function fu({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}function pu({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function hu({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),t.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),t.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),t.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),t.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),t.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),t.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),t.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),t.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),t.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function xu({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),t.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function bu({size:e=We.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Ji=[hd,{singleTilde:!1}],Qi=[Ji,xd,bd],gu=[Ji],Ba=200,yu=80,Ao=650,Ks=new Map;function Gr(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function vu(e,s){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(s||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${qd(n)}`}function wu(e,s,r,n){return e||!s?!1:Gr(r,n)}function ju({scrollTop:e,scrollHeight:s,clientHeight:r,topThresholdPx:n=yu,bottomThresholdPx:a=Ba}){const i=Math.max(0,Number(e)||0),c=Math.max(0,Number(s)||0),l=Math.max(0,Number(r)||0);return Math.max(0,c-l)<=0?{showTop:!1,showBottom:!1}:{showTop:i>n,showBottom:Math.max(0,c-i-l)>a}}function ku(e){return ju({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Ys(e,s=Ba){return!!e&&e.fromBottom>=s}function Su(e,s){return Gr(e,s)?!Ys(e):!0}function Nu({hasSelection:e,userScrolledUp:s,hasChatContentChanged:r=!0}){return!(e||s||!r)}function Cu({hasSelection:e,userScrolledUp:s,contextAutoScrollActive:r}){return e?!1:r||!s}function kn(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function Zi(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Tu(e,s,r){return Number(e.receivedAt||r[qr(e,s)]||0)||0}function ec(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Mu(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function wr(e,s){if(!e)return s;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||s}catch{return e.split(/[\\/]/).filter(Boolean).pop()||s}}function Sn(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function Io(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):ec(e)?t.jsx(Ra,{remarkPlugins:Qi,children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function jr({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:Io(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=Sn(r);return a?t.jsx("img",{src:a,alt:wr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=Sn(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=Sn(r);return a?t.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:wr(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||wr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=wr(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}),Io(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 qr(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 Au=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(Ra,{remarkPlugins:gu,children:s.text}),t.jsx("span",{className:"action-time",children:Zi(s.timestamp)})]})},(e,s)=>e.log===s.log),Iu=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var I,M,w;const d=(s.role||"").toLowerCase(),m=d==="user"||d==="human",u=s.kind||(d==="tool"?"tool":"standard"),f=Mu(s.content)?s.content:null,b=!!(f!=null&&f.some(v=>v.type!=="text")),S=_a(s.content,{joiner:`
|
|
4
|
-
`});if(u==="thought"){const v=typeof((I=s.meta)==null?void 0:I.label)=="string"?s.meta.label:"Thought";return t.jsxs("div",{className:"self-start chat-msg-thought",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx(nu,{size:13}),t.jsx("span",{children:v})]}),t.jsx("div",{className:"chat-msg-body",children:S})]})}if(u==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),b&&f?t.jsx("div",{className:"tool-text w-full",children:t.jsx(jr,{parts:f,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:S})]});if(u==="terminal"){const v=(M=s.meta)!=null&&M.isRunning?"⏳":"✅",$=typeof((w=s.meta)==null?void 0:w.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:v}),t.jsx("span",{children:$})]}),b&&f?t.jsx("div",{className:"chat-msg-body",children:t.jsx(jr,{parts:f,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:S})]})}if(u==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:b&&f?t.jsx(jr,{parts:f,renderAsPreformatted:!1}):S.slice(0,100)});const g=s.meta,k=(typeof(g==null?void 0:g.renderMode)=="string"?g.renderMode.trim():"")==="preformatted",p=S,x=!1,y=p,N=k,j=!N&&ec(y);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${m?"self-end":"self-start"}`,children:(p||b||m)&&t.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${p||b?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:m?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Zi(r)})]}),(p||b)&&t.jsx("div",{className:"chat-markdown",children:b&&f?t.jsx(jr,{parts:f,renderAsPreformatted:N}):N?t.jsx("pre",{className:"chat-preformatted",children:y}):j?t.jsx(Ra,{remarkPlugins:Qi,children:y}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:y})}),x]})})},(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),Ru=o.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:d={},lastMessageHash:m,emptyState:u,onLoadMore:f,isLoadingMore:b,hasMoreHistory:S,hiddenLiveCount:g=0,loadError:h,scrollToBottomRequestNonce:k,isVisible:p=!0},x){const y=o.useRef(null),N=o.useRef(null),j=o.useRef(null),I=o.useRef(0),M=o.useRef(""),w=o.useRef(""),v=o.useRef(!1),$=o.useRef(null),_=o.useRef(!1),T=o.useRef(null),F=o.useRef(!1),[B,L]=o.useState(new Set),[C,A]=o.useState({showTop:!1,showBottom:!1}),K=o.useRef(!1),P=o.useRef(!1),D=o.useRef(p),H=o.useRef(p),Q=o.useRef(null);H.current=p;const be=()=>{const Y=y.current;return Y?Y.scrollHeight-Y.scrollTop-Y.clientHeight<Ba:!0},de=o.useCallback(()=>{const Y=y.current,G=Y?ku(Y):{showTop:!1,showBottom:!1};A(ue=>ue.showTop===G.showTop&&ue.showBottom===G.showBottom?ue:G)},[]),te=o.useCallback((Y="auto")=>{var ue;const G=y.current;G&&(G.scrollTo({top:G.scrollHeight,behavior:Y}),(ue=G.ownerDocument.defaultView)==null||ue.requestAnimationFrame(()=>de()))},[de]),Z=o.useCallback((Y="auto")=>{var ue;const G=y.current;G&&(G.scrollTo({top:0,behavior:Y}),(ue=G.ownerDocument.defaultView)==null||ue.requestAnimationFrame(()=>de()))},[de]),ce=o.useCallback(()=>{var se;const Y=y.current,G=(se=window.getSelection)==null?void 0:se.call(window);if(!Y||!G||G.rangeCount===0||G.isCollapsed){F.current=!1;return}const ue=G.anchorNode,ke=G.focusNode;F.current=!!(ue&&ke&&Y.contains(ue)&&Y.contains(ke))},[]),fe=vu(s,m),J=o.useCallback(()=>{const Y=y.current;if(!Y||!l||!H.current)return;const G={top:Y.scrollTop,fromBottom:Math.max(0,Y.scrollHeight-Y.scrollTop-Y.clientHeight),messageFingerprint:fe};Q.current={contextKey:l,snapshot:G},Ks.set(l,G)},[l,fe]),me=o.useCallback((Y="auto")=>{$.current!=null&&cancelAnimationFrame($.current),$.current=requestAnimationFrame(()=>{$.current=null,te(Y)})},[te]),ve=o.useCallback(()=>{K.current=!1,_.current=!0,P.current=!0,T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{_.current=!1,T.current=null},Ao)},[]);o.useEffect(()=>{const Y=!v.current,G=w.current!==l;if(w.current=l,Y||G){v.current=!0;const ke=l?Ks.get(l):null,se=!!ke&&Gr(ke,fe);K.current=se?Ys(ke):!1,_.current=Su(ke,fe),F.current||(se?requestAnimationFrame(()=>{const Re=y.current;Re&&(kn(Re,ke),K.current=Ys(ke),de(),P.current=!0)}):me("auto")),I.current=s.length,M.current=fe;return}s.length>I.current;const ue=fe!==M.current;Nu({hasSelection:F.current,userScrolledUp:K.current,hasChatContentChanged:ue})&&me("auto"),I.current=s.length,M.current=fe},[fe,l,s.length,me,de]),o.useEffect(()=>{k&&(ve(),F.current||me("auto"))},[ve,me,k]),o.useEffect(()=>{const Y=D.current;Y&&!p&&J(),H.current=p,D.current=p;const G=l?Ks.get(l):null;if(wu(Y,p,G,fe)){if(!G)return;K.current=Ys(G),_.current=!1,F.current||requestAnimationFrame(()=>{const ue=y.current;ue&&(kn(ue,G),de())});return}},[p,l,fe,ve,J,me,de]),o.useEffect(()=>()=>{const Y=Q.current;Y&&Ks.set(Y.contextKey,Y.snapshot),$.current!=null&&cancelAnimationFrame($.current),T.current!=null&&window.clearTimeout(T.current)},[]),o.useEffect(()=>{const Y=N.current,G=y.current;if(!Y||!G)return;const ue=()=>{T.current!=null&&window.clearTimeout(T.current),T.current=window.setTimeout(()=>{_.current=!1,T.current=null},Ao)},ke=new ResizeObserver(()=>{de();const se=_.current;Cu({hasSelection:F.current,userScrolledUp:K.current,contextAutoScrollActive:se})&&(me("auto"),se&&ue())});return ke.observe(Y),G!==Y&&ke.observe(G),()=>{ke.disconnect(),T.current!=null&&(window.clearTimeout(T.current),T.current=null)}},[me,l,de]),o.useImperativeHandle(x,()=>({scrollToBottom:(Y="smooth")=>{te(Y)}}),[te]),o.useEffect(()=>{const Y=y.current;if(!Y)return;let G;const ue=()=>{J(),clearTimeout(G),G=setTimeout(()=>{K.current=!be(),de()},50)};return Y.addEventListener("scroll",ue,{passive:!0}),()=>{Y.removeEventListener("scroll",ue),clearTimeout(G)}},[J,de]),o.useEffect(()=>(document.addEventListener("selectionchange",ce),()=>document.removeEventListener("selectionchange",ce)),[ce]);const ae=o.useRef(0),pe=o.useRef(!1);o.useEffect(()=>{const Y=y.current;if(!Y||!pe.current||ae.current===0)return;const G=Y.scrollHeight-ae.current;G>0&&(Y.scrollTop=G),de(),J(),ae.current=0,pe.current=!1},[s.length,J,de]),o.useEffect(()=>{if(P.current||!l)return;const Y=Ks.get(l),G=y.current;if(!(!Y||!G)){if(!Gr(Y,fe)){te("auto"),P.current=!0;return}kn(G,Y),K.current=Ys(Y),de(),P.current=!0}},[l,fe,s.length,te,de]);const je=()=>{const Y=y.current;Y&&(ae.current=Y.scrollHeight),pe.current=!0,f==null||f()},xe=()=>{K.current=!0,Z("smooth"),J()},ge=()=>{ve(),te("smooth"),J()},oe=o.useMemo(()=>{const Y=s.map((se,Re)=>({type:"message",data:se,index:Re,ts:Tu(se,Re,d)}));if(!r||r.length===0)return Y;const G=[...r].sort((se,Re)=>se.timestamp-Re.timestamp).map((se,Re)=>({type:"action",data:se,index:Re,ts:se.timestamp})),ue=[];let ke=0;for(const se of Y){for(;ke<G.length&&se.ts>0&&G[ke].ts<se.ts;)ue.push(G[ke++]);ue.push(se)}for(;ke<G.length;)ue.push(G[ke++]);return ue},[s,r,d]),le=g>0||!!S,ie=g>0?`↑ Show ${Math.min(g,80)} earlier messages${g>80?` (${g} hidden)`:""}`:h?`↻ ${h}`:"↑ Load older messages";return t.jsxs("div",{className:"chat-scroll-frame",children:[t.jsx("div",{ref:y,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:N,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..."}),le&&!b&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{type:"button",onClick:je,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${h&&g===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:ie})}),oe.length===0&&!le&&(u||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),oe.map(Y=>{if(Y.type==="action"){const Oe=Y.data;return t.jsx(Au,{log:Oe},`action-${Y.index}`)}const G=Y.data,ue=Y.index,ke=qr(G,ue),se=G.receivedAt||d[ke],Re=`${l}-${ke}`,$e=B.has(Re);return t.jsx(Iu,{message:G,receivedAt:se,agentName:n,userName:a,isCliMode:i,isTextExpanded:$e,onToggleTextExpanded:()=>L(Oe=>{const He=new Set(Oe);return $e?He.delete(Re):He.add(Re),He})},`msg-${ke}`)}),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:j})]})}),(C.showTop||C.showBottom)&&t.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[C.showTop&&t.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:xe,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),C.showBottom&&t.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:ge,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Lu=o.memo(Ru,(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.lastMessageHash===s.lastMessageHash&&e.emptyState===s.emptyState&&e.onLoadMore===s.onLoadMore&&e.isLoadingMore===s.isLoadingMore&&e.hasMoreHistory===s.hasMoreHistory&&e.hiddenLiveCount===s.hiddenLiveCount&&e.loadError===s.loadError&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isVisible===s.isVisible),_u="modulepreload",Pu=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(d=>{if(d=Pu(d),d in Ro)return;Ro[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":_u,m||(f.as="script"),f.crossOrigin="",f.href=d,l&&f.setAttribute("nonce",l),document.head.appendChild(f),m)return new Promise((b,S)=>{f.addEventListener("load",b),f.addEventListener("error",()=>S(new Error(`Unable to preload CSS for ${d}`)))})}))}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 Lo=!1;const tc=o.forwardRef(({onInput:e,onViewportMetrics:s,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:i="measured"},c)=>{const l=o.useRef(null),[d,m]=o.useState(null),u=o.useRef([]),f=o.useRef(!1),b=o.useRef(!1),S=o.useRef(!1),g=o.useRef(!1),h=()=>{const k=l.current;if(k){f.current&&(k.clear(),f.current=!1);for(const p of u.current)k.write(p.data,p.onProcessed);u.current=[],b.current&&(k.fit(),b.current=!1),S.current&&(k.bumpResize(),S.current=!1),g.current&&(k.scrollToTop(),g.current=!1)}};return o.useImperativeHandle(c,()=>({write:(k,p)=>{l.current?l.current.write(k,p):u.current.push({data:k,onProcessed:p})},clear:()=>{l.current?l.current.clear():(u.current=[],f.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(u.current=[],f.current=!0)},resize:(k,p)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(k,p)},fit:()=>{l.current?l.current.fit():b.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():S.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():g.current=!0},getSelection:()=>{var k,p;return((p=(k=l.current)==null?void 0:k.getSelection)==null?void 0:p.call(k))||""},getVisibleText:()=>{var k,p;return((p=(k=l.current)==null?void 0:k.getVisibleText)==null?void 0:p.call(k))||""}}),[]),o.useEffect(()=>{d&&h()},[d]),o.useEffect(()=>{let k=!1;return Du(()=>import("./terminal-DbJP_JGY.js"),__vite__mapDeps([0,1,2])).then(p=>{Lo||(Lo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),k||m(()=>p.GhosttyTerminalView)}).catch(p=>{console.error("[CliTerminal] failed to load terminal renderer",p)}),()=>{k=!0}},[]),d?t.jsx(d,{ref:l,onInput:e,onViewportMetrics:s,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:i,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"}})});tc.displayName="CliTerminal";function kr({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 _o({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 Eu({cursorPos:e,viewportRef:s,imgRef:r}){var x;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(x=s.current)==null?void 0:x.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,d=c/l,m=a.width/a.height;let u,f,b,S;d>m?(u=a.width,f=a.width/d,b=0,S=(a.height-f)/2):(f=a.height,u=a.height*d,b=(a.width-u)/2,S=0);const g=a.left-i.left+b+u*e.nx,h=a.top-i.top+S+f*e.ny,k=Math.max(8,Math.min(i.width-8,g)),p=Math.max(8,Math.min(i.height-8,h));return t.jsxs("div",{style:{position:"absolute",left:k-8,top:p-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 $u({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:f,mobileFillZoom:b,onZoomOut:S,onZoomReset:g,onZoomIn:h,transportType:k,screenshotUsage:p,lastActionStatus:x}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:y=>y.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(y=>!y),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:y=>y.stopPropagation(),onChange:y=>l(y.target.value),onKeyDown:y=>{d(y)},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(y=>!y),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:m?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),u>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),k==="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"}),k==="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"}),p&&p.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:p.budgetExhausted?"#ef4444":"#c4b5fd",background:p.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:p.budgetExhausted?"TURN blocked":`TURN ${p.dailyUsedMinutes}/${p.dailyBudgetMinutes}m`}),x&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:x})]})]}),a&&t.jsxs("div",{onTouchStart:y=>y.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: ",u<=(f?b:1)+.01?f?"FILL":"FIT":`${Math.round(u*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:y=>{y.stopPropagation(),S()},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:y=>{y.stopPropagation(),g()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:f?"FILL":"FIT"}),t.jsx("button",{onClick:y=>{y.stopPropagation(),h()},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 Bu({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 Ku(){if(typeof window>"u")return!1;try{return window.__ADHDEV_DEBUG_RENDERS__===!0||window.localStorage.getItem("adhdev_debug_renders")==="1"}catch{return window.__ADHDEV_DEBUG_RENDERS__===!0}}function Po(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function lr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!Ku())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,Po(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,Po(s[c])]))}),r.current=s})}function Wu({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:d,setPanX:m,setPanY:u,setZoom:f,lastWheelTimeRef:b,onAction:S,setLastActionStatus:g,spawnRippleFromNormalized:h,clampPan:k,isMobile:p,mobileFillZoom:x}){const[y,N]=o.useState(null),j=o.useRef(null),I=o.useRef(null),M=o.useRef(null),w=o.useRef(!1),v=o.useRef(null),$=o.useRef(0),_=o.useRef(null),T=o.useRef(1),F=o.useRef({x:0,y:0}),B=o.useRef(!1),L=o.useRef(n),C=o.useRef(S),A=30,K=550,P=18,D=60,H=400,Q=12,be=()=>{if(j.current)return;const Z={nx:.5,ny:.5};j.current=Z,N(Z)};return o.useEffect(()=>{L.current=n,n==="mouse"&&be()},[n]),o.useEffect(()=>{C.current=S},[S]),o.useEffect(()=>{const Z=e.current;if(!Z)return;const ce=pe=>{if(!r.current)return null;const je=r.current.getBoundingClientRect();return!je.width||!je.height?null:{nx:Math.max(0,Math.min(1,(pe.clientX-je.left)/je.width)),ny:Math.max(0,Math.min(1,(pe.clientY-je.top)/je.height))}},fe=(pe,je)=>{if(!r.current)return{dnx:0,dny:0};const xe=r.current,ge=xe.getBoundingClientRect(),oe=xe.naturalWidth||ge.width,le=xe.naturalHeight||ge.height,ie=oe/le,Y=ge.width/ge.height;let G,ue;return ie>Y?(G=ge.width,ue=ge.width/ie):(ue=ge.height,G=ge.height*ie),{dnx:pe/G,dny:je/ue}},J=(pe,je,xe)=>{if(xe<=1.05)return;const ge=-(pe-.5)*100,oe=-(je-.5)*100,le=k(ge,oe,xe);(Math.abs(le.x-l.current)>.1||Math.abs(le.y-d.current)>.1)&&(m(le.x),u(le.y),l.current=le.x,d.current=le.y)},me=pe=>{const je=s.current;if(je&&pe.target instanceof Node&&je.contains(pe.target))pe.preventDefault();else return;if(pe.touches.length===1){const xe=pe.touches[0];I.current={x:xe.clientX,y:xe.clientY,time:Date.now()},M.current={x:xe.clientX,y:xe.clientY},B.current||(w.current=!1),v.current=setTimeout(()=>{if(!w.current&&!B.current)if(w.current=!0,L.current==="mouse"){const ge=j.current||{nx:.5,ny:.5};g("Right Click"),h(ge.nx,ge.ny,"right"),C.current("input_click",{...ge,button:"right"}).catch(()=>{})}else{const ge=ce(xe);ge&&(g("Right Click"),h(ge.nx,ge.ny,"right"),C.current("input_click",{...ge,button:"right"}).catch(()=>{}))}},500);return}if(pe.touches.length===2){v.current&&clearTimeout(v.current),w.current=!0,B.current=!0;const xe=pe.touches[1].clientX-pe.touches[0].clientX,ge=pe.touches[1].clientY-pe.touches[0].clientY;_.current=Math.sqrt(xe*xe+ge*ge),T.current=c.current,F.current={x:(pe.touches[0].clientX+pe.touches[1].clientX)/2,y:(pe.touches[0].clientY+pe.touches[1].clientY)/2}}},ve=pe=>{const je=s.current;if(je&&pe.target instanceof Node&&je.contains(pe.target)&&pe.preventDefault(),pe.touches.length===1&&M.current){const xe=pe.touches[0],ge=xe.clientX-M.current.x,oe=xe.clientY-M.current.y;if(!w.current&&I.current){const le=xe.clientX-I.current.x,ie=xe.clientY-I.current.y;Math.sqrt(le*le+ie*ie)>8&&(w.current=!0,v.current&&clearTimeout(v.current))}if(w.current)if(L.current==="mouse"){const le=fe(ge,oe),ie=j.current||{nx:.5,ny:.5},Y=Math.max(0,Math.min(1,ie.nx+le.dnx)),G=Math.max(0,Math.min(1,ie.ny+le.dny));j.current={nx:Y,ny:G},N({nx:Y,ny:G}),g(`Cursor: ${Math.round(Y*100)}%, ${Math.round(G*100)}%`),J(Y,G,c.current);const ue=Date.now();ue-b.current>=30&&(b.current=ue,C.current("input_mouseMoved",{nx:Y,ny:G}).catch(()=>{}))}else if(c.current>1){const le=s.current;if(le){const ie=le.clientWidth,Y=le.clientHeight,G=l.current+ge/ie*100,ue=d.current+oe/Y*100,ke=k(G,ue,c.current);m(ke.x),u(ke.y),l.current=ke.x,d.current=ke.y}}else{const le=ce(xe);if(le){const ie=Date.now();ie-b.current>=40&&(b.current=ie,g("Scroll"),C.current("input_wheel",{nx:le.nx,ny:le.ny,deltaX:Math.round(-ge*2.5),deltaY:Math.round(-oe*2.5)}).catch(()=>{}))}}M.current={x:xe.clientX,y:xe.clientY};return}if(pe.touches.length===2&&_.current!==null){const xe=pe.touches[1].clientX-pe.touches[0].clientX,ge=pe.touches[1].clientY-pe.touches[0].clientY,le=Math.sqrt(xe*xe+ge*ge)/_.current,ie=(pe.touches[0].clientX+pe.touches[1].clientX)/2,Y=(pe.touches[0].clientY+pe.touches[1].clientY)/2,G=ie-F.current.x,ue=Y-F.current.y,ke=Math.abs(le-1)>.03;if(L.current==="mouse"){if(ke){const se=Math.max(i,Math.min(5,T.current*le));f(se),c.current=se}else if(Math.abs(G)>2||Math.abs(ue)>2){const se=j.current||{nx:.5,ny:.5},Re=Date.now();Re-b.current>=30&&(b.current=Re,g("Scroll"),C.current("input_wheel",{nx:se.nx,ny:se.ny,deltaX:Math.round(-G*3),deltaY:Math.round(-ue*3)}).catch(()=>{}))}}else{const se=Math.max(i,Math.min(5,T.current*le));f(se),c.current=se;const Re=s.current;if(Re&&se>1){const $e=Re.clientWidth,Oe=Re.clientHeight,He=l.current+G/$e*100,W=d.current+ue/Oe*100,Ce=k(He,W,se);m(Ce.x),u(Ce.y),l.current=Ce.x,d.current=Ce.y}}F.current={x:ie,y:Y}}},ae=pe=>{var je;if(v.current&&clearTimeout(v.current),_.current=null,pe.touches.length===1&&B.current){const xe=pe.touches[0];I.current={x:xe.clientX,y:xe.clientY,time:Date.now()},M.current={x:xe.clientX,y:xe.clientY},w.current=!0;return}if(pe.touches.length===0){if(B.current){B.current=!1,w.current=!1;return}if(pe.changedTouches.length===1){const xe=pe.changedTouches[0],ge=Date.now(),oe=ge-(((je=I.current)==null?void 0:je.time)||0),le=I.current?xe.clientX-I.current.x:0,ie=I.current?xe.clientY-I.current.y:0,Y=Math.sqrt(le*le+ie*ie);if(L.current==="mouse"){if(oe<A||oe>K||Y>P){w.current=!1;return}const G=j.current||ce(xe);G&&(g(`Click: ${Math.round(G.nx*100)}%, ${Math.round(G.ny*100)}%`),h(G.nx,G.ny,"left"),C.current("input_click",{...G}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(oe<D||oe>H||Y>Q){w.current=!1;return}const G=ce(xe);if(!G)return;ge-$.current<300?(g("Double tap"),h(G.nx,G.ny,"double"),C.current("input_click",{...G,clickCount:2}).catch(()=>{}),$.current=0):(g(`Tap: ${Math.round(G.nx*100)}%, ${Math.round(G.ny*100)}%`),h(G.nx,G.ny,"left"),C.current("input_click",{...G}).catch(()=>{}),$.current=ge)}}w.current=!1}};return Z.addEventListener("touchstart",me,{passive:!1}),Z.addEventListener("touchmove",ve,{passive:!1}),Z.addEventListener("touchend",ae,{passive:!1}),()=>{Z.removeEventListener("touchstart",me),Z.removeEventListener("touchmove",ve),Z.removeEventListener("touchend",ae),v.current&&clearTimeout(v.current)}},[e,s,r,i,c,l,d,m,u,f,b,g,h,k]),{cursorPos:y,cursorPosRef:j,handleToggleInputMode:()=>{a(Z=>{const ce=Z==="touch"?"mouse":"touch";return ce==="mouse"&&be(),ce})},handleZoomReset:()=>{const Z=p?x:1;f(Z),c.current=Z,m(0),u(0),l.current=0,d.current=0}}}function sc({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),d=o.useRef(null),[m,u]=o.useState(null),[f,b]=o.useState(""),[,S]=o.useState(!1),[g,h]=o.useState([]),k=o.useRef(0),[p,x]=o.useState(!1),[y,N]=o.useState(!1),j=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[I,M]=o.useState(j?"mouse":"touch"),[w,v]=o.useState(1),$=o.useRef(!1),[_,T]=o.useState(1),[F,B]=o.useState(0),[L,C]=o.useState(0);lr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:I,zoom:_,panX:F,panY:L,isMenuOpen:p,isImeOpen:y});const A=o.useRef(0),K=o.useRef(_),P=o.useRef(F),D=o.useRef(L);o.useEffect(()=>{K.current=_},[_]),o.useEffect(()=>{P.current=F},[F]),o.useEffect(()=>{D.current=L},[L]),o.useEffect(()=>{var oe;(oe=c.current)==null||oe.focus()},[]);const H=r==="connected",Q=n,be=H?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",de=H?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!j||$.current||!Q)return;const oe=d.current,le=l.current;if(!oe||!le)return;const ie=()=>{const Y=le.clientWidth,G=le.clientHeight,ue=oe.naturalWidth,ke=oe.naturalHeight;if(!ue||!ke||!Y||!G)return;const se=Math.min(Y/ue,G/ke),$e=Math.max(Y/ue,G/ke)/se;$e>1.01&&(v($e),T($e),K.current=$e),$.current=!0};oe.complete&&oe.naturalWidth?ie():oe.addEventListener("load",ie,{once:!0})},[Q,j]);const te=.5;o.useEffect(()=>{_<=te&&(B(0),C(0))},[_,te]);const Z=(oe,le,ie)=>{if(ie<=te)return{x:0,y:0};const Y=(ie-1)/(2*ie)*100,G=(ie-1)/(2*ie)*100;return{x:Math.max(-Y,Math.min(Y,oe)),y:Math.max(-G,Math.min(G,le))}},ce=(oe,le)=>{if(!d.current)return null;const ie=d.current.getBoundingClientRect();return!ie.width||!ie.height?null:{nx:Math.max(0,Math.min(1,(oe-ie.left)/ie.width)),ny:Math.max(0,Math.min(1,(le-ie.top)/ie.height))}},fe=(oe,le,ie)=>{const Y=l.current;if(!Y)return;const G=Y.getBoundingClientRect(),ue=++k.current;h(ke=>[...ke,{id:ue,x:oe-G.left,y:le-G.top,type:ie}]),setTimeout(()=>h(ke=>ke.filter(se=>se.id!==ue)),600)},J=(oe,le,ie)=>{const Y=d.current,G=l.current;if(!Y||!G)return;const ue=Y.getBoundingClientRect(),ke=G.getBoundingClientRect(),se=Y.naturalWidth||ue.width,Re=Y.naturalHeight||ue.height,$e=se/Re,Oe=ue.width/ue.height;let He,W,Ce,Te;$e>Oe?(He=ue.width,W=ue.width/$e,Ce=0,Te=(ue.height-W)/2):(W=ue.height,He=ue.height*$e,Ce=(ue.width-He)/2,Te=0);const Le=ue.left-ke.left+Ce+He*oe,Be=ue.top-ke.top+Te+W*le,Fe=++k.current;h(Ye=>[...Ye,{id:Fe,x:Le,y:Be,type:ie}]),setTimeout(()=>h(Ye=>Ye.filter(et=>et.id!==Fe)),600)},me=async oe=>{var ie;const le=ce(oe.clientX,oe.clientY);if(le){u(`Click: ${Math.round(le.nx*100)}%, ${Math.round(le.ny*100)}%`),fe(oe.clientX,oe.clientY,"left"),(ie=c.current)==null||ie.focus();try{const Y=await e("input_click",{nx:le.nx,ny:le.ny});Y!=null&&Y.success||s(`❌ Click failed: ${Y==null?void 0:Y.error}`)}catch(Y){s(`❌ Click error: ${Y.message||Y}`)}}},ve=async(oe,le,ie,Y=0)=>{try{await e("input_key",{type:ie?"char":"keyDown",key:oe,code:le,text:ie?oe:void 0,unmodifiedText:ie?oe:void 0,modifiers:Y})}catch(G){s(`❌ Key error: ${G.message||G}`)}},ae=async oe=>{if(oe.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(oe.key)&&oe.preventDefault();let ie=0;oe.altKey&&(ie|=1),oe.ctrlKey&&(ie|=2),oe.metaKey&&(ie|=4),oe.shiftKey&&(ie|=8),u(`Key: ${oe.key}`),await ve(oe.key,oe.code,oe.key.length===1,ie)},pe=async oe=>{if(oe.key==="Enter"){if(oe.nativeEvent.isComposing)return;if(f){const le=f;b(""),u(`IME Sent: ${le}`);try{const ie=await e("input_type",{text:le});ie!=null&&ie.success||s(`❌ IME error: ${ie==null?void 0:ie.error}`)}catch(ie){s(`❌ IME error: ${ie.message}`)}}else u("Key: Enter"),await ve("Enter","Enter",!1)}};o.useEffect(()=>{const oe=c.current;if(!oe)return;const le=ie=>{var Y;if((Y=d.current)!=null&&Y.contains(ie.target)){ie.preventDefault();const G=Date.now();if(G-A.current<40)return;A.current=G;const ue=ce(ie.clientX,ie.clientY);if(!ue)return;u(`Scroll: ${Math.round(ie.deltaY)}`),e("input_wheel",{nx:ue.nx,ny:ue.ny,deltaX:Math.round(ie.deltaX),deltaY:Math.round(ie.deltaY)}).catch(()=>{})}};return oe.addEventListener("wheel",le,{passive:!1}),()=>oe.removeEventListener("wheel",le)},[e]);const{cursorPos:je,handleToggleInputMode:xe,handleZoomReset:ge}=Wu({containerRef:c,viewportRef:l,imgRef:d,inputMode:I,setInputMode:M,minZoom:te,zoomRef:K,panXRef:P,panYRef:D,setPanX:B,setPanY:C,setZoom:T,lastWheelTimeRef:A,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:J,clampPan:Z,isMobile:j,mobileFillZoom:w});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ae,onContextMenu:oe=>oe.preventDefault(),onFocus:()=>S(!0),onBlur:()=>S(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[Q?t.jsx("img",{ref:d,src:Q,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${_}) translate(${F}%, ${L}%)`,transformOrigin:"center center",cursor:I==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:me,onContextMenu:oe=>oe.preventDefault(),onDragStart:oe=>oe.preventDefault()}):t.jsx(Bu,{waitingLabel:be,waitingHint:de,transportType:i}),I==="mouse"&&Q&&t.jsx(Eu,{cursorPos:je,viewportRef:l,imgRef:d}),g.map(oe=>{const ie={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[oe.type];return t.jsxs("div",{style:{position:"absolute",left:oe.x,top:oe.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ie}, 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(${ie}, 0.9)`,boxShadow:`0 0 12px rgba(${ie}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},oe.id)})]}),t.jsx($u,{inputMode:I,onToggleInputMode:xe,isImeOpen:y,setIsImeOpen:N,isMenuOpen:p,setIsMenuOpen:x,imeText:f,setImeText:b,handleImeSubmit:pe,isConnActive:H,zoom:_,isMobile:j,mobileFillZoom:w,onZoomOut:()=>T(oe=>Math.max(.5,oe-.25)),onZoomReset:ge,onZoomIn:()=>T(oe=>Math.min(5,oe+.25)),transportType:i,screenshotUsage:a,lastActionStatus:m}),t.jsx("style",{children:`
|
|
5
|
-
@keyframes slideUp {
|
|
6
|
-
from { opacity: 0; transform: translateY(6px); }
|
|
7
|
-
to { opacity: 1; transform: translateY(0); }
|
|
8
|
-
}
|
|
9
|
-
@keyframes slideUpSidebar {
|
|
10
|
-
from { opacity: 0; transform: translateY(6px); }
|
|
11
|
-
to { opacity: 1; transform: translateY(0); }
|
|
12
|
-
}
|
|
13
|
-
@keyframes click-ripple-ring {
|
|
14
|
-
0% { transform: scale(0.3); opacity: 1; }
|
|
15
|
-
100% { transform: scale(2.2); opacity: 0; }
|
|
16
|
-
}
|
|
17
|
-
@keyframes click-ripple-dot {
|
|
18
|
-
0% { transform: scale(1); opacity: 0.9; }
|
|
19
|
-
50% { transform: scale(1.8); opacity: 0.6; }
|
|
20
|
-
100% { transform: scale(0.5); opacity: 0; }
|
|
21
|
-
}
|
|
22
|
-
@keyframes remote-float {
|
|
23
|
-
0% { transform: translateY(0px); }
|
|
24
|
-
50% { transform: translateY(-7px); }
|
|
25
|
-
100% { transform: translateY(0px); }
|
|
26
|
-
}
|
|
27
|
-
`})]})}function dn(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 d=Math.floor(l/60);if(d<24)return`${d}h${r}`;const m=Math.floor(d/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const rc=e=>dn(e);function Ou(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 Es(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 Fu(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...Ou(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 Yr(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 un(e,s,r){const n=Yr(e,s),a=Es(e),i=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,d=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=n.inboxBucket==="working"||l,b=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:b,requiresAction:m,isWorking:u,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":b?"task_complete":"idle"}}function Hu(e,s,r){return un(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function nc({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Es(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(ar,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,d)=>{const m=c(l).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(m),f=/^(reject|deny|delete|remove|abort)/.test(m),b=r===l,S=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:S,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${S&&!b?"opacity-40":"opacity-100"} ${S?"cursor-not-allowed":"cursor-pointer"}`,style:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:f?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:b?"⏳ ...":c(l)},d)})})]})]})}const Ka="adhdev_controls_bar_visible",pa="adhdev:controlsbarvisibilitychange";function Nn(e){if(!e)return!1;try{return e.getItem(Ka)==="1"}catch{return!1}}function Uu(e,s){if(s)try{s.setItem(Ka,e?"1":"0")}catch{}}function zu(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(pa,{detail:{visible:e}}))}function Wa(){const[e,s]=o.useState(()=>typeof window>"u"?!1:Nn(window.localStorage)),r=o.useRef(e),n=o.useCallback((c,l=!0)=>{r.current=c,s(c),typeof window<"u"&&Uu(c,window.localStorage),l&&zu(c)},[]);o.useEffect(()=>{const c=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:Nn(window.localStorage);r.current=u,s(u)},l=d=>{if(d.key!==Ka)return;const m=Nn(window.localStorage);r.current=m,s(m)};return window.addEventListener(pa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(pa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{n(c)},[n]),i=o.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:i}}var Vu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Gu(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function jt(e,s){if(Gu(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 ac(e){return jt(e)==="generating"}function ot(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function qu(e){if(e<60)return`${Math.round(e)}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),n=s%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),i=r%24;return`${a}d ${i}h`}function Cn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function mn(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 Yu(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const s=e.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function Xu(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Ju(e){return Yu(e.trim().replace(/\.local$/i,""))}function Qu(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function oc(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&&!Xu(c));if(r&&r!=="Unknown")return Ju(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function Ct(e,s={}){return Qu(e)||oc(e,s)}function ic(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 cc(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 ms(e,s){return ic(e).join(" · ")}function or(e){return e.transport==="pty"}function Ss(e){return e.transport==="acp"}function Zu(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:ot(e)}function Do(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=ot(r||"").trim().toLowerCase();return n===a||n===i||n===c}function em(e){return jt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function tm(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=jt(n.status);if(!i){s.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),d=r.indexOf(c||"idle");d>=0&&(l<0||d<l)&&s.set(a,{...n,status:c})}return Array.from(s.values())}function sm(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 rm(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&&sm(s.receivedAt)||0}function nm(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ha(e){return Math.max(nm(e),rm(e.activeChat))}function am(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 Oa(e,s){return am(ha(e),ha(s),Ct(e,{fallbackId:e.id}),Ct(s,{fallbackId:s.id}),e.id,s.id)}const lc="adhdev_notification_prefs",Eo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function om(){try{const e=localStorage.getItem(lc);if(e){const s=JSON.parse(e);return{...Eo,...s}}}catch{}return{...Eo}}function im(e){try{localStorage.setItem(lc,JSON.stringify(e))}catch{}}let Wt=om(),Er=[];function cm(){Er.forEach(e=>e())}function lm(e){Wt={...Wt,...e},im(Wt),cm()}function dm(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Er.push(r),()=>{Er=Er.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{lm(r)},[]);return[{...Wt},s]}function Js(e){if(!Wt.globalEnabled)return!1;switch(e){case"disconnect":return Wt.disconnectAlert;case"completion":return Wt.completionAlert;case"approval":return Wt.approvalAlert;case"browser":return Wt.browserNotifications;default:return!0}}const um={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function dc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function uc(){return"Notification"in window&&Notification.permission==="granted"}let Jt=null;function mm(e){return e!==!1}async function fm(){if(Jt!==null)return Jt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Jt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Jt=!!await e.pushManager.getSubscription(),Jt):(Jt=!1,!1)}catch{return Jt=!1,!1}}function xa(e,s,r){if(uc())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 pm(e,s={}){const r={...um,...s},n=o.useRef(new Map),a=o.useRef(0),[i,c]=o.useState(null);o.useEffect(()=>{let d=!1;return fm().then(m=>{d||c(m)}),()=>{d=!0}},[]);const l=o.useCallback((d,m,u)=>{const f=Date.now();f-a.current<r.throttleMs||(a.current=f,xa(d,m,u))},[r.throttleMs]);o.useEffect(()=>{var d;if(!(!r.enabled||!uc())&&Js("browser")&&!mm(i)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,jt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),f=jt(m.status,{activeModal:m.activeModal}),b=m.name||m.id;if(r.onApproval&&Js("approval")&&f==="waiting_approval"&&u!=="waiting_approval"){const S=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";l(`🔔 ${b} — Approval needed`,S.slice(0,120),`approval-${m.id}`)}r.onComplete&&Js("completion")&&ac(u)&&f==="idle"&&l(`✅ ${b} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&f==="error"&&u!=="error"&&l(`⚠️ ${b} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,f)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,i,l])}const hm=/^(run|approve|accept|yes|allow|always)/,xm=/^(run|approve|accept|yes|allow|always|proceed|save)/,bm=/^(reject|deny|delete|remove|abort|cancel|no)/;function Fa(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function gm(e){const s=Fa(e).toLowerCase();return hm.test(s)?"primary":bm.test(s)?"danger":"default"}function ym(e){return xm.test(Fa(e).toLowerCase())?"approve":"reject"}function vm(e){return e.map((s,r)=>({label:Fa(s),variant:gm(s),action:ym(s),button:s,buttonIndex:r}))}function wm(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function jm(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 km{constructor(){Je(this,"dedupMap",new Map);Je(this,"DEDUP_WINDOW_MS",5e3);Je(this,"DEDUP_MAX_SIZE",50);Je(this,"DEDUP_CLEANUP_AGE_MS",1e4);Je(this,"toastCallbacks",[]);Je(this,"resolveActionFn",null);Je(this,"viewRequestRespondFn",null);Je(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:s,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(s){if(s.daemonId){const a=this.ides.find(i=>i.id===s.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var g;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 d=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=ot(m);const f=this.resolveOwningDaemon(s);if(f){const h=Ct(f,{fallbackId:f.id});h&&(u=!m||m==="adhdev-daemon"?h:`${h}/${u}`)}let b="",S="info";if(s.event==="agent:generating_completed"){const h=s.duration?` (${s.duration}s)`:"";b=`✅ ${u} agent task completed${h}`,S="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(b=`⚡ ${u} approval needed`,S="warning",(g=s.modalButtons)!=null&&g.length&&this.resolveActionFn){const h=this.resolveActionRouteTarget(s);if(!h)return;const k=this.resolveActionFn,p=vm(s.modalButtons).map(N=>({label:N.label,variant:N.variant,onClick:()=>{k(h,"resolve_action",{action:N.action,button:N.button,buttonIndex:N.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),x=wm(u,s.modalMessage,b),y=Date.now();this.emitToast({id:y,message:x,type:S,timestamp:y,targetKey:n||h,actions:p,duration:15e3}),b=""}}else if(s.event==="monitor:long_generating"){const h=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";b=`⚠️ ${u} agent is taking a long time${h}`,S="warning",Js("browser")&&!document.hasFocus()&&xa(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${h.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const h=s.requesterName||"A team member",k=s.requestId,p=s.orgId;if(b=`👁️ ${h} wants to view your session`,S="warning",k&&p&&this.viewRequestRespondFn){const x=Date.now(),y=jm(p,k,this.viewRequestRespondFn,(N,j)=>console.error(`[EventManager] ${N} view request failed:`,j));this.emitToast({id:x,message:b,type:S,timestamp:x,actions:y,duration:3e4}),b=""}Js("browser")&&!document.hasFocus()&&xa("👁️ View Request",`${h} wants to view your session`,`view-request-${k}`)}else s.event==="team:view_request_approved"?(b="✅ View request approved",S="success"):s.event==="team:view_request_rejected"&&(b=`❌ ${s.targetName||"Team member"} declined your view request`,S="warning");if(b){const h=Date.now();this.emitToast({id:h,message:b,type:S,timestamp:h,targetKey:n||s.daemonId,duration:5e3})}}}const nt=new km,$o=new Map;function Xr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ns(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function fn(e){return Xr(e)?Xr(e.result)?e.result:e:null}function Sm(e){const s=fn(e);return!s||!Xr(s.controlResult)||!Array.isArray(s.controlResult.options)?null:s.controlResult}function Sr(e){const s=fn(e);return!s||!Xr(s.controlResult)||typeof s.controlResult.ok!="boolean"?null:s.controlResult}function Ws(e){const s=fn(e);if(!(!s||typeof s.error!="string"||!s.error.trim()))return s.error}function Nr(e){const s=fn(e);return!!s&&s.success===!1}function Nm(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";nt.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";nt.showToast(n.notification.body,a)}}}function Cm(e,s){return e&&Ns(e.currentValue)?e.currentValue:s}function Tm(e,s){return Ns(s)?Ns(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Mm(e,s){var i,c;if((s.now??Date.now())<s.localOverrideUntil){const l=s.localValues[e];if(Ns(l))return l}const n=(i=s.controlValues)==null?void 0:i[e];if(Ns(n))return n;const a=(c=s.defaultValues)==null?void 0:c[e];return Ns(a)?a:void 0}function $r(e,s){return e.options||s[e.id]||[]}const Am={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 Im(e,s,r){var n;return((n=Am[s])==null?void 0:n.has(r.id))===!0}function Ha(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Im(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Tn(e,s){return{value:s}}function Rm(e,s,r){var a;return r?((a=$r(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const Lm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function _m({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=xt(),d=`${e}:${s||n}`,m=Lm[n]||"#94a3b8",[u,f]=o.useState({}),b=o.useRef({}),S=o.useRef(c);b.current=u,S.current=c;const g=o.useRef(0),h={};for(const A of i||[])A.defaultValue!==void 0&&(h[A.id]=A.defaultValue);const k={...h,...c||{},...Date.now()<g.current?u:{}};o.useEffect(()=>{c&&Date.now()>g.current&&f({})},[c]);const[p,x]=o.useState($o.get(d)||{}),[y,N]=o.useState(null),[j,I]=o.useState(null),M=o.useCallback(async(A,K={})=>{const P={...K,...s&&{targetSessionId:s}};return await l(e,A,P)},[e,s,l]),w=o.useCallback(async(A,K={})=>{const P=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await M("invoke_provider_script",{...P,scriptName:A,...K})},[M,n,r,s]),v=o.useCallback((A,K,P)=>{const D=Cm(P,K);f(H=>({...H,[A.id]:D})),Nm(P==null?void 0:P.effects)},[]),$=o.useCallback((A,K)=>{f(P=>{const D={...P};return K===void 0?delete D[A.id]:D[A.id]=K,D}),g.current=0},[]);if(!i||i.length===0)return null;const _=Ha(i,{hostIdeType:r,providerType:n});if(_.length===0)return null;const T=async A=>{if(y===A.id){N(null);return}if($r(A,p).length>0){N(A.id);return}if(A.dynamic&&A.listScript){I(A.id);try{const P=await w(A.listScript,{}),D=Sm(P);if(!D){const be=Ws(P);be&&nt.showToast(be,"warning");return}const H=D.options;x(be=>{const de={...be,[A.id]:H};return $o.set(d,de),de});const Q=Mm(A.id,{localOverrideUntil:g.current,localValues:b.current,controlValues:S.current,defaultValues:h});if(Tm(Q,D.currentValue)){const be=D.currentValue;f(de=>({...de,[A.id]:be}))}N(A.id)}catch(P){const D=P instanceof Error?P.message:`Could not load ${A.label}`;nt.showToast(D,"warning")}finally{I(null)}}},F=async(A,K)=>{N(null);const P=(c==null?void 0:c[A.id])??h[A.id];f(D=>({...D,[A.id]:K})),g.current=Date.now()+5e3;try{if(!A.setScript)return;const D=await w(A.setScript,Tn(A,K)),H=Sr(D);if(H&&!H.ok||Nr(D))throw new Error((H==null?void 0:H.error)||Ws(D)||`Could not update ${A.label}`);v(A,K,H)}catch(D){$(A,P);const H=D instanceof Error?D.message:`Could not update ${A.label}`;nt.showToast(H,"warning")}},B=async A=>{const K=$r(A,p).map(de=>de.value);if(K.length===0)return;const P=String(k[A.id]||""),H=(K.indexOf(P)+1)%K.length,Q=K[H];if(typeof Q!="string")return;const be=(c==null?void 0:c[A.id])??h[A.id];f(de=>({...de,[A.id]:Q})),g.current=Date.now()+5e3;try{if(!A.setScript)return;const de=await w(A.setScript,Tn(A,Q)),te=Sr(de);if(te&&!te.ok||Nr(de))throw new Error((te==null?void 0:te.error)||Ws(de)||`Could not update ${A.label}`);v(A,Q,te)}catch(de){$(A,be);const te=de instanceof Error?de.message:`Could not update ${A.label}`;nt.showToast(te,"warning")}},L=async A=>{const P=!k[A.id],D=(c==null?void 0:c[A.id])??h[A.id];f(H=>({...H,[A.id]:P})),g.current=Date.now()+5e3;try{if(!A.setScript)return;const H=await w(A.setScript,Tn(A,P)),Q=Sr(H);if(Q&&!Q.ok||Nr(H))throw new Error((Q==null?void 0:Q.error)||Ws(H)||`Could not update ${A.label}`);v(A,P,Q)}catch(H){$(A,D);const Q=H instanceof Error?H.message:`Could not update ${A.label}`;nt.showToast(Q,"warning")}},C=async A=>{if(!A.invokeScript)return;if(A.confirmMessage){const P=[A.confirmTitle,A.confirmMessage,A.confirmLabel].filter(H=>typeof H=="string"&&H.trim().length>0);if(!window.confirm(P.join(`
|
|
28
|
-
|
|
29
|
-
`)))return}const K=(c==null?void 0:c[A.id])??h[A.id];try{const P=await w(A.invokeScript),D=Sr(P);if(D&&!D.ok||Nr(P))throw new Error((D==null?void 0:D.error)||Ws(P)||`Could not run ${A.label}`);D&&v(A,K??!0,D)}catch(P){$(A,K);const D=P instanceof Error?P.message:`Could not run ${A.label}`;nt.showToast(D,"warning")}};return t.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),_.map(A=>{const K=String(k[A.id]||""),P=Rm(A,p,K),D=y===A.id,H=j===A.id,Q=$r(A,p),be="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(A.type){case"select":return t.jsxs("div",{className:"relative max-w-full",children:[t.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:D?`${m}55`:"var(--border-default)",background:D?`${m}10`:"var(--surface-tertiary)",color:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(A),title:A.label,children:[A.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:H?"Loading…":P||A.label}),t.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),D&&Q.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>N(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:A.label}),Q.map(de=>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:de.value===K?`${m}14`:"transparent",color:de.value===K?"var(--text-primary)":"var(--text-secondary)",borderLeft:de.value===K?`2px solid ${m}`:"2px solid transparent"},title:de.description||de.label,onMouseEnter:te=>{te.currentTarget.style.background=`${m}10`},onMouseLeave:te=>{te.currentTarget.style.background=de.value===K?`${m}14`:"transparent"},onClick:()=>void F(A,de.value),children:[t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:de.label}),de.value===K&&t.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},de.value))]})]})]},A.id);case"cycle":return t.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void B(A),title:`Click to cycle: ${Q.map(de=>de.label).join(" → ")}`,children:[A.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P||A.label}),t.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},A.id);case"toggle":return t.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:K?`${m}44`:"var(--border-default)",background:K?`${m}14`:"var(--surface-tertiary)",color:K?m:"var(--text-muted)"},onClick:()=>void L(A),"aria-pressed":!!K,children:[A.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),A.label]},A.id);case"action":return t.jsxs("button",{type:"button",className:`${be} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void C(A),children:[A.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:A.resultDisplay==="inline"&&K?`${A.label}: ${K}`:A.label})]},A.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:K?"var(--text-primary)":"var(--text-muted)"},children:[A.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:A.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:K?`${A.label}: ${K}`:A.label})]},A.id);default:return null}})]})})}function Pm({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:d}){const{isVisible:m}=Wa(),u=Ha(l,{hostIdeType:a,providerType:i});return!e||s||u.length===0||!m?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(_m,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:u,controlValues:d})})}function Dm({hasDraft:e,isBusy:s=!1}){return!e||s}const mc=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u}){const f=o.useRef(null),[b,S]=o.useState(""),g=o.useRef(!1),{isVisible:h,toggleVisibility:k}=Wa();o.useEffect(()=>{S("")},[s]),o.useEffect(()=>{var x;l&&((x=f.current)==null||x.focus({preventScroll:!0}))},[s,l]);const p=async()=>{const x=b.trim();if(!(!x||a)&&!g.current){g.current=!0;try{await c(x)!==!1&&S("")}finally{g.current=!1}}};return t.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":""].filter(Boolean).join(" "),style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[t.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[d&&t.jsx("button",{type:"button",onClick:()=>{k(),u==null||u()},"aria-label":h?"Hide controls":"Show controls","aria-pressed":h,title:h?"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:b,onChange:x=>S(x.target.value),onPaste:x=>{const y=x.clipboardData.getData("text");y&&S(N=>N+y),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.preventDefault(),p()}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{p()},disabled:Dm({hasDraft:!!b.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${b.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:b.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:b.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),st=e=>e.transport==="pty",$s=(e,s)=>st(e)?e.mode||"terminal":"chat",fc=(e,s)=>st(e)&&$s(e)==="terminal",Qe=e=>e.transport==="acp",Em=180;function qt(e){return e.streamSource!=="agent-stream"}function bs(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function pc(e){return e.machineName||""}function dr(e){return bs(e)}function Bt(e){return e.agentType||""}function Jr(e){return e.hostIdeType||""}function Ua(e){return e.displayPrimary||e.agentName||"Agent"}function hc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function $m(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function xc(e){const s=$m(e),r=Ms(s==null?void 0:s.content),n=Ms(e.lastMessagePreview);return r||n||""}function Bm(e,s=Em){const r=Ms(e);if(!r||s<=0)return"";const n=Array.from(r);return n.length<=s?r:`${n.slice(0,Math.max(0,s-1)).join("").trimEnd()}…`}function Km(e){return Bm(xc(e)||e.displaySecondary||"")}function bc(e){return[e.displaySecondary,pc(e)].filter(Boolean)}function Is(e){return e.agentName||ot(Bt(e))}function Wm(e){var s,r;if(!qt(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return ot(Jr(e)||Bt(e))}function gc(e){return qt(e)?e.sessionId:e.nativeSessionId}function Bo(e){return qt(e)?"native":e.tabKey}function Om(e){return e.sessionId}function Fm(e,s){if(s)return qt(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Hm(e,s){const r=Bt(e),n=qt(e),a=st(e)||Qe(e),i=n?a?Is(e)||(s==null?void 0:s.cliName)||ot(Jr(e)||r):s!=null&&s.type?ot(s.type):ot(Jr(e)||r):Is(e);return{isNativeConversation:n,isCli:st(e),isAcp:Qe(e),isCliTerminal:fc(e),providerType:r,displayLabel:i,targetEntry:Fm(e,s)}}function ts(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:st(e)||Qe(e)?{agentType:Bt(e)}:e.streamSource==="agent-stream"?{agentType:Bt(e)}:s}function Rs(e){return e?dr(e):""}function Os(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function za(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Um(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."}function yc(){return"select_session"}function zm(){return"open_panel"}function Vm({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function Gm(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function Ko(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function Qr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Va(e){return e instanceof Error?e.message:String(e||"")}function Wo(e){const s=Va(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Oo(e,s){const r=Va(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function pn({sendDaemonCommand:e,activeConv:s,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[d,m]=o.useState(null),u=o.useRef(!1),f=o.useRef(null);o.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const b=o.useCallback(async k=>{if(!s||u.current)return!1;const p=k.trim(),x=za(s);if(Vm({hasMessage:!!p,blockedMessage:x,sendInFlight:u.current}))return x&&m(x),!1;const y=Date.now(),N={tabKey:s.tabKey,message:p,timestamp:y};if(Gm(f.current,N))return m(null),!0;u.current=!0,l(!0),m(null),f.current=N;try{const j=Rs(s);if(!j)return f.current=Ko(f.current,N),m("Unable to send message right now."),!1;const I=await e(j,"send_chat",{message:p,...ts(s)}),M=Qr(I);if(M!=null&&M.deduplicated)return m(null),!0;if((M==null?void 0:M.sent)===!1)throw new Error((M==null?void 0:M.error)||"Send failed");if((M==null?void 0:M.success)===!1)throw new Error((M==null?void 0:M.error)||"Send failed");return m(null),!0}catch(j){const I=Va(j);return I.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",I):console.warn("Send blocked/failed",j),f.current=Ko(f.current,N),m(Um(j)),!1}finally{u.current=!1,l(!1)}},[s,e]),S=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(k){console.error("Relaunch failed",k)}},[s,e]),g=o.useCallback(async k=>{if(s)try{const x=(s.modalButtons||[]).indexOf(k),y=k.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y),j=Rs(s);if(!j)return;const I=await e(j,"resolve_action",{button:k,action:N?"approve":"reject",...x>=0&&{buttonIndex:x},...ts(s)}),M=Qr(I);M.success||r(w=>[...w,{routeId:s.tabKey,text:Oo(k,M==null?void 0:M.error),timestamp:Date.now()}])}catch(p){Wo(p)||console.error("[ModalButton] Error:",p),r(x=>[...x,{routeId:s.tabKey,text:Wo(p)?Oo(k,p):`❌ **${k}** error`,timestamp:Date.now()}])}},[s,e,r]),h=o.useCallback(async()=>{if(!(!s||a)){i(!0);try{await e(s.routeId,zm(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(k){console.error("Focus agent failed",k)}finally{i(!1)}}},[s,a,e]);return{isSendingChat:c,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:b,handleRelaunch:S,handleModalButton:g,handleFocusAgent:h}}const qm=10,Ym=8e3,Xm=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function Jm(e){return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s'"`]+/gi,"$1[REDACTED:bearer]").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]{12,}=*/gi,"$1[REDACTED:bearer]").replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{20,}\b/g,"[REDACTED:github-token]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:api-key]").replace(/\b(?:adk|adm)_[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:adhdev-token]").replace(/((?:api[_-]?key|token|secret|password|passwd|client[_-]?secret)\s*[:=]\s*)[^\s,'"`}&]+/gi,"$1[REDACTED:secret]").replace(/([?&](?:api[_-]?key|token|secret|password|client_secret)=)[^&#\s]+/gi,"$1[REDACTED:secret]")}function ba(e,s="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Xm.test(s)&&e.trim())return"[REDACTED:secret-field]";const n=Jm(e);return n.length>8e3?`${n.slice(0,8e3)}…[truncated ${n.length-8e3} chars]`:n}if(typeof e!="object")return String(e);if(r>=6)return"[MaxDepth]";if(Array.isArray(e)){const n=e.slice(-20).map(a=>ba(a,s,r+1));return e.length>20?[{truncatedBefore:e.length-20},...n]:n}return Object.fromEntries(Object.entries(e).slice(0,80).map(([n,a])=>[n,ba(a,n,r+1)]))}function Cr(e,s){return Array.isArray(e)?e.slice(-s):[]}function Qm(e,s=Date.now()){const r=e&&s-e.firstAt<=Ym,n=r?e.count+1:1;return n>=qm?{state:{count:0,firstAt:s},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:s},shouldCollect:!1}}function vc(e){var n;const{activeConv:s}=e,r={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:s.routeId,tabKey:s.tabKey,sessionId:s.sessionId,providerSessionId:s.providerSessionId,transport:s.transport,agentName:s.agentName,agentType:s.agentType,hostIdeType:s.hostIdeType,status:s.status,connectionState:s.connectionState,title:s.title,workspaceName:s.workspaceName,displayPrimary:s.displayPrimary,displaySecondary:s.displaySecondary,streamSource:s.streamSource,lastMessageHash:s.lastMessageHash},messageCounts:{live:s.messages.length,visible:e.visibleMessages.length,history:((n=e.chatTailState.historyMessages)==null?void 0:n.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:Cr(s.messages,10),visibleMessagesTail:Cr(e.visibleMessages,5),historyMessagesTail:Cr(e.chatTailState.historyMessages,5),actionLogsTail:Cr(e.actionLogs.filter(a=>a.routeId===s.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{hasMoreHistory:!!e.chatTailState.hasMoreHistory,historyError:e.chatTailState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return ba(r)}function wc(e,s={}){const r=e&&typeof e=="object"?e:{},n=s.locatorCopyStatus??(s.locatorCopied===!1?"failed":"copied"),a=n==="copied"?"locator copied":n==="manual"?"locator shown for manual copy":"locator copy failed";return r.delivery==="daemon_file"?`Chat debug signal sent${typeof r.bundleId=="string"&&r.bundleId.trim()?` (${r.bundleId})`:""}; saved on daemon, ${a}.`:`Chat debug signal sent; ${a}.`}async function jc(e){var s;if(typeof navigator<"u"&&((s=navigator.clipboard)!=null&&s.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(r){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",r)}if(typeof document<"u"&&document.body){let r=null;try{if(r=document.createElement("textarea"),r.value=e,r.setAttribute("readonly","true"),r.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(r),r.focus(),r.select(),document.execCommand("copy"))return"copied"}catch{}finally{r==null||r.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function kc(e){const s=e&&typeof e=="object"?e:{};if(s.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(s.bundleId||"")}`,`savedPath: ${String(s.savedPath||"")}`,`sizeBytes: ${String(s.sizeBytes||"")}`,`createdAt: ${String(s.createdAt||"")}`];return s.summary&&typeof s.summary=="object"&&r.push("","summary:",JSON.stringify(s.summary,null,2)),Array.isArray(s.warnings)&&s.warnings.length>0&&r.push("","warnings:",...s.warnings.map(n=>`- ${String(n)}`)),r.join(`
|
|
30
|
-
`)}return typeof s.text=="string"?s.text:s.bundle&&typeof s.bundle=="object"?`# ADHDev Chat Debug Bundle
|
|
31
|
-
|
|
32
|
-
\`\`\`json
|
|
33
|
-
${JSON.stringify(s.bundle,null,2)}
|
|
34
|
-
\`\`\``:`# ADHDev Chat Debug Bundle
|
|
35
|
-
|
|
36
|
-
\`\`\`json
|
|
37
|
-
${JSON.stringify(s,null,2)}
|
|
38
|
-
\`\`\``}function kt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ot(e,s){const r=kt(s);return r?`${e}:${r}`:void 0}function Gt(e,s,r){const n=Ot(s,r),a=kt(r);n&&e.push(n),a&&e.push(a)}function js(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function Sc(e){return kt(e.providerSessionId)||kt(e.sessionId)||kt(e.tabKey)||kt(e.routeId)}function Ga(e){return js([kt(e.providerSessionId),kt(e.sessionId)])}function Cs(e){const s=[];return Gt(s,"provider",e.providerSessionId),Gt(s,"session",e.sessionId),Gt(s,"tab",e.tabKey),Gt(s,"route",e.routeId),js(s)}function Zm(e){const s=[];return kt(e.providerSessionId)?(Gt(s,"provider",e.providerSessionId),js(s)):kt(e.sessionId)?(Gt(s,"session",e.sessionId),js(s)):kt(e.tabKey)?(Gt(s,"tab",e.tabKey),js(s)):kt(e.routeId)?(Gt(s,"route",e.routeId),js(s)):[]}function qa(e){return Ot("provider",e.providerSessionId)||Ot("session",e.sessionId)||Ot("tab",e.tabKey)||Ot("route",e.routeId)||"unknown:"}function ur(e){return Ga(e)[0]}function ef(e){const s=kt(e.providerSessionId),r=kt(e.sessionId),n=kt(e.tabKey),a=kt(e.routeId),i=[Ot("provider",s),Ot("session",r),Ot("tab",n),Ot("route",a)].filter(d=>typeof d=="string"),c=Cs({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=qa({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:Sc({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:ur({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function ga(e,s){const r=ef(e);return Zm(s).some(n=>r.lookupKeys.includes(n))}function Fo(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 ss(e){const s=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=Fo(s==null?void 0:s.receivedAt)||Fo(s==null?void 0:s.timestamp)||0;return Math.max(r,n)}function ya(e,s=0){return ss(e)||e.lastUpdated||s||0}function Nc(e){return ss(e)||e.lastUpdated||0}function Cc(e,s,r=Nc){const n=r(s)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(s.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:e.tabKey.localeCompare(s.tabKey)}function va(e){var r;const s=jt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function tf(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!va(e)&&!e.title.trim()}function sf(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(va(r))-Number(va(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Cc(s,r)})[0]||null}function Pt(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=sf(a);return n?i&&tf(n)?i:n:i||r[0]||null}function Yt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ya(e){return ur(e)||e.tabKey||e.routeId||null}function Tc(e){const s=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(s)return s;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Pt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Ya(a):null}function Mc({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=xs(),c=bs(e),l=pc(e),d=e.transport==="cdp-page"||e.transport==="cdp-webview",m=e.streamSource==="agent-stream"&&!!e.agentName,u=!m&&(e.transport==="pty"||e.transport==="acp"),f=Is(e),b=Wm(e),S=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),g=o.useCallback(()=>{if(r){r();return}const h=Ya(e);h&&i(Yt(h))},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[d&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:g,title:b,children:[t.jsx(Tt,{size:12}),t.jsx("span",{children:b})]}):t.jsxs("span",{className:"conversation-meta-chip",title:b,children:[t.jsx(Tt,{size:12}),t.jsx("span",{children:b})]})),m&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(As,{size:12}),t.jsx("span",{children:f})]}),u&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(As,{size:12}),t.jsx("span",{children:f})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:l,children:[t.jsx(ds,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(ds,{size:12}),t.jsx("span",{children:l})]}))]})}function Mn(e,s){return`${e}:${s}`}function rf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Fs(e,s){rf()&&console.debug(`[subscription-manager] ${e}`,s)}class nf{constructor(){Je(this,"active",new Map);Je(this,"retryTimers",new Map)}subscribe(s,r,n,a,i){var u;const c=Mn(n.topic,n.key),l=this.active.get(c);let d=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const f={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,f),Fs("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=s.sendData)==null?void 0:u.call(s,r,n))??!1,!d&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(c,s,i.retryIntervalMs)}const m=()=>{var S;this.clearRetry(c);const f=this.active.get(c);if(!f||(f.handlers.delete(a),f.handlers.size>0))return;this.active.delete(c);const b={type:"unsubscribe",topic:n.topic,key:n.key};Fs("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(S=s.sendData)==null||S.call(s,r,b)};return m.initialSendAccepted=d,m}publish(s){const r=Mn(s.topic,s.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=s,Ts.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),Ts.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=Mn(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;Fs("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);Fs("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)}scheduleRetry(s,r,n){if(this.retryTimers.has(s))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(s);const i=this.active.get(s);if(!i)return;const c=((l=r.sendData)==null?void 0:l.call(r,i.daemonId,i.request))??!1;Fs("subscribe_retry",{id:s,accepted:c,topic:i.request.topic,key:i.request.key}),c||this.scheduleRetry(s,r,n)},n);this.retryTimers.set(s,a)}clearRetry(s){const r=this.retryTimers.get(s);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(s))}}const Ft=new nf;function af(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 of(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 Zr(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=of(d),f=af(i,n),b=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,S=m.filter(k=>k.kind==="workspace"&&k.transport==="cdp-page"),g=m.filter(k=>k.kind==="agent"&&k.transport==="pty"),h=m.filter(k=>k.kind==="agent"&&k.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...b&&{machine:b,platform:b.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},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:S.some(k=>!!k.cdpConnected)});for(const k of S){const p=f.get(k.id),x=qs(k,p),y=(u.get(k.id)||[]).map(N=>qs(N,f.get(N.id)));r.push({id:`${n}:ide:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(p==null?void 0:p.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,status:x.cdpConnected?"online":"detected",daemonId:n,instanceId:k.id,workspace:x.workspace,terminals:0,childSessions:y,agents:y.map(N=>({id:N.id,name:N.providerName||N.providerType,type:N.providerType,status:N.status})),activeChat:x.activeChat,chats:[],cdpConnected:x.cdpConnected,...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},timestamp:l})}for(const k of g){const p=f.get(k.id),x=qs(k,p);r.push({id:`${n}:cli:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(p==null?void 0:p.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:k.id,cliName:x.providerName||x.providerType,mode:x.mode||(p==null?void 0:p.mode)||"terminal",workspace:x.workspace||"",activeChat:x.activeChat,...x.resume!==void 0&&{resume:x.resume},...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},timestamp:l,_isCli:!0})}for(const k of h){const p=f.get(k.id),x=qs(k,p);r.push({id:`${n}:acp:${k.id}`,sessionId:k.id,providerSessionId:k.providerSessionId??(p==null?void 0:p.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:k.id,cliName:x.providerName||x.providerType,mode:"chat",workspace:x.workspace||"",activeChat:x.activeChat,...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const cf=15e3,lf=15e3,df=6e4,uf=1200,Ho=12,mf=8e3,ff=4e3,An=new Map,In=new Map,Tr=new Set,Qs=new Map;function pf(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 Uo(e,s){const r=Qs.get(e);!r||r.size===0||(Qs.delete(e),r.forEach(n=>n(s)))}function hf(e,s){return new Promise(r=>{const n=Qs.get(e)||new Set;Qs.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Qs.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function mr(){const{sendCommand:e,sendData:s}=xt(),{injectEntries:r,getIdes:n}=nr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??df,l=In.get(a)||0;if(!(i!=null&&i.force)&&Tr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const d=An.get(a);if(d)return d;const m=(async()=>{if(s&&!Tr.has(a)){const h=Ft.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},k=>{const p=n(),x=p.find(N=>N.id===a),y=Zr(k.status,{daemonId:a,existingDaemon:x,existingEntries:p,timestamp:k.timestamp});y.length>0&&r(y),In.set(a,Date.now()),Uo(a,!0)});if(h.initialSendAccepted?Tr.add(a):Tr.delete(a),!(i!=null&&i.force)&&h.initialSendAccepted&&await hf(a,uf))return}const u=await e(a,"get_status_metadata"),f=pf(u);if(!f)return;const b=n(),S=b.find(h=>h.id===a),g=Zr(f,{daemonId:a,existingDaemon:S,existingEntries:b,timestamp:f.timestamp||Date.now()});g.length>0&&r(g,{authoritativeDaemonIds:[a]}),In.set(a,Date.now()),Uo(a,!0)})().finally(()=>{An.delete(a)});return An.set(a,m),m},[n,r,e,s])}function xf(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}const bf=60,gf=50;function Ac(e={}){return e.isCliLike?gf:bf}function yf(e={}){return Ac(e)}const fr=60,vf=1e3,Xa=12e4,wf=new Set(["generating","waiting_approval","starting","streaming","working"]),zo=new Map;function Ic(e,s){return`${e}::${s}`}function wa(e=fr){return{liveMessages:[],cursor:jf([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function jf(e,s=fr){return{tailLimit:s}}function Vo(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("|")}class kf{constructor(s){Je(this,"manager");Je(this,"sendData");Je(this,"daemonId");Je(this,"sessionId");Je(this,"historySessionId");Je(this,"subscriptionKey");Je(this,"snapshot");Je(this,"transportSubscription",null);Je(this,"listeners",new Set);Je(this,"retainCount",0);Je(this,"loadHistoryPromise",null);Je(this,"pendingDisconnectTimer",null);this.manager=s.manager||Ft,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=wa(Math.max(0,s.tailLimit??fr))}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);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}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({offset:this.snapshot.historyOffset,excludeRecentCount:this.snapshot.liveMessages.length}),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}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}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)},{retryIntervalMs:vf}))}disconnect(){var s;(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){if(s.error)return;const r=Array.isArray(s.messages)?s.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};Vo(this.snapshot.liveMessages)===Vo(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.emit())}}function Rc(e){const s=Ic(e.daemonId,e.sessionId),r=zo.get(s);if(r)return r.updateOptions(e),r;const n=new kf(e);return zo.set(s,n),n}function Sf(e,s){return{...e,loadHistoryPage:s}}function Nf(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Cf(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(wf.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=s.now??Date.now(),a=Math.max(0,Number(s.recentActivityMs??Xa)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=a:Array.isArray(e.messages)&&e.messages.length>0}function Tf(e=Xa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Mf(e,s={}){const r=new Set,n=[];for(const a of e){if(!Cf(a,s))continue;const i=dr(a),c=a.sessionId||"";if(!i||!c)continue;const l=Ic(i,c);if(r.has(l))continue;r.add(l);const d=ur(a);n.push({daemonId:i,sessionId:c,historySessionId:d||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Nf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Af(e,s){const{sendData:r,sendCommand:n}=xt(),a=(s==null?void 0:s.enabled)!==!1,i=dr(e),c=e.sessionId||"",l=ur(e)||c,d=`daemon:${i}:session:${c}`,m=Math.max(0,(s==null?void 0:s.tailLimit)??fr),u=o.useMemo(()=>!a||!i||!c?null:Rc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:d,sendData:r,tailLimit:m}),[i,a,l,r,c,d,m]),[f,b]=o.useState(()=>(u==null?void 0:u.getSnapshot())||wa(m));o.useEffect(()=>{if(!u){b(wa(m));return}u.retain(),b(u.getSnapshot());const g=u.subscribe(h=>{b(h)});return()=>{g(),u.release()}},[u,m]);const S=o.useCallback(async()=>{!u||!i||!c||await u.loadHistoryPage(async({offset:g,excludeRecentCount:h})=>{const k=e.agentType,p=await n(i,"chat_history",{agentType:k,offset:g,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:h}),x=p&&typeof p=="object"&&"result"in p?p.result||{}:p||{};return{messages:Array.isArray(x.messages)?x.messages:[],hasMore:x.hasMore===!0}})},[e.agentType,u,i,l,n,c]);return o.useMemo(()=>Sf(f,S),[S,f])}function If(e,s){const{sendData:r}=xt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??fr),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??Xa)),c=Tf(i),[l,d]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(f=>f+1)},c);return()=>{clearInterval(u)}},[e.length,n,c]);const m=o.useMemo(()=>Mf(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(f=>Rc({...f,sendData:r,tailLimit:a}));return u.forEach(f=>{f.retain()}),()=>{u.forEach(f=>f.release())}},[m.signature,n,r,a])}function Rf(e,s){return s?s.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Go(e){const s=String(e.role||"").toLowerCase();if(s!=="user"&&s!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function Lf(e,s){if(e.length===0)return[];if(s.some(Go))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const i=e[a];if(!i||!Go(i))continue;const c=String(i.role||"").toLowerCase();n.has(c)||(n.add(c),r.unshift(i))}return r}function _f(e){const{historyMessages:s,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),i=a>0?r.slice(0,a):[],c=a>0?r.slice(-n):r,l=Lf(i,c),d=l.length>0?[...l,...c]:c;return s.length===0?d:[...s,...d]}function Pf(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Df(e){return Pf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Ef(e,s,r=`${s}s`){return`${e} ${e===1?s:r}`}function $f(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Bf(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Lc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function _c(e){const s=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return s||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function Kf(e){return Lc(e)?!1:e.inboxBucket==="task_complete"&&_c(e).length>0}function qo(e){return e.branch||"detached HEAD"}function Wf(e){if(e.error)return`${qo(e)} · Git error: ${e.error}`;const s=[qo(e)];return e.changedFiles>0?s.push(Ef(e.changedFiles,"file")+" changed"):e.dirty||s.push("clean"),e.ahead>0&&s.push(`ahead ${e.ahead}`),e.behind>0&&s.push(`behind ${e.behind}`),e.hasConflicts&&s.push("conflicts"),s.join(" · ")}function Of(e,s){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Wf(s)}`}function Ff(e,s){return e.lastUpdated||e.lastMessageAt||s.lastCheckedAt||0}function Hf(e,s={}){if(s.enabled===!1)return[];if(!Bf(e))return[];const r=Lc(e)?"working":Kf(e)?"complete":null;if(!r)return[];const n=r==="complete"?_c(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${$f(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Of(r,e.git),timestamp:Ff(e,e.git),meta:{source:"git-system-bubble",phase:r,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const Uf=60;function ja({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:d,showMetaChips:m=!1,scrollToBottomRequestNonce:u,isInputActive:f=!0,isVisible:b=!0}){var ve,ae,pe,je,xe,ge,oe;const S=o.useRef(new Map),g=o.useRef(void 0),h=mr(),{sendCommand:k}=xt(),{isVisible:p}=Wa();lr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const x=Nt.useMemo(()=>Es(e),[e.status,e.connectionState]),y=o.useMemo(()=>Hm(e,s),[e,s]),N=o.useMemo(()=>{var le;return Ha((le=y.targetEntry)==null?void 0:le.providerControls,{hostIdeType:e.hostIdeType,providerType:y.providerType})},[e.hostIdeType,y.providerType,(ve=y.targetEntry)==null?void 0:ve.providerControls]),j=Ac({isCliLike:y.isCli||y.isAcp}),I=yf({isCliLike:y.isCli||y.isAcp}),M=Af(e,{enabled:b&&!!e.sessionId,tailLimit:I}),[w,v]=o.useState(j),$=e.tabKey,_=M.historyMessages,T=M.hasMoreHistory,F=M.historyError,B=Rf(e,M);o.useEffect(()=>{v(j)},[j,$]);const L=Math.max(0,B.length-w),C=Ua(e),A=dr(e),K=Df(e),P=za(e),D=a||P,H=!!P,[Q,be]=o.useState(!1);o.useEffect(()=>{const le=y.targetEntry;A&&(!le||le.providerControls===void 0||le.controlValues===void 0)&&h(A,{minFreshMs:3e4}).catch(()=>{})},[A,y.isAcp,(ae=y.targetEntry)==null?void 0:ae.providerControls,(pe=y.targetEntry)==null?void 0:pe.controlValues,h]);const de=o.useCallback(async()=>{if(!Q){if(B.length>w){v(le=>Math.min(B.length,le+Uf));return}be(!0);try{await M.loadHistoryPage()}finally{be(!1)}}},[M,Q,B.length,w]),{allMessages:te,receivedAtMap:Z}=o.useMemo(()=>{const le=_f({historyMessages:_,liveMessages:B,visibleLiveCount:w}),ie=Hf(e),Y=ie.length>0?[...le,...ie]:le,G={};return Y.forEach((ue,ke)=>{const se=`${e.tabKey}:${qr(ue,ke)}`;let Re=xf(ue)||S.current.get(se)||0;Re||(Re=Date.now(),S.current.set(se,Re)),G[qr(ue,ke)]=Re}),{allMessages:Y,receivedAtMap:G}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,L,_,B,w]),ce=o.useMemo(()=>l.filter(le=>le.routeId===e.tabKey).sort((le,ie)=>le.timestamp-ie.timestamp),[l,e.tabKey]),fe=o.useCallback(async()=>{var ke,se;if(!A)return;const le=vc({activeConv:e,visibleMessages:te,actionLogs:l,controls:(ke=y.targetEntry)==null?void 0:ke.providerControls,controlValues:(se=y.targetEntry)==null?void 0:se.controlValues,visibleBarControlCount:N.length,chatTailState:{hasMoreHistory:T,historyError:F,historyMessages:_},ui:{controlsVisible:p,visibleLiveCount:w,hiddenLiveCount:L,isInputActive:f,isVisible:b}}),ie=await k(A,"get_chat_debug_bundle",{agentType:y.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:le}),Y=Qr(ie),G=kc(Y),ue=await jc(G);ue==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),nt.showToast(wc(Y,{locatorCopyStatus:ue}),ue==="failed"?"warning":"success")},[e,l,te,p,y.providerType,(je=y.targetEntry)==null?void 0:je.controlValues,(xe=y.targetEntry)==null?void 0:xe.providerControls,A,T,L,_,f,b,F,k,N.length,w]),J=o.useCallback(()=>{const le=Qm(g.current);g.current=le.state,le.shouldCollect&&fe().catch(ie=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ie),nt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[fe]),me=o.useMemo(()=>{if(B.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((x.isGenerating||e.status==="streaming")&&be(!1),e.status==="not_monitored"&&K)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(As,{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(us,{size:14})," Open ",C," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&K)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(qi,{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(us,{size:14})," Open ",C," 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"&&!Q)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,K,i,c,Q,B.length,C,x.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&t.jsx(Mc,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Lu,{messages:te,actionLogs:ce,agentName:Is(e)||C||"Agent",userName:d,isCliMode:y.isCli||y.isAcp,isWorking:x.isGenerating,contextKey:e.tabKey,receivedAtMap:Z,lastMessageHash:e.lastMessageHash,onLoadMore:de,isLoadingMore:Q,hasMoreHistory:T,hiddenLiveCount:L,loadError:F??void 0,emptyState:me,scrollToBottomRequestNonce:u,isVisible:b}),t.jsx(Pm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:y.providerType,displayLabel:y.displayLabel,controls:(ge=y.targetEntry)==null?void 0:ge.providerControls,controlValues:(oe=y.targetEntry)==null?void 0:oe.controlValues,isActive:f,isCliTerminal:y.isCliTerminal}),!y.isCliTerminal&&t.jsx(mc,{contextKey:e.tabKey,panelLabel:C,isSending:n,isBusy:H,statusMessage:D,onSend:r,isActive:f,showControlsToggle:N.length>0,onControlsToggle:J})]})}let Pc=Xt;function Dc(){return Pc()}class zf{constructor(){Je(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(a=>a(...r))}}let Ec=new zf;class Vf{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,n){return()=>{}}requestRuntimeSnapshot(s,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let dt=new Vf;function Gf(e){e.dashboardWS&&(Ec=e.dashboardWS),e.connectionManager&&(dt=e.connectionManager),e.useDaemonsHook&&(Pc=e.useDaemonsHook)}const qf=.5,Yf=1.25;function ct(e){return Ua(e)}function fs(e){return bc(e).join(" · ")}function $c(e){const s=xc(e);return s||(e.title?e.title:fs(e)||"No messages yet")}function Bc(e,s){const{isReconnecting:r,isConnecting:n}=Es(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Xf(e,s){const r=["Chat",...bc(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function rs(e){return Bc(e)||fs(e)}function Jf(e){return`${ct(e)} · ${$c(e)}`}function Qf(e){const s=Jr(e),r=s?ot(s):Is(e);return`${ct(e)} — ${r||"Agent"}`}function Zf(e){return Is(e)||"CLI"}function Kc(e){return hc(e)}function Wc(e){return e?`Remote · ${ct(e)||e.workspaceName||"Session"}`:"Remote"}function ep({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var re;Xt();const{sendPtyInput:d}=xt(),[m,u]=o.useState(!1),f=o.useRef(!1);f.current=m;const[b,S]=o.useState("Runtime terminal unavailable"),[g,h]=o.useState(!1),[k,p]=o.useState(null),[x,y]=o.useState(!1),[N,j]=o.useState(!1),[I,M]=o.useState(1),[w,v]=o.useState(!1),[$,_]=o.useState({width:0,height:0}),[T,F]=o.useState({width:0,height:0}),[B,L]=o.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[C,A]=o.useState(null),K=o.useRef(null),P=o.useRef(null),D=o.useRef(!1),H=o.useRef(!1),Q=o.useRef(c),be=o.useRef(0),de=o.useRef(!1),te=o.useRef(""),Z=o.useRef(null),ce=o.useRef(!1),fe=o.useRef(!1),J=o.useRef(null),me=o.useRef(null),ve=o.useRef(null),ae=32*1024,pe=()=>{var E,X,ee,ne;return((X=(E=K.current)==null?void 0:E.ownerDocument)==null?void 0:X.defaultView)||((ne=(ee=P.current)==null?void 0:ee.ownerDocument)==null?void 0:ne.defaultView)||window},je=E=>{const X=pe();return{ownerWindow:X,frameId:X.requestAnimationFrame(E)}},xe=()=>{const E=J.current;if(E){try{E.ownerWindow.cancelAnimationFrame(E.frameId)}catch{}J.current=null}},ge=()=>{const E=me.current;if(E){try{E.ownerWindow.clearTimeout(E.timeoutId)}catch{}me.current=null}},oe=()=>{const E=ve.current;if(E){try{E.ownerWindow.clearTimeout(E.timeoutId)}catch{}ve.current=null}},le=()=>{c&&J.current===null&&(J.current=je(()=>{et()}))},ie=e.tabKey,Y=e.sessionId||"",G=e.daemonId||((re=e.routeId)==null?void 0:re.split(":")[0])||e.routeId||"",ue=za(e),ke=m?i||ue:b,se=qf,Re=Yf,$e=.05,Oe=()=>{const E=T.width,X=T.height;if(!Number.isFinite($.width)||$.width<=0||!Number.isFinite($.height)||$.height<=0||!Number.isFinite(E)||E<=0||!Number.isFinite(X)||X<=0)return 1;const ee=$.width/E,ne=$.height/X;return Number(Math.min(Re,Math.max(se,Math.min(ee,ne))).toFixed(2))},He=Oe(),W=D.current&&I>He,Ce=Number.isFinite(T.width)&&T.width>0?Math.max($.width,Math.round(T.width*I)):$.width,Te=Number.isFinite(T.height)&&T.height>0?Math.max($.height,Math.round(T.height*I)):$.height,Le=()=>{je(()=>{const E=P.current;E&&(E.scrollLeft=0,E.scrollTop=E.scrollHeight-E.clientHeight)})},Be=()=>{var E,X;be.current=0,de.current=!1,te.current="",Z.current=null,ce.current=!1,fe.current=!1,D.current||(H.current=!1,M(1)),J.current!==null&&xe(),u(!1),S("Runtime terminal unavailable"),oe(),ge(),p(null),A(null),v(!1),h(!1),y(!1),j(!1),(X=(E=r.current)==null?void 0:E.reset)==null||X.call(E)},Fe=()=>{var E,X;be.current=0,de.current=!1,te.current="",Z.current=null,ce.current=!1,fe.current=!1,J.current!==null&&xe(),u(!0),S(""),oe(),ge(),p(null),A(null),v(!1),h(!1),y(!1),j(!1),(X=(E=r.current)==null?void 0:E.reset)==null||X.call(E)},Ye=()=>{fe.current&&(fe.current=!1,je(()=>{var E,X;(X=(E=r.current)==null?void 0:E.scrollToTop)==null||X.call(E)}))},et=()=>{if(J.current=null,!c)return;const E=te.current;if(!E)return;const X=E.slice(0,ae);te.current=E.slice(X.length);const ee=r.current;if(!ee){te.current=X+te.current,le();return}ee.write(X,()=>{if(te.current.length>0){le();return}Ye()})},ut=E=>{E&&(te.current+=E,le())},ft=(E,X=0,ee,ne,we={})=>{var _e,Se,Pe,Ee;const Ae=!!we.force;!Ae&&X>0&&be.current>=X||!Ae&&X===0&&de.current||(be.current=X,X>0&&y(!0),u(!0),S(""),typeof ee=="number"&&typeof ne=="number"&&ee>0&&ne>0&&((Se=(_e=r.current)==null?void 0:_e.resize)==null||Se.call(_e,ee,ne)),te.current="",(Ee=(Pe=r.current)==null?void 0:Pe.reset)==null||Ee.call(Pe),E?ut(E):Ye())};o.useEffect(()=>{Be()},[Y]),o.useEffect(()=>{var X;if(!Y)return;const E=((X=dt.onRuntimeEvent)==null?void 0:X.call(dt,Y,ee=>{if(!(!ee||ee.sessionId!==Y)){if(ee.type==="runtime_snapshot"){if(!c){Z.current={text:ee.text||"",seq:ee.seq||0,cols:ee.cols,rows:ee.rows,force:!!ee.force};return}ft(ee.text||"",ee.seq||0,ee.cols,ee.rows,{force:!!ee.force});return}if(ee.type==="session_output"){de.current=!0,typeof ee.seq=="number"&&(be.current=Math.max(be.current,ee.seq),ee.seq>0&&y(!0)),f.current||u(!0),f.current||S(""),typeof ee.data=="string"&&ut(ee.data);return}if(ee.type==="session_cleared"){if(!c){ce.current=!0,te.current="",Z.current=null;return}Fe();return}if(ee.type==="session_io_error"){const ne=typeof ee.error=="string"&&ee.error?ee.error:typeof ee.reason=="string"&&ee.reason?ee.reason:"unknown error";u(!1),S(`Runtime input failed: ${ne}`);return}}},G))||(()=>{});return()=>{E()}},[G,Y,r,c]);const pt=async(E={})=>{var X;if(!G||!Y)return{success:!1,error:"daemonId and sessionId are required"};E.preserveStatus||S(E.loadingMessage||"Loading runtime terminal...");try{const ee=await((X=dt.requestRuntimeSnapshot)==null?void 0:X.call(dt,G,Y,{sinceSeq:E.sinceSeq,force:E.force}));return ee&&ee.success===!1?(E.preserveStatus||(u(!1),S(`Runtime terminal unavailable: ${ee.error}`)),ee):ee||{success:!0}}catch(ee){const ne=(ee==null?void 0:ee.message)||String(ee);return E.preserveStatus||(u(!1),S(`Runtime terminal unavailable: ${ne}`)),{success:!1,error:ne}}},Ne=async E=>{var Ae,_e;const X=((Ae=K.current)==null?void 0:Ae.ownerDocument)||document,ee=X.defaultView||window,ne=(_e=ee.navigator)==null?void 0:_e.clipboard;if(ne!=null&&ne.writeText&&ee.isSecureContext)try{return await ne.writeText(E),!0}catch{}let we=null;try{return we=X.createElement("textarea"),we.value=E,we.setAttribute("readonly","true"),we.style.position="fixed",we.style.left="-9999px",we.style.top="0",X.body.appendChild(we),we.focus(),we.select(),X.execCommand("copy")}catch{return!1}finally{we==null||we.remove()}},Ue=E=>{ge(),A(E);const X=pe();me.current={ownerWindow:X,timeoutId:X.setTimeout(()=>{me.current=null,A(ee=>ee===E?null:ee)},2200)}},Xe=E=>{oe(),p(E);const X=pe();ve.current={ownerWindow:X,timeoutId:X.setTimeout(()=>{ve.current=null,p(ee=>ee===E?null:ee)},2200)}},Ve=async()=>{var we,Ae,_e,Se;const E=((Ae=(we=r.current)==null?void 0:we.getSelection)==null?void 0:Ae.call(we))||"",X=((Se=(_e=r.current)==null?void 0:_e.getVisibleText)==null?void 0:Se.call(_e))||"",ee=E.trimEnd()||X.trimEnd();if(!ee){Ue("Nothing to copy");return}if(!await Ne(ee)){Ue("Copy failed");return}Ue(E.trimEnd()?"Copied selection":"Copied visible terminal")},tt=E=>{if(!m||!c)return;((d==null?void 0:d(G,Y,E))??!1)||Ue("Terminal input failed")},O=async()=>{if(g)return;h(!0),p("Loading older terminal output..."),fe.current=!0;const E=await pt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(h(!1),(E==null?void 0:E.success)===!1){fe.current=!1,p(`Older terminal output unavailable: ${E.error}`);return}j(!0),Xe("Older terminal output loaded"),je(()=>{var X;(X=r.current)==null||X.bumpResize()})};o.useEffect(()=>{var X,ee;if(!Y)return;G&&((X=dt.getState)==null?void 0:X.call(dt,G))==="connected"&&pt();const E=(ee=dt.onStateChange)==null?void 0:ee.call(dt,(ne,we)=>{ne!==G||we!=="connected"||pt()});return()=>{E==null||E()}},[G,Y,r]),o.useEffect(()=>{s&&Be()},[s,ie,r]),o.useEffect(()=>{var ne,we;const E=K.current,X=(we=(ne=E==null?void 0:E.ownerDocument)==null?void 0:ne.defaultView)==null?void 0:we.ResizeObserver;if(!E||!X)return;const ee=new X(Ae=>{const _e=Ae[0];if(!_e)return;const{width:Se,height:Pe}=_e.contentRect;_(Ee=>{const Ie=Math.round(Se),Ge=Math.round(Pe);return Ee.width===Ie&&Ee.height===Ge?Ee:{width:Ie,height:Ge}})});return ee.observe(E),()=>ee.disconnect()},[]),o.useEffect(()=>{if(D.current)return;const E=Oe();!Number.isFinite(E)||E<=0||M(X=>H.current?E<X-$e?E:X:(H.current=!0,E))},[T.height,T.width,$.height,$.width]),o.useEffect(()=>{W&&Le()},[W,Te,Ce]),o.useEffect(()=>{var ee;const E=Q.current;if(Q.current=c,!c)return;E||j(!1),ce.current&&(ce.current=!1,Fe());const X=Z.current;X&&(Z.current=null,ft(X.text,X.seq,X.cols,X.rows,{force:!!X.force})),G&&Y&&((ee=dt.getState)==null?void 0:ee.call(dt,G))==="connected"&&pt(),te.current&&J.current===null&&le(),je(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[G,c,Y]),o.useEffect(()=>()=>{J.current!==null&&xe(),ge(),oe()},[]),o.useEffect(()=>{const E=ne=>{var Ae;const we=ne.detail;we!=null&&we.sessionId&&we.sessionId!==Y||m&&((Ae=r.current)==null||Ae.bumpResize())},X=pe(),ee=X===window?[window]:[window,X];for(const ne of ee)ne.addEventListener("adhdev:fit-cli-terminal",E);return()=>{for(const ne of ee)ne.removeEventListener("adhdev:fit-cli-terminal",E)}},[m,Y,r]);const q=m&&x&&!N&&(B.atTop||!B.canScroll)||g||!!k;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:K,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[q&&t.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[t.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{O()},disabled:!Y||g,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:g?"Loading older...":"Load older terminal output"}),k&&t.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:k})]}),t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[C&&t.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:C}),t.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ve()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),t.jsxs("div",{className:"relative",children:[t.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>v(E=>!E),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":w,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),w&&t.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),t.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>v(!1),"aria-label":"Close terminal control keys",children:"×"})]}),t.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B"),children:"Esc"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt(" "),children:"Tab"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\r"),children:"Enter"}),t.jsx("span",{"aria-hidden":"true"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),t.jsx("span",{"aria-hidden":"true"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B[D"),"aria-label":"Arrow left",children:"←"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt("\x1B[C"),"aria-label":"Arrow right",children:"→"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt(""),children:"Ctrl-C"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt(""),children:"Ctrl-D"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>tt(""),children:"Bksp"})]})]})]}),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:()=>{D.current=!0,M(E=>{const X=Math.max(He,Number((E-.1).toFixed(2)));return X>He&&Le(),X})},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:()=>{D.current=!0,M(E=>{const X=Math.min(Re,Number((E+.1).toFixed(2)));return X>He&&Le(),X})},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{ref:P,className:W?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:t.jsx("div",{style:{width:Ce>0?`${Ce}px`:"100%",height:Te>0?`${Te}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:t.jsx("div",{style:{width:T.width>0?`${T.width}px`:"100%",height:T.height>0?`${T.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:I},children:t.jsx(tc,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:F,onScrollMetrics:L,onInput:E=>{!m||(d==null||d(G,Y,E))}})})})}),!m&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:b})]}),t.jsx(mc,{contextKey:e.tabKey,panelLabel:ct(e),isSending:a,isBusy:!!ue,statusMessage:ke,onSend:async E=>ue?!1:n(E),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const tp=5e3,sp=12e3;function rp(e){return e==="disconnected"||e==="reconnecting"}function np({wsStatus:e,showReconnected:s,loginUrl:r,onReconnect:n,reconnectDelayMs:a=tp,reconnectActionDelayMs:i=sp}){const c=rp(e),[l,d]=o.useState(()=>!c||a<=0),[m,u]=o.useState(()=>!c||i<=0),f=o.useRef(!1);o.useEffect(()=>{if(!c){d(!1);return}if(f.current=!1,a<=0){f.current=!0,d(!0);return}d(!1);const j=setTimeout(()=>{f.current=!0,d(!0)},a);return()=>clearTimeout(j)},[a,c]),o.useEffect(()=>{if(!c){u(!1);return}if(i<=0){u(!0);return}u(!1);const j=setTimeout(()=>{u(!0)},i);return()=>clearTimeout(j)},[i,c]);const b=c?l:e==="offline"||e==="auth_failed",S=!!(n&&e!=="auth_failed"&&(!c||m)),g=o.useMemo(()=>!s||e!=="connected"?!1:a<=0||f.current,[a,s,e]),h=e==="auth_failed"?"red":e==="offline"?"orange":"accent",k={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))"},p={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)"},x={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},y="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",N={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return t.jsxs(t.Fragment,{children:[b&&t.jsx("div",{className:y,style:N,children:t.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:k[h],border:p[h],color:x[h]},children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),t.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",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 — refresh the page or try again shortly.")]}),S&&t.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),g&&t.jsx("div",{className:y,style:N,children:t.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function 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",d=()=>{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:d,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Ja({mode:e,onChange:s,compact:r=!1}){const n=r?14:15;return t.jsx("button",{type:"button",onClick:()=>s(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?t.jsx($a,{size:n}):t.jsx(Ht,{size:n})})}const Et="New session",Oc="A connected machine is ready. Start a new session to begin chatting, or open a workspace to launch an IDE, CLI, or ACP session.";function op(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const s=[e.branch||"Git"];return e.changedFiles>0&&s.push(`±${e.changedFiles}`),e.ahead>0&&s.push(`↑${e.ahead}`),e.behind>0&&s.push(`↓${e.behind}`),s.length===1&&e.dirty&&s.push("dirty"),s.join(" ")}function ip(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function cp(e){switch(e){case"conflict":return"border-red-500/25 bg-red-500/[0.08] text-red-400";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-emerald-500/15 bg-emerald-500/[0.06] text-emerald-500"}}function Ls({git:e,className:s="",compact:r=!1}){const n=op(e),a=ip(e);if(!n||!a)return null;const i=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return t.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${cp(a)} ${s}`.trim(),title:i.join(" · ")||n,"data-git-tone":a,children:[t.jsx("span",{"aria-hidden":"true",children:"⑂"}),t.jsx("span",{className:"truncate",children:n})]})}function lp({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 Yo({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Xo({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=dn(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 dashboard-header-inbox-item-preview",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:d=>{d.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),i()},children:"Delete"})]})]})}function dp({activeConv:e,wsStatus:s,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:f,onShowAllHidden:b,onResetPanelsToMain:S,inboxOpen:g,onInboxOpenChange:h,hiddenOpen:k,onHiddenOpenChange:p,onOpenNewSession:x,onOpenDashboardGuide:y,guideNudgeVisible:N=!1,actionShortcuts:j,notifications:I,notificationUnreadCount:M,onOpenNotification:w,onMarkNotificationRead:v,onMarkNotificationUnread:$,onDeleteNotification:_,onOpenGitDialog:T}){const{ides:F,p2pStates:B={}}=Xt(),L=!!e&&st(e)&&!Qe(e),C=!!e&&Qe(e),A=l||(e?fc(e)?"terminal":"chat":null),[K,P]=o.useState(!1),D=o.useRef(null),H=o.useRef(null),Q=F.filter(ae=>ae.type==="adhdev-daemon"),be=lp({wsStatus:s,isConnected:r,daemonCount:Q.length,p2pStates:B}),de=be.subtitle,te=be.tone==="connected"?"#22c55e":be.tone==="limited"?"#eab308":"#ef4444",Z=be.tone==="connected"?"0 0 4px #22c55e80":be.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",ce=o.useMemo(()=>I.filter(ae=>!ae.readAt),[I]),fe=o.useMemo(()=>I.filter(ae=>!!ae.readAt),[I]),J=o.useMemo(()=>ce.slice(0,9),[ce]),me=M;o.useEffect(()=>{if(!g)return;const ae=pe=>{var je;(je=D.current)!=null&&je.contains(pe.target)||h(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[g,h]),o.useEffect(()=>{if(!k)return;const ae=pe=>{var je;(je=H.current)!=null&&je.contains(pe.target)||p(!1)};return document.addEventListener("mousedown",ae),()=>document.removeEventListener("mousedown",ae)},[k,p]),o.useEffect(()=>{if(!k&&!g)return;const ae=pe=>{if(!pe.altKey)return;const je=pe.code.match(/^Digit([1-9])$/);if(!je)return;const xe=Number(je[1])-1,ge=k?u[xe]:void 0,oe=g?J[xe]:void 0;if(!(!ge&&!oe)){if(pe.preventDefault(),pe.stopPropagation(),ge){f==null||f(ge),p(!1);return}oe&&(w(oe),h(!1))}};return window.addEventListener("keydown",ae,!0),()=>window.removeEventListener("keydown",ae,!0)},[u,k,g,J,p,h,w,f]);const ve=ae=>{if(!ae)return;const pe=n.find(je=>je.tabKey===ae);pe&&(m==null||m(pe))};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(Ht,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?ct(e):"Dashboard"}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:te,boxShadow:Z}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:be.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:te,boxShadow:Z}}),de&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",de]}),x&&t.jsx("button",{type:"button",onClick:x,className:"btn btn-secondary btn-sm ml-2",title:`${Et}${j!=null&&j.openNewSession?` (${j.openNewSession})`:""}`,"aria-label":Et,children:t.jsx(Xi,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[y&&t.jsxs("button",{type:"button",onClick:y,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[t.jsx("span",{className:"font-semibold leading-none",children:"?"}),N&&t.jsx("span",{children:"Guide"})]}),e&&(L||C||!Qe(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:fs(e)||ct(e),children:ct(e)}),T&&e.git&&e.daemonId&&e.workspacePath?t.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>T(e.daemonId,e.workspacePath),children:t.jsx(Ls,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):t.jsx(Ls,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(L||C)&&c&&t.jsxs(t.Fragment,{children:[L&&d&&A&&t.jsx(Ja,{mode:A,onChange:d,compact:!0}),t.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:C?"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(vt,{size:14})})]}),!Qe(e)&&t.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Da,{size:14})}),!L&&!Qe(e)&&t.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Tt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:D,children:[t.jsxs("div",{className:`dashboard-header-hidden${K?" is-drop-target":""}`,ref:H,onDragEnter:ae=>{ae.dataTransfer.types.includes("text/tab-key")&&(ae.preventDefault(),P(!0))},onDragOver:ae=>{ae.dataTransfer.types.includes("text/tab-key")&&(ae.preventDefault(),ae.dataTransfer.dropEffect="move",P(!0))},onDragLeave:ae=>{ae.currentTarget.contains(ae.relatedTarget)||P(!1)},onDrop:ae=>{const pe=ae.dataTransfer.getData("text/tab-key");ae.preventDefault(),P(!1),ve(pe)},children:[t.jsxs("button",{type:"button",onClick:()=>p(!k),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${j!=null&&j.toggleHiddenTabs?` (${j.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(Ea,{size:16}),u.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),k&&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(Yo,{value:j==null?void 0:j.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[S&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:S,children:"Reset panels"}),u.length>0&&b&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{b(),p(!1)},children:"Restore all"})]})]}),e&&m&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(Yo,{value:j==null?void 0:j.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:ct(e)})]}),u.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(ae=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{f==null||f(ae),p(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:ct(ae)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(ae)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(ae)+1]}):null,fs(ae)]})]},ae.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>h(!g),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(ln,{size:16}),me>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:me})]}),g&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ce.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),ce.map(ae=>t.jsx(Xo,{notification:ae,shortcutIndex:J.indexOf(ae)>=0?J.indexOf(ae)+1:void 0,onOpen:()=>w(ae),onMarkRead:()=>v(ae.id),onMarkUnread:()=>$(ae.id),onDelete:()=>_(ae.id)},ae.id))]}),fe.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),fe.map(ae=>t.jsx(Xo,{notification:ae,onOpen:()=>w(ae),onMarkRead:()=>v(ae.id),onMarkUnread:()=>$(ae.id),onDelete:()=>_(ae.id)},ae.id))]}),I.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function gt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function up(e,s){return String(e||"")!==String(s||"")}function mp(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(d=>String(d||"").toLowerCase()).join(`
|
|
39
|
-
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!ic(c.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
40
|
-
`).includes(a)))}function fp(e,s="recent"){const r=e.slice();return r.sort((n,a)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(s==="messages"){const i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function Fc(e,s={}){return fp(mp(e,s),s.sortMode||"recent")}function en(e){return e?"Resume saved history":"Start fresh"}function Qa(e){return e?"Resuming saved history…":"Starting fresh…"}function pp(){return"Start fresh"}function Hc(e,s=!1){return e==="cli"?en(s):e==="ide"?"Start IDE":"Start ACP session"}function Uc(e,s=!1){return e==="cli"?Qa(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function hp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function xp(){return"Open saved history"}function bp(){return"Saved History"}function Za(){return"Use saved history when you want continuity in the same provider conversation."}function gp(){return"No saved history found yet."}function yp(){return"Refresh saved history"}function vp(){return"Refreshing saved history…"}function ns(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function as(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 _s(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ps(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function eo(e){return`Resume saved history with ${e}?`}function to(){return"Review or change the target workspace before resuming saved history."}function wp(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function so({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:f,onSwitchSession:b,onRefreshHistory:S,onResumeSavedSession:g}){var _;const h=s.find(T=>T.id===e.routeId),k=(h==null?void 0:h.chats)||[],p=(_=h==null?void 0:h.activeChat)==null?void 0:_.id,x=st(e)&&!Qe(e),[y,N]=o.useState(()=>gt()),j=l||y,I=String(d||"").trim(),M=T=>{if(m){m(T);return}N(T)},w=o.useMemo(()=>a.map(T=>{const F=String(T.workspace||"").trim();return T.canResume||F||!I?T:{...T,workspace:I,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[I,a]),v=o.useMemo(()=>Fc(w,{textQuery:j.textQuery,workspaceQuery:j.workspaceQuery,modelQuery:j.modelQuery,resumableOnly:j.resumableOnly,sortMode:j.sortMode}),[w,j.modelQuery,j.resumableOnly,j.sortMode,j.textQuery,j.workspaceQuery]),$=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:u,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?bp():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Qf(e)}),x&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Za()})]}),t.jsx("button",{onClick:u,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(vt,{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:f,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:j.textQuery,onChange:T=>M({...j,textQuery:T.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:j.workspaceQuery,onChange:T=>M({...j,workspaceQuery:T.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:j.modelQuery,onChange:T=>M({...j,modelQuery:T.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:j.sortMode,onChange:T=>M({...j,sortMode:T.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:j.resumableOnly,onChange:T=>M({...j,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),v.map(T=>{const F=e.providerSessionId===T.providerSessionId,B=F||!T.canResume||!!c,L=T.workspaceFallbackSource==="selected-workspace";return t.jsxs("button",{type:"button",onClick:()=>{B||!g||g(T)},disabled:B,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${F?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${B?"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 ${F?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:T.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:wp(T.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:T.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:[T.workspace||"Workspace unknown",L?" · selected workspace":"",ms(T.summaryMetadata)?` · ${ms(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:F?"ACTIVE":T.canResume?L?"RESUME IN SELECTED WORKSPACE":c===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):k.map(T=>t.jsxs("div",{onClick:()=>{b(e.routeId,T.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${p===T.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===T.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.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:[T.id.substring(0,12),"..."]}),p===T.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},T.id)),(x&&!i&&v.length===0||!x&&k.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(au,{size:32})}),t.jsx("div",{className:"text-[13px]",children:x?a.length>0?"No saved history matches these filters.":gp():"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:vp()})})]}),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:S,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(cr,{size:13})," ",x?yp():"Refresh History"]})})})]})]});return typeof document>"u"?$:rr.createPortal($,document.body)}const Jo={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 zc({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=Jo[n.type]||Jo.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(vt,{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 jp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function kp(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Sp(e){return e.sessionId||e.instanceId||e.agentType}function Rn(e,s){return e||s}function Vc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Ct(r,{fallbackId:r.id}));return s}function Gc(e,s={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=s.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function ro(e,s={}){return Np(e,Gc(e,s))}function Np(e,s={}){var f,b,S,g,h,k;const r=[],n=s.machineName,a=s.connectionState,i=kp(e),c=e.workspace||"",l=Zu(e.type,{agentName:e.cliName}),d=st(e)||Qe(e)?l:ot(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(p=>{var x,y;return{sessionId:p.id,instanceId:p.id,providerSessionId:p.providerSessionId,transport:p.transport,sessionCapabilities:p.capabilities,agentType:p.providerType,agentName:p.providerName||ot(p.providerType),status:p.status,title:p.title,lastMessagePreview:p.lastMessagePreview,lastMessageRole:p.lastMessageRole,lastMessageAt:p.lastMessageAt,lastMessageHash:p.lastMessageHash,messages:((x=p.activeChat)==null?void 0:x.messages)||[],activeModal:((y=p.activeChat)==null?void 0:y.activeModal)||void 0,unread:p.unread,lastSeenAt:p.lastSeenAt,lastUpdated:p.lastUpdated,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,surfaceHidden:p.surfaceHidden,git:p.git}}):[],u=jp(e);if(u){const p=e.sessionId||e.instanceId,x=l,y=(f=e.activeChat)==null?void 0:f.activeModal,N=y&&Array.isArray(y.buttons)&&y.buttons.length>0,j=jt((b=e.activeChat)==null?void 0:b.status,{activeModal:(S=e.activeChat)==null?void 0:S.activeModal})||jt((h=(g=e.agents)==null?void 0:g[0])==null?void 0:h.status)||"idle",I=e.activeChat||{title:"",messages:[]};let M=I.title&&String(I.title).trim()?String(I.title).trim():"";const w=(k=e.activeChat)==null?void 0:k.id,v=e.chats;if(w&&Array.isArray(v)&&v.length>0){const F=v.find(B=>B.id===w||B.id&&String(B.id)===String(w));F!=null&&F.title&&String(F.title).trim()&&(M=String(F.title).trim())}const $=(st(e)||Qe(e),e.type),_=(st(e)||Qe(e))&&Do(M,x,$)?"":M,T=I.messages||[];r.push({routeId:e.id,sessionId:p,providerSessionId:e.providerSessionId,nativeSessionId:p,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:st(e)?e.mode||"terminal":"chat",agentName:x,agentType:$,status:j,title:_,messages:T,resume:e.resume,hostIdeType:!st(e)&&!Qe(e)?e.type:void 0,workspaceName:i,workspacePath:c,git:e.git,displayPrimary:_||i||(st(e)?e.mode==="chat"?x:"Terminal":x),displaySecondary:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:N?y.buttons:void 0,modalMessage:N?y.message:void 0,streamSource:"native",tabKey:Rn(p,e.id),machineName:n,connectionState:a})}if(u&&(st(e)||Qe(e)))return r;for(const p of m){const x=p.activeModal&&Array.isArray(p.activeModal.buttons)&&p.activeModal.buttons.length>0,y=em(p),N=Sp(p),j=`${e.id}:${N}`,I=p.title&&String(p.title).trim()||"",M=Do(I,p.agentName,p.agentType)?"":I,w=p.messages||[];(p.transport==="cdp-webview"||p.sessionId||p.providerSessionId||w.length>0||x||M||!["idle","panel_hidden","disconnected","not_monitored"].includes(y))&&r.push({routeId:e.id,sessionId:p.sessionId||p.instanceId,providerSessionId:p.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:p.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:p.sessionCapabilities,mode:"chat",agentName:p.agentName,agentType:p.agentType,status:y,title:M,messages:w,hostIdeType:e.type,workspaceName:i,workspacePath:c,git:p.git||e.git,displayPrimary:M||i||p.agentName||d,displaySecondary:`${d} · ${p.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:p.lastMessagePreview,lastMessageRole:p.lastMessageRole,lastMessageAt:p.lastMessageAt,lastMessageHash:p.lastMessageHash,lastUpdated:p.lastUpdated||e.lastUpdated,inboxBucket:p.inboxBucket,completionMarker:p.completionMarker,modalButtons:x?p.activeModal.buttons:void 0,modalMessage:x?p.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Rn(p.sessionId||p.instanceId,j),machineName:n,connectionState:a})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:i,workspacePath:c,git:e.git,displayPrimary:i||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Rn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function Cp(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 qc(e,s){const r=Cp(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Yc=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],Xc=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],Jc=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],Tp=Yc,Mp=Xc,Ap=Jc;function Ut(...e){return gd(yd(e))}function Ip({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:Ut("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 Zs({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(Ip,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:Ut("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const ka="adhdev:themechange";function Rp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function vs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ws(e){return e==="system"?Rp():e}function Qc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Br(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(ka,{detail:{preference:e,theme:s}}))}function Lp(){const e=vs(),s=ws(e);Qc(s),Br(e,s)}function no(){const[e,s]=o.useState(vs),[r,n]=o.useState(()=>ws(vs()));o.useEffect(()=>{Qc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),Br("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=d=>{const m=d.detail||{},u=m.preference,f=m.theme;s(u==="dark"||u==="light"||u==="system"?u:vs()),n(f==="dark"||f==="light"?f:ws(vs()))},l=d=>{if(d.key!=="theme")return;const m=vs(),u=ws(m);s(m),n(u)};return window.addEventListener(ka,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ka,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=ws(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Br(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",d=ws(l);n(d);try{localStorage.setItem("theme",l)}catch{}return Br(l,d),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const Qo={dark:"Dark",light:"Light",system:"System"};function _p({collapsed:e}){const{preference:s,cycleTheme:r}=no(),n=s==="dark"?t.jsx(iu,{size:16}):s==="light"?t.jsx(ou,{size:16}):t.jsx(cu,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Qo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Qo[s]})]})}function Ln(e,s){return e?typeof e=="function"?e(s):e:null}function Pp({children:e,brand:s,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=o.useState(!1),[f,b]=o.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),S=()=>u(!0),g=()=>u(!1),h=()=>{b(y=>{const N=!y;try{localStorage.setItem(d,N?"1":"0")}catch{}return N})},k=o.useMemo(()=>({collapsed:f,mobileMenuOpen:m,openMobileMenu:S,closeMobileMenu:g,toggleCollapsed:h}),[f,m]),p=y=>`nav-item${y.active?" active":""} cursor-pointer ${f?"justify-center py-2.5 px-0":""}${y.className?` ${y.className}`:""}`,x=y=>t.jsxs("div",{className:p(y),id:`nav-${y.id}`,onClick:()=>{y.onSelect(),g()},title:f?y.title??(typeof y.label=="string"?y.label:void 0):y.title,children:[t.jsx("span",{className:"nav-icon",children:y.icon}),!f&&y.label]},y.id);return t.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:S,children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),m&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:g,onKeyDown:y=>y.key==="Escape"&&g()}),t.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsx("div",{className:`sidebar-logo ${f?"justify-center gap-0":""}`,children:Ln(s,k)}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:g,children:t.jsx(vt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:r.map(x)}),n.map(y=>t.jsxs("div",{className:y.className??"border-t border-border-subtle pt-2 mt-2",children:[!f&&y.title?t.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:y.title}):null,y.items.map(x)]},y.key)),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(x),Ln(i,k),t.jsx(_p,{collapsed:f}),Ln(c,k)]})]}),t.jsx("main",{className:"main-content relative",children:t.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function yt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:Ut("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 tn({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:Ut("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 Dp={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"},Ep={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function ks({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:Ut("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Dp[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:Ep[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:"✕"})]})}function _n({label:e,hint:s,children:r,className:n}){return t.jsxs("div",{className:Ut("mb-5",n),children:[t.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,s&&t.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:s})]})}function Pn(e){const{className:s,...r}=e;return t.jsx("input",{...r,className:Ut("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",s)})}const $p={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"},Bp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Kp({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:Ut("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",$p[e],r),children:[t.jsx("span",{className:Ut("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Bp[e])}),n]})}function Zt({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 Wp({onPrefChange:e}){const[s,r]=dm(),[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(Zt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ln,{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(Zt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tt,{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:()=>{dc().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(Zt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(lu,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(Zt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(du,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(Zt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(As,{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 sn(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Op(e,s){const r=sn(e),n=sn(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 Zc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function er(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Op(r,s)>=0)return!1;const n=sn(r),a=sn(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Fp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Dn(e,s){return e instanceof Error?e.message:s}function Hp({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(tn,{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(zp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Zo({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 rr.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 Up(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Tp,...Mp,...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 zp({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var B,L;const[i,c]=o.useState("idle"),[l,d]=o.useState(""),[m,u]=o.useState(null),[f,b]=o.useState("idle"),[S,g]=o.useState(""),h=e.version||null,k=((B=e.machine)==null?void 0:B.platform)||((L=e.system)==null?void 0:L.platform)||"",p=Ct(e,{fallbackId:e.id}),x=k==="win32"?"🪟":k==="darwin"?"🍎":"🐧",y=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),N=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),j=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),I=e.p2p,M=async()=>{if(r){c("upgrading"),d("Starting upgrade...");try{const C=Fp(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),d(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),d(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),d(C.error||"Upgrade failed"))}catch(C){c("error"),d(Dn(C,"Connection lost during upgrade"))}}},w=async()=>{if(u(null),!!n){b("loading");try{await n(e.id),b("done"),g("Machine disconnected.")}catch(C){b("error"),g(Dn(C,"Failed to disconnect"))}}},v=async()=>{if(u(null),!!a){b("loading");try{await a(e.id),b("done"),g("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){b("error"),g(Dn(C,"Failed to revoke token"))}}},$="0.9.70",_=Zc(e,$),T=er(e,$),F=y.length+N.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:x}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:p}),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),"…"]}),h&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${_?"":"bg-bg-secondary"}`,style:_?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",h,!_&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&_&&t.jsx("button",{onClick:M,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":`${T?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&t.jsx("button",{onClick:()=>u("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>u("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(Kp,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[I&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&F>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),F>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[y.map(C=>{const A=Up(C.type),K=C.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:A.icon}),t.jsx("span",{children:A.name}),K!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${K?"bg-green-400":"animate-pulse"}`,style:K?void 0:{background:"var(--status-warning)"},title:K?"CDP connected":"CDP connecting..."})]},C.id)}),N.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:C.cliName||"CLI"})]},C.id)),j.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||S)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-red-400":i==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:S||l})]}),m==="disconnect"&&t.jsx(Zo,{title:"🔌 Disconnect Machine",message:`Disconnect "${p}" from ADHDev?
|
|
41
|
-
|
|
42
|
-
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
43
|
-
|
|
44
|
-
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:w,onCancel:()=>u(null)}),m==="revoke"&&t.jsx(Zo,{title:"⚠️ Remove Machine",message:`Remove "${p}" from your dashboard?
|
|
45
|
-
|
|
46
|
-
This will:
|
|
47
|
-
• Immediately disconnect the machine
|
|
48
|
-
• Delete the machine registration
|
|
49
|
-
• Require restarting ADHDev on that machine
|
|
50
|
-
|
|
51
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:v,onCancel:()=>u(null)})]})}const Vp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Gp(){const{preference:e,setPreference:s}=no();return t.jsx("div",{className:"flex gap-2",children:Vp.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 qp(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 Yp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function En(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function ei(e){const{r:s,g:r,b:n}=Yp(e);return .2126*En(s)+.7152*En(r)+.0722*En(n)}function ti(e,s){const r=ei(e),n=ei(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function el(e){const s=qp(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return ti(s,r)>=ti(s,n)?r:n}const Sa={bgPrimary:"#0a0e1a",bgSecondary:"#0f1320",surfacePrimary:"#111726",textPrimary:"#f0f0f5",textSecondary:"#9ca3af",textMuted:"#6b7280",borderSubtle:"#1d2536",borderDefault:"#313c52",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#111726",assistantText:"#f0f0f5",containerBg:"#0f1320",sendButton:"#d97706",inputBorder:"#313c52",bubbleRadius:16},Na={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},Xp=[{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"}}}],tl="adhdev-chat-theme",sl="adhdev-chat-theme-custom";function Kr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(tl)||"ember"}catch{return"ember"}}function _t(e){try{const s=localStorage.getItem(sl);if(s){const r=JSON.parse(s);return{...e==="dark"?Sa:Na,...r[e]}}}catch{}return e==="dark"?Sa:Na}function Mr(e,s){try{localStorage.setItem(sl,JSON.stringify({dark:e,light:s}))}catch{}}function Mt(e,s){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${s})`}function rn(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),a=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const Jp={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function tr(e,s){var a;const r=(a=Jp[e])==null?void 0:a[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",rn(r,24)),n.style.setProperty("--accent-on-primary",el(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${rn(r,18)})`),n.style.setProperty("--border-accent",Mt(r,.35)),n.style.setProperty("--nav-active-bg",Mt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Mt(r,.06)}`)}function os(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Mt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Mt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Mt(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",Mt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Mt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",rn(e.accentColor,30)),s.style.setProperty("--accent-on-primary",el(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${rn(e.accentColor,40)})`),s.style.setProperty("--border-accent",Mt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Mt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Mt(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${Mt(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function ao(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(r=>e.style.removeProperty(r))}function Qp(e){try{localStorage.setItem(tl,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=is()?"dark":"light";os(_t(s))}else ao(),tr(e,is()?"dark":"light")}function Zp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Kr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=is()?"dark":"light";os(_t(s))}else ao(),tr(e,is()?"dark":"light")}function is(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function wt({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 Hs({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 eh({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>_t(r));o.useEffect(()=>{a(_t(r))},[r]);const i=o.useCallback((c,l)=>{a(d=>{const m={...d,[c]:l},f=_t(r==="dark"?"light":"dark");return r==="dark"?Mr(m,f):Mr(f,m),os(m),s(m),m})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(Hs,{title:"App Background",children:[t.jsx(wt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(wt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(wt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Hs,{title:"App Text",children:[t.jsx(wt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(wt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(wt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Hs,{title:"Borders & Accent",children:[t.jsx(wt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(wt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(wt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Hs,{title:"Chat Bubbles",children:[t.jsx(wt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(wt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(wt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(wt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Hs,{title:"Chat Layout",children:[t.jsx(wt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(wt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(wt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const c=e?Sa:Na,d=_t(e?"light":"dark");e?Mr(c,d):Mr(d,c),a(c),os(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 th(){const[e,s]=o.useState(Kr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>_t("dark"));o.useEffect(()=>{n(is());const d=new MutationObserver(()=>{const f=is();n(f);const b=Kr();b==="custom"?os(_t(f?"dark":"light")):tr(b,f?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const f=is();n(f);const b=Kr();b==="custom"?os(_t(f?"dark":"light")):tr(b,f?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?os(_t(r?"dark":"light")):(ao(),tr(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(_t(r?"dark":"light"))},[r]);const c=d=>{s(d),Qp(d)},l=[...Xp,{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(d=>{const m=e===d.id,u=r?d.preview.dark:d.preview.light,f=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.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:u.userBubble,color:f},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[m&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&t.jsx(eh,{dark:r,onColorsChange:d=>i(d)})]})}const oo="adhdev_mobileDashboardMode_v1",Ca="adhdev:mobile-dashboard-mode-change";function io(){try{return localStorage.getItem(oo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function sh(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??io())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==oo||s()};return window.addEventListener(Ca,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Ca,r),window.removeEventListener("storage",n)}}function rh(e){try{localStorage.setItem(oo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ca,{detail:e}))}function nh(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(io()==="chat")},[]),t.jsx(Zt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ht,{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),rh(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const $n=new Map,si=new Map;function ah(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function oh(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 rl(){const{sendCommand:e}=xt(),{injectEntries:s,getIdes:r}=nr();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??lf,c=si.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=$n.get(n);if(l)return l;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=ah(m);if(!u)return;const f=r().find(S=>S.id===n),b=oh(f,n,u.machine,u.timestamp||Date.now());s([b]),si.set(n,Date.now())})().finally(()=>{$n.delete(n)});return $n.set(n,d),d},[r,s,e])}function ih(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 ch(e,s){const{sendData:r}=xt(),{injectEntries:n,getIdes:a}=nr(),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(d=>Ft.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:s==null?void 0:s.intervalMs}},u=>{const f=a().find(S=>S.id===d),b=ih(f,d,u);n([b])}));return()=>{l.forEach(d=>d())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function lh(e,s){const{sendData:r}=xt(),[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 d=Ft.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},m=>{l&&(clearTimeout(l),l=null),a(m.diagnostics),c(!1)});return d.initialSendAccepted?l=setTimeout(()=>{c(!1)},ff):c(!1),()=>{l&&clearTimeout(l),d()}},[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 dh(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function nl(e){const{sendData:s}=xt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=dh(e);if(!a||!e.sessionId||!s){n({});return}const i=Ft.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}),Ts.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 al="adhdev_hiddenTabs";function uh(){try{const e=localStorage.getItem(al);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function gs(e){try{localStorage.setItem(al,JSON.stringify([...e]))}catch{}}function Bn(e){return qa(e)}function co(e,s){return Cs(s).some(r=>e.has(r))}function mh(){const[e,s]=o.useState(uh),r=o.useCallback(m=>{const u=Bn(m);s(f=>{const b=new Set(f);return b.has(u)?b.delete(u):b.add(u),gs(b),b})},[]),n=o.useCallback(m=>{const u=Bn(m);s(f=>{if(f.has(u))return f;const b=new Set(f);return b.add(u),gs(b),b})},[]),a=o.useCallback(m=>{const u=Bn(m);s(f=>{if(!f.has(u))return f;const b=new Set(f);return b.delete(u),gs(b),b})},[]),i=o.useCallback(()=>{s(m=>{if(m.size===0)return m;const u=new Set;return gs(u),u})},[]),c=o.useCallback((m,u)=>{s(f=>{const b=new Set(f);for(const S of u)b.add(S);return gs(b),b})},[]),l=o.useCallback((m,u)=>{s(f=>{const b=new Set(f);for(const S of u)b.delete(S);return gs(b),b})},[]),d=o.useCallback(m=>co(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:d}}function ol(e){return e instanceof Error?e.message:String(e||"")}function il(e){const s=ol(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 cl(e){const s=ol(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}async function ll({conversation:e,mode:s,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!st(e)||Qe(e))return;const i=$s(e);if(i===s)return;const c=e.sessionId;c&&a(l=>({...l,[c]:s}));try{await n(bs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Bt(e),mode:s})}catch(l){const d=cl(l);c&&!d&&a(m=>{const u={...m};return i===dl(r,c)?delete u[c]:u[c]=i,u}),il(l)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",l instanceof Error?l.message:String(l)):console.error("Failed to switch CLI view mode:",l)}}function ri(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 fh(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=ri(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(d=>ri(d,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function dl(e,s){if(!s)return null;for(const r of e){if(r.sessionId===s&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===s&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function ph(e,s){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))dl(s,a)===i&&(delete n[a],r=!0);return r?n:e}function hh({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{dc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Kc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return pm(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const d=Date.now(),m={};for(const[u,f]of Object.entries(l))d-f<5e3&&(m[u]=f);return Object.keys(m).length===Object.keys(l).length?l:m})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const d=l.filter(m=>m.timestamp>c).slice(-100);return d.length===l.length?l:d})},6e4);return()=>clearInterval(i)},[n]),null}function xh(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 Kn(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 bh(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 ni(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?bh(Ms(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 gh(e){const s=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),ni(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),ni(r.activeChat)].join(":"))].join("|")}function yh(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 vh(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of Cs({routeId:n.routeId}))r.set(i,a);for(const i of Cs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of Cs({tabKey:n.tabKey}))r.set(i,n)}return r}function wh(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function jh(e){const s=wh(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=Ms(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function kh({ides:e,connectionStates:s,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>xh(e),[e]),i=o.useMemo(()=>Vc(e),[e]),c=o.useRef([]),l=o.useRef([]),d=o.useRef([]),m=o.useRef(new Map),u=o.useRef(new Map),f=o.useMemo(()=>{const N=new Map,j=[];for(const v of a){const{connectionState:$="new",machineName:_}=Gc(v,{machineNames:i,connectionStates:s,defaultConnectionState:"new"}),T=gh(v),F=m.current.get(v.id);if(F&&F.ide===v&&F.sourceSignature===T&&F.connectionState===$&&F.machineName===_){N.set(v.id,F),j.push(...F.conversations);continue}const B=ro(v,{machineNames:i,connectionStates:s,defaultConnectionState:"new"}),L={ide:v,sourceSignature:T,connectionState:$,machineName:_,conversations:B};N.set(v.id,L),j.push(...B)}m.current=N;const I=new Map,M=v=>{const $=jh(v),_=u.current.get(v.tabKey);if(_&&_.signature===$)return I.set(v.tabKey,_),_.timestamp;const T={signature:$,timestamp:Nc(v)||(_==null?void 0:_.timestamp)||0};return I.set(v.tabKey,T),T.timestamp},w=[...j].sort((v,$)=>Cc(v,$,M));return u.current=I,w},[a,s,i]),b=o.useMemo(()=>{const N=yh(f,r);return Kn(c.current,N)?c.current:(c.current=N,N)},[f,r]),S=o.useMemo(()=>{const N=new Map,j=Array.from(new Set(b.map(I=>I.routeId)));for(const I of j){const M=Pt(b,I);M&&N.set(I,M)}return N},[b]),g=o.useMemo(()=>{const N=new Map;for(const j of b){const I=S.get(j.routeId),M=j.streamSource==="native"&&I?I:j;for(const w of Cs({providerSessionId:j.providerSessionId,sessionId:j.sessionId}))N.set(w,M)}return N},[b,S]),h=o.useMemo(()=>vh(b,S),[b,S]),k=o.useCallback(N=>{if(N)return g.get(N)},[g]),p=o.useCallback(N=>{if(N)return h.get(N)},[h]),x=o.useMemo(()=>{const N=b.filter(j=>!co(n,j));return Kn(l.current,N)?l.current:(l.current=N,N)},[b,n]),y=o.useMemo(()=>{const N=x.map(j=>j.tabKey);return Kn(d.current,N)?d.current:(d.current=N,N)},[x]);return{chatIdes:a,conversations:b,visibleConversations:x,visibleTabKeys:y,resolveConversationBySessionId:k,resolveConversationByTarget:p}}function Sh({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 d=new URLSearchParams(l);return d.delete("activeTab"),d},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Nh({ides:e,sendDaemonCommand:s,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{nt.setIdes(e)},[e]),o.useEffect(()=>{nt.setResolveAction((a,i,c)=>{s(a,i,c).catch(()=>{})})},[s]),o.useEffect(()=>{const a=nt.onToast(i=>{r(l=>l.some(m=>m.message===i.message&&i.timestamp-m.timestamp<3e3)?l:[...l.slice(-4),{id:i.id,message:i.message,type:i.type,timestamp:i.timestamp,targetKey:i.targetKey,actions:i.actions}]);const c=i.duration||5e3;setTimeout(()=>r(l=>l.filter(d=>d.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=Ec.on("status_event",i=>{nt.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var h;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const d=l.targetSessionId||l.targetKey||l.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||l.daemonId;if(!u)return;const f=Number(l.buttonIndex),b=l.button||((h=m==null?void 0:m.modalButtons)==null?void 0:h[f])||"Approve",S=String(b).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),g=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(S);s(u,"resolve_action",{action:g?"approve":"reject",button:b,...Number.isFinite(f)&&{buttonIndex:f},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(k=>console.error("[SW Action] approval failed:",k))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,s])}const Ch="adhdev_dashboardLayout_v1",Th="adhdev_dashboardDockview_v1",Mh="adhdev_dashboardDockviewHiddenRestore_v1",Us={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function lo(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function Ah(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function ul(e){return`${Ch}:${e}`}function Ih(e){const s=ul(e);return lo(s,null)}function Rh(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=ul(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function ml(e){return`${Th}:${e}`}function Lh(e){const s=ml(e);return lo(s,null)}function _h(e,s){try{const r=ml(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function fl(e){return`${Mh}:${e}`}function Ph(e){const s=fl(e);return lo(s,{})}function Dh(e,s){try{const r=fl(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Eh(){return{groupAssignments:[...Us.groupAssignments],focusedGroup:Us.focusedGroup,groupActiveTabIds:{...Us.groupActiveTabIds},groupTabOrders:{...Us.groupTabOrders},groupSizes:[...Us.groupSizes]}}function $h(e,s){return e?e.length===s.length&&e.every((r,n)=>r===s[n]):s.length===0}function Bh(){const[e]=o.useState(()=>Ah(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,d]=o.useState({}),[m,u]=o.useState([]),[f,b]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,g]=o.useState(!1),h=o.useCallback(()=>{if(S)return;const v=Ih(e)??Eh();r(new Map(v.groupAssignments)),a(v.focusedGroup),c(v.groupActiveTabIds),d(v.groupTabOrders),u(v.groupSizes),g(!0)},[S,e]);o.useEffect(()=>{S&&Rh(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:m})},[S,e,s,n,i,l,m]),o.useEffect(()=>{const v=window.matchMedia("(max-width: 767px)"),$=_=>b(_.matches);return v.addEventListener("change",$),()=>v.removeEventListener("change",$)},[]);const k=o.useCallback(v=>{r(v)},[]),p=o.useCallback(v=>{a(v)},[]),x=o.useCallback(v=>{c(v)},[]),y=o.useCallback(v=>{d(v)},[]),N=o.useCallback(v=>{u(v)},[]),j=o.useCallback(v=>{p(v)},[p]),I=o.useCallback((v,$)=>{c(_=>(_[v]??null)===($??null)?_:{..._,[v]:$})},[]),M=o.useCallback((v,$)=>{d(_=>{const T=_[v];return $h(T,$)?_:{..._,[v]:$}})},[]),w=o.useCallback((v,$)=>{const _=$.get(v)??0;return I(_,v),j(_),_},[j,I]);return{layoutProfile:e,groupAssignments:s,updateGroupAssignments:k,focusedGroup:n,updateFocusedGroup:p,focusGroup:j,groupActiveTabIds:i,updateGroupActiveTabIds:x,setGroupActiveTab:I,groupTabOrders:l,updateGroupTabOrders:y,setGroupTabOrder:M,groupSizes:m,updateGroupSizes:N,isMobile:f,hasHydratedStoredLayout:S,hydrateStoredLayout:h,focusConversationTab:w}}function Kh(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Ga(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Wh({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:f,handleRefreshHistory:b}){const S=o.useRef(!1),g=o.useRef(!1),h=o.useRef(null),k=o.useRef(!1);o.useEffect(()=>{if(!e||S.current||s.length===0)return;if(!a){i();return}const p=r(e);p&&(c(p.tabKey,n),S.current=!0,g.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),l(x=>{const y=new URLSearchParams(x);return y.delete("activeTab"),y},{replace:!0}))},[e,s,r,n,a,i,c,l]),o.useEffect(()=>{if(!(g.current||a)&&s.length!==0){if(!e){i(),g.current=!0;return}if(S.current){g.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(g.current||a)&&(i(),g.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!d){k.current=!1;return}if(!m||k.current||u)return;const p=f.find(x=>x.id===m.routeId);p&&(!p.chats||p.chats.length===0||Kh(p.chats,m))&&(k.current=!0,b())},[d,m,u,f,b])}function Wn(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=Ga(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function pl({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[d,m]=o.useState(!1),u=o.useCallback(async g=>{try{await e("standalone","launch_ide",{ideType:g,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),f=o.useCallback(async(g,h)=>{try{const k=g||(s==null?void 0:s.daemonId)||"",p=await e(k,"switch_chat",{id:h,sessionId:h,...ts(s)}),x=p==null?void 0:p.result;if((p==null?void 0:p.success)===!0||x==="switched"||x==="switched-by-title")return;x===!1||x==="not_found"?Os(a,"⚠️ Session tab not found — try refreshing history"):typeof x=="string"&&x.startsWith("error:")?Os(a,`⚠️ Switch error: ${x}`):Os(a,"⚠️ Session switch failed")}catch(k){console.error("Switch failed",k),Os(a,`❌ Switch failed: ${k.message||"connection error"}`)}},[s,e,a]),b=o.useCallback(async()=>{if(!(!s||c)){l(!0);try{const g=Rs(s);await e(g,"new_chat",{...ts(s)}),i(h=>({...h,[s.tabKey]:Date.now()}))}catch(g){console.error("New chat failed",g)}finally{l(!1)}}},[s,c,e,i]),S=o.useCallback(async()=>{var g,h;if(!(!s||d)){m(!0);try{const k=Rs(s),p=async()=>e(k,"list_chats",{forceExpand:!0,...ts(s)});let x=await p(),y=(x==null?void 0:x.chats)||((g=x==null?void 0:x.result)==null?void 0:g.chats);Wn(y,s)&&(await new Promise(N=>setTimeout(N,450)),x=await p(),y=(x==null?void 0:x.chats)||((h=x==null?void 0:x.result)==null?void 0:h.chats)),x!=null&&x.success&&Array.isArray(y)&&(n(s.routeId,y),Wn(y,s)&&!Wn(r,s)&&Os(a,"⚠️ History dialog did not fully open — try once more"))}catch(k){console.error("Refresh history failed",k)}finally{m(!1)}}},[s,r,d,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:f,handleNewChat:b,handleRefreshHistory:S}}function Oh(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 Fh(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function ai(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 Ar(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 d=a[l];typeof d=="number"&&d>0&&i.set(c,d)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function oi(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 Hh(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 Uh(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 ii(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 ci(e){return Array(e).fill(100/e)}function zh({groupAssignments:e,updateGroupAssignments:s,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:d,visibleTabKeys:m}){const u=o.useRef(null),f=o.useMemo(()=>Ar(e,m),[e,m]),b=f.assignments,S=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),g=S>1,h=o.useCallback((j,I)=>{s(M=>{const w=new Map(Ar(M,m).assignments);return I===0?w.delete(j):w.set(j,I),w}),n(M=>({...M,[I]:j})),r(I)},[s,m,n,r]),k=o.useCallback(j=>{s(I=>{const M=Ar(I,m).assignments,w=new Map;for(const[v,$]of M)$!==j&&($>j?w.set(v,$-1):w.set(v,$));return w}),c(I=>{if(I.length<=1)return[];const M=[...I];M.splice(j,1);const w=M.reduce((v,$)=>v+$,0);return w>0?M.map(v=>v/w*100):[]}),r(0)},[s,m,c,r]),p=o.useCallback((j,I)=>{I.preventDefault();const M=u.current;if(!M)return;const w=I.clientX,v=M.offsetWidth,$=i.length===S?[...i]:ci(S),_=F=>{const L=(F.clientX-w)/v*100,C=[...$];C[j]=Math.max(15,$[j]+L),C[j+1]=Math.max(15,$[j+1]-L),c(C)},T=()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",_),document.addEventListener("mouseup",T)},[i,S,c]),x=o.useCallback((j,I,M)=>{if(S>=4)return;const w=M==="left"?I:I+1;s(v=>{const $=Ar(v,m).assignments,_=new Map;for(const T of d){const F=$.get(T.tabKey)??0,B=F>=w?F+1:F;B>0&&_.set(T.tabKey,B)}return w>0&&_.set(j,w),_}),c(v=>{const $=v.length===S?[...v]:ci(S),_=$[I]??100/S,T=Math.max(15,_/2),F=Math.max(15,_/2),B=[...$];B[I]=T,B.splice(w,0,F);const L=B.reduce((C,A)=>C+A,0);return B.map(C=>C/L*100)}),n(v=>{const $=ii(v,w);return $[w]=j,$}),a(v=>{const $=ii(v,w);return $[w]=[j],$}),r(w)},[S,s,m,d,c,n,a,r]);o.useEffect(()=>{Oh(e,b)||s(b)},[e,b,s]),o.useEffect(()=>{const{mapping:j,usedGroups:I}=f;n(M=>{const w=oi(M,j);return ai(M,w)?M:w}),a(M=>{const w=oi(M,j);return ai(M,w)?M:w}),r(M=>{const w=l?0:Hh(M,I,j);return M===w?M:w}),c(M=>{const w=l?[]:Uh(M,I,f.groupCount);return Fh(M,w)?M:w})},[f,l,n,a,r,c]);const y=o.useMemo(()=>{const j=Array.from({length:S},()=>[]);for(const I of d){const M=b.get(I.tabKey)??0,w=Math.min(M,S-1);j[w].push(I)}return j},[d,b,S]),N=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:u,normalizedGroupAssignments:b,numGroups:S,isSplitMode:g,groupedConvs:y,moveTabToGroup:h,closeGroup:k,handleResizeStart:p,splitTabRelative:x,clearAllSplits:N}}function Vh({ides:e,sendDaemonCommand:s}){const r="0.9.70",n=o.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:Zc(u,r)).sort((u,f)=>Number(er(f,r))-Number(er(u,r))),[r,e]),a=o.useMemo(()=>n.some(u=>er(u,r)),[r,n]),[i,c]=o.useState(!1),[l,d]=o.useState({}),m=o.useCallback(async u=>{var f,b;d(S=>({...S,[u]:"upgrading"}));try{const S=await s(u,"daemon_upgrade",{});(f=S==null?void 0:S.result)!=null&&f.upgraded||(b=S==null?void 0:S.result)!=null&&b.success?d(g=>({...g,[u]:"done"})):d(g=>({...g,[u]:"error"}))}catch{d(S=>({...S,[u]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:m}}const hl=80;function Wr(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Gh(e){return{...e,createdAt:Wr(e.createdAt),updatedAt:Wr(e.updatedAt,e.createdAt),lastEventAt:Wr(e.lastEventAt,e.updatedAt||e.createdAt)}}function qh(e){const s=qa(e);return s==="unknown:"?e.id:s}function Yh(e){return[e.type,Sc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Xh(e,s=hl){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=qh(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 Jh(e,s){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?s.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=un(a,s),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const d=Wr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),m=Yh({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(Gh({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:hc(a),preview:Km(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return Xh(n)}function Qh(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Zh(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=hl}=e,a=o.useMemo(()=>Jh(s,r).slice(0,Math.max(0,n)),[s,r,n]),i=o.useMemo(()=>Qh(a),[a]);return{notifications:a,unreadCount:i}}function ex({notifications:e,sendDaemonCommand:s}){const r=o.useCallback(i=>{const c=e.find(d=>d.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&s(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,s]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&s(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,s]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&s(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,s]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const tx=o.createContext(null);function sx(){return o.useContext(tx)}function hn(...e){const s=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();s.has(c)||(s.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function rx(e){const s=e.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function xn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=rx(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 nx(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 ax(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function bn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=ax(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=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${c}${u}`:`${m.replace(/[\\/]+$/,"")}${c}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:l(i,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:i,directories:d}}function ox(e,s){const r={meshId:s.meshId||"",workspace:s.workspace||"",serverName:s.serverName||"adhdev-mesh",adhdevMcpCommand:s.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function xl(e,s={}){const r=e==null?void 0:e.mcpConfig;return(r==null?void 0:r.mode)!=="manual"?null:{serverName:r.serverName||"adhdev-mesh",configFormat:r.format,configPathCommand:r.configPathCommand,requiresRestart:r.requiresRestart===!0,instructions:r.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:ox(r.template||"",{...s,serverName:r.serverName||"adhdev-mesh"})}}function bl(e){if(!e||typeof e!="object")return null;const s=e,r=typeof s.instructions=="string"?s.instructions:"",n=typeof s.template=="string"?s.template:"";return!r&&!n?null:{serverName:typeof s.serverName=="string"?s.serverName:void 0,configFormat:typeof s.configFormat=="string"?s.configFormat:void 0,configPathCommand:typeof s.configPathCommand=="string"?s.configPathCommand:void 0,requiresRestart:s.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function ix(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function li(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function di(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function cx({ides:e,conversations:s,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=li(n.workspacePath),l=e.find(m=>{var g,h,k,p;if(!m||m.type==="adhdev-daemon"||ix(m.daemonId||m.id)!==n.machineId||(or(m)?"cli":Ss(m)?"acp":"ide")!==n.kind||String(m.agentType||m.type||"")!==n.providerType)return!1;if(n.resumeSessionId)return String(m.providerSessionId||"")===n.resumeSessionId;if(c){const x=li(m.workspace||m.runtimeWorkspaceLabel);return x?x===c:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((p=(k=(h=(g=m.activeChat)==null?void 0:g.messages)==null?void 0:h.at)==null?void 0:k.call(h,-1))==null?void 0:p.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const d=Tc({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:s});d&&(a(null),r(d))},[s,e,r,n]),o.useEffect(()=>{if(!n)return;const c=window.setTimeout(()=>{a(l=>!l||l.startedAt!==n.startedAt?l:null)},45e3);return()=>window.clearTimeout(c)},[n]),{trackPendingLaunch:i}}function lx({sendDaemonCommand:e,trackPendingLaunch:s,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=sx(),l=o.useCallback(async(h,k)=>bn(e,h,k),[e]),d=o.useCallback(async(h,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const p=await e(h,"workspace_add",{path:k.trim()});return p!=null&&p.success?{ok:!0}:{ok:!1,error:(p==null?void 0:p.error)||"Could not save workspace"}}catch(p){return{ok:!1,error:p instanceof Error?p.message:"Could not save workspace"}}},[e]),m=o.useCallback(async(h,k,p)=>{var x;try{const y={ideType:k,enableCdp:!0};(x=p==null?void 0:p.workspacePath)!=null&&x.trim()&&(y.workspace=p.workspacePath.trim());const N=await e(h,"launch_ide",y);return!(N!=null&&N.success)&&(N==null?void 0:N.success)!==void 0?{ok:!1,error:(N==null?void 0:N.error)||"Could not launch IDE"}:(s({machineId:h,kind:"ide",providerType:k,workspacePath:(p==null?void 0:p.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not launch IDE"}}},[e,s]),u=o.useCallback(async(h,k,p,x)=>{var N,j,I;const y=Date.now();try{const M={cliType:p};(N=x==null?void 0:x.workspacePath)!=null&&N.trim()?M.dir=x.workspacePath.trim():x!=null&&x.workspaceId&&(M.workspaceId=x.workspaceId),(j=x==null?void 0:x.resumeSessionId)!=null&&j.trim()&&(M.resumeSessionId=x.resumeSessionId.trim()),Array.isArray(x==null?void 0:x.cliArgs)&&x.cliArgs.length>0&&(M.cliArgs=x.cliArgs),(I=x==null?void 0:x.initialModel)!=null&&I.trim()&&(M.initialModel=x.initialModel.trim());const w=await e(h,"launch_cli",M),v=(w==null?void 0:w.result)||w,$=(v==null?void 0:v.sessionId)||(v==null?void 0:v.id);return w!=null&&w.success&&$?(r($),{ok:!0}):w!=null&&w.success?(s({machineId:h,kind:k,providerType:p,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:y}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(v==null?void 0:v.error)||`Could not launch ${k.toUpperCase()} session`}}catch(M){return di(M)?(s({machineId:h,kind:k,providerType:p,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:y}),{ok:!0}):{ok:!1,error:M instanceof Error?M.message:`Could not launch ${k.toUpperCase()} session`}}},[r,e,s]),f=o.useCallback(async h=>{var k;if(c!=null&&c.listMeshes)return c.listMeshes(h);if(!h)return[];try{const p=await e(h,"list_meshes",{}),x=(p==null?void 0:p.result)??p;if((x==null?void 0:x.success)===!1)throw new Error((x==null?void 0:x.error)||"Could not load meshes");return(Array.isArray(x==null?void 0:x.meshes)?x.meshes:Array.isArray((k=x==null?void 0:x.result)==null?void 0:k.meshes)?x.result.meshes:[]).map(N=>{var j;return{id:String((N==null?void 0:N.id)||""),name:String((N==null?void 0:N.name)||(N==null?void 0:N.id)||"Untitled mesh"),repoIdentity:(N==null?void 0:N.repoIdentity)||(N==null?void 0:N.repo_identity)||null,workspace:Array.isArray(N==null?void 0:N.nodes)&&N.nodes.length>0?String(((j=N.nodes[0])==null?void 0:j.workspace)||""):null,nodesCount:Array.isArray(N==null?void 0:N.nodes)?N.nodes.length:void 0,status:(N==null?void 0:N.status)||null}}).filter(N=>N.id)}catch(p){throw console.error("List meshes failed",p),p}},[c,e]),b=o.useCallback(async(h,k,p)=>{if(!k.trim())return{ok:!1,error:"Choose a mesh first."};if(c!=null&&c.launchMeshCoordinator)return c.launchMeshCoordinator(h,k,p);const x=Date.now();try{const y=await e(h,"launch_mesh_coordinator",{meshId:k.trim(),cliType:p.trim()||"claude-cli"}),N=(y==null?void 0:y.result)??y;if((N==null?void 0:N.success)===!1||(y==null?void 0:y.success)===!1){const I=String((N==null?void 0:N.code)||(y==null?void 0:y.code)||""),M=bl((N==null?void 0:N.meshCoordinatorSetup)||(N==null?void 0:N.manualSetup)||(y==null?void 0:y.meshCoordinatorSetup)||(y==null?void 0:y.manualSetup));return{ok:!1,error:(N==null?void 0:N.error)||(y==null?void 0:y.error)||"Could not launch mesh coordinator",code:I||void 0,manualSetup:M}}const j=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);return j?r(j):s({machineId:h,kind:"cli",providerType:p,workspacePath:(N==null?void 0:N.workspace)||null,startedAt:x}),{ok:!0}}catch(y){return di(y)?(s({machineId:h,kind:"cli",providerType:p,startedAt:x}),{ok:!0}):{ok:!1,error:y instanceof Error?y.message:"Could not launch mesh coordinator"}}},[c,r,e,s]),S=o.useCallback(async(h,k)=>{if(!h||!k)return[];try{const p=await e(h,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),x=(p==null?void 0:p.result)??p;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(p){return console.error("List saved sessions failed",p),[]}},[e]),g=o.useCallback(async h=>{await ll({conversation:n,mode:h,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:l,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:f,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:S,setActiveCliViewMode:g}}function dx(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function ux(e,s,r=Date.now()){return!e||!dx(s)?null:{tabKey:e,nonce:r}}function mx({isMobile:e,conversations:s,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,d]=o.useState(null),[m,u]=o.useState(null),f=o.useMemo(()=>{var k,p;if(!e){if(l){const x=s.find(y=>y.tabKey===l);if(x)return x}return r[0]}const h=n[a];if(h){const x=s.find(y=>y.tabKey===h);if(x)return x}return((k=i[a])==null?void 0:k[0])||((p=i[0])==null?void 0:p[0])},[s,l,a,n,i,e,r]),b=o.useCallback(h=>{d(h)},[]),S=o.useCallback(h=>{d(h.tabKey),c(k=>{const p=new URLSearchParams(k),x=Om(h);return x?p.set("activeTab",x):p.delete("activeTab"),p},{replace:!0})},[c]),g=o.useCallback((h,k)=>{const p=ux(h,k);p&&u(p)},[]);return{activeConv:f,openDesktopConversation:S,requestScrollToBottom:g,scrollToBottomRequest:m,setDesktopActiveTab:b}}function fx(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 px(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,completionMarker:s,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function hx({activeConv:e,isMobile:s,liveSessionInboxState:r,sendDaemonCommand:n}){const a=o.useRef(null),i=o.useRef(null),c=o.useRef(null),l=o.useRef(null),d=o.useRef(null);o.useEffect(()=>{const m=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),i.current=null};if(s){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=Yr(e,r),f=px({tabKey:e.tabKey,historySessionId:ur(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ss(e),liveState:u}),b=f.autoReadKey,S=fx({autoReadKey:b,shouldMarkSeen:f.shouldMarkSeen,completedKey:a.current,pendingKey:i.current});if(!f.shouldMarkSeen){S.shouldCancelPending&&m(),a.current=b;return}if(!S.shouldSchedule)return;S.shouldCancelPending&&m();const g=()=>{if(document.visibilityState!=="visible"||a.current===b)return;a.current=b,i.current=null,c.current=null,l.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const k=f.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:k,completionMarker:f.completionMarker}).catch(()=>{})};if(i.current=S.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(g,1500);const k=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};d.current=k,document.addEventListener("visibilitychange",k);return}const h=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(g,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,s,r,n]),o.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function On(e){if(!e)return"";const s=String(e.workspacePath||"").trim();if(s)return s;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function xx({activeConv:e,remoteDialogConv:s,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:d}){var A;const[m,u]=o.useState(!1),[f,b]=o.useState([]),[S,g]=o.useState(()=>gt()),[h,k]=o.useState(!1),[p,x]=o.useState(null),y=o.useRef(null),N=o.useMemo(()=>r||s||e,[e,r,s]),j=!!N&&st(N)&&!Qe(N),I=o.useMemo(()=>{if(!N||!j)return null;const K=N.daemonId||N.routeId||"",P=Bt(N),D=On(N);return`${K}:${P}:${N.providerSessionId||""}:${D}`},[N,j]),M=o.useMemo(()=>!N||!j?"":On(N),[N,j]),{isCreatingChat:w,isRefreshingHistory:v,handleSwitchSession:$,handleNewChat:_,handleRefreshHistory:T}=pl({sendDaemonCommand:a,activeConv:N,chats:(A=n.find(K=>K.id===(N==null?void 0:N.routeId)))==null?void 0:A.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),F=o.useCallback(()=>{u(!0)},[]),B=o.useCallback(()=>{u(!1)},[]),L=o.useCallback(async()=>{if(!(!N||!j||h)){k(!0);try{const K=N.daemonId||N.routeId,P=Bt(N),D=On(N),H=await a(K,"list_saved_sessions",{agentType:P,providerType:P,kind:"cli",limit:50,...N.providerSessionId?{providerSessionId:N.providerSessionId}:{},...D?{workspace:D}:{}}),Q=(H==null?void 0:H.result)??H;b(Array.isArray(Q==null?void 0:Q.sessions)?Q.sessions:[])}catch(K){console.error("Refresh saved sessions failed",K),b([])}finally{k(!1)}}},[N,h,j,a]);o.useEffect(()=>{if(!m){y.current=null;return}if(!j){y.current=null,b([]),k(!1);return}!I||h||y.current!==I&&(y.current=I,L())},[L,m,h,j,I]);const C=o.useCallback(async K=>{if(!N||!j||!K.providerSessionId||!K.workspace)return;const P=N.daemonId||N.routeId,D=Bt(N);try{x(K.providerSessionId);const H=await a(P,"launch_cli",{cliType:D,dir:K.workspace,resumeSessionId:K.providerSessionId,initialModel:cc(K.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Q=(H==null?void 0:H.result)??H,be=typeof(Q==null?void 0:Q.sessionId)=="string"?Q.sessionId:typeof(Q==null?void 0:Q.id)=="string"?Q.id:"";be&&d(de=>{const te=new URLSearchParams(de);return te.set("activeTab",be),te},{replace:!0}),B()}catch(H){console.error("Resume saved session failed",H)}finally{x(null)}},[B,N,j,a,d]);return{historyModalOpen:m,openHistoryModal:F,closeHistoryModal:B,historyTargetConv:N,isSavedSessionHistoryTarget:j,isHistoryCreatingChat:w,isHistoryRefreshingHistory:v,handleHistorySwitchSession:$,handleHistoryNewChat:_,handleHistoryRefresh:T,savedHistorySessions:f,savedHistoryFilters:S,setSavedHistoryFilters:g,missingWorkspaceResumePath:M,isSavedHistoryLoading:h,resumingSavedHistorySessionId:p,handleRefreshSavedHistory:L,handleResumeSavedHistorySession:C}}function bx({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[d,m]=o.useState(null),[u,f]=o.useState(null),b=o.useMemo(()=>{if(e||!n)return null;const p=l(n);return p&&!st(p)&&!Qe(p)?p:null},[e,n,l]),S=o.useMemo(()=>{const p=d==null?void 0:d.routeId;if(!p)return null;const x=d!=null&&d.tabKey?i.find(y=>y.tabKey===d.tabKey):a?i.find(y=>y.tabKey===a):null;return(x==null?void 0:x.routeId)===p?x:Pt(i,p)},[i,d,a]),g=o.useMemo(()=>{if(S)return c.find(p=>p.id===S.routeId)},[c,S]);o.useEffect(()=>{b&&(m({routeId:b.routeId,tabKey:Bo(b)}),f(b),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,b]);const h=o.useCallback(p=>{p&&(m({routeId:p.routeId,tabKey:Bo(p)}),f(p))},[]),k=o.useCallback(()=>{m(null),f(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:g,remoteDialogActiveConv:u,setRemoteDialogActiveConv:f,openRemoteDialog:h,closeRemoteDialog:k}}function gx({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:b,setRemoteDialogActiveConv:S,openRemoteDialog:g,closeRemoteDialog:h}=bx({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[k,p]=o.useState(!1),[x,y]=o.useState(null),N=o.useCallback(async M=>{const w=M||d;!w||!st(w)&&!Qe(w)||(y(w),p(!0))},[d]),j=o.useCallback(()=>{p(!1),y(null)},[]),I=o.useCallback(async M=>{const w=x||d;if(!w||!st(w)&&!Qe(w)){j();return}p(!1);try{const v=Bt(w),$=w.routeId||w.daemonId||"";await m($,"stop_cli",{cliType:v,targetSessionId:w.sessionId,mode:M})}catch(v){console.error("Stop CLI failed:",v)}finally{y(null)}},[d,j,x,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:b,setRemoteDialogActiveConv:S,openRemoteDialog:g,closeRemoteDialog:h,cliStopDialogOpen:k,cliStopTargetConv:x,requestCliStop:N,cancelCliStop:j,confirmCliStop:I}}function Fn(e,s=!0){return(e??!0)&&s}const uo=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:f,isFocusingAgent:b,actionLogs:S,userName:g,scrollToBottomRequestNonce:h,isInputActive:k=!0,isVisible:p=!0}){const x=n,y=!n,N=Fn(p,x),j=Fn(p,y),I=Fn(p),M=nl(s),w=M.status||M.modalMessage||M.modalButtons?{...s,...M.status?{status:M.status}:{},...M.modalMessage!==void 0?{modalMessage:M.modalMessage}:{},...M.modalButtons!==void 0?{modalButtons:M.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(nc,{activeConv:w,onModalButton:c}),w.transport!=="pty"&&w.transport!=="acp"&&w.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(ar,{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,w.transport==="pty"?t.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[t.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:x?"visible":"hidden",pointerEvents:x?"auto":"none"},children:t.jsx(ep,{activeConv:w,clearToken:r,terminalRef:i,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:N,isInputActive:k&&N})}),t.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:y?"visible":"hidden",pointerEvents:y?"auto":"none"},children:t.jsx(ja,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:b,actionLogs:S,userName:g,scrollToBottomRequestNonce:h,isInputActive:k&&j,isVisible:j})})]}):t.jsx(ja,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:b,actionLogs:S,userName:g,scrollToBottomRequestNonce:h,isInputActive:k&&I,isVisible:I})]})},(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&&e.isVisible===s.isVisible);function yx({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:f,onOpenHistory:b,onOpenRemote:S,onStopCli:g,cliViewMode:h,onSetCliViewMode:k,handleSendChat:p,handleFocusAgent:x,handleModalButton:y,handleRelaunch:N}){const j=o.useRef(null),I=st(e)&&!s,M=I&&h==="terminal",w=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 ${w} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:t.jsx(Pa,{size:18})}),t.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ct(e)}),t.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:t.jsx(Mc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>f(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[I&&h&&t.jsx(Ja,{mode:h,onChange:k,compact:!0}),I&&g&&t.jsx("button",{onClick:()=>{g(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(vt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",children:t.jsx(Da,{size:14})}),!s&&!I&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",children:t.jsx(Tt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(uo,{activeConv:e,clearToken:0,isCliTerminal:M,ideEntry:n,terminalRef:j,handleModalButton:y,handleRelaunch:N,handleSendChat:p,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:x,isFocusingAgent:d,actionLogs:a,userName:i})})]})}const Hn={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 vx(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function gl(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(vx())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Hn[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:Hn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Hn[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 yl({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:Ht}];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 Ir({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 ys({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 zs({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 wx({conversation:e,onCancel:s,onConfirm:r}){const n=ct(e),a=fs(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",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:s}),t.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,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] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),t.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:s,"aria-label":"Cancel hide chat",children:t.jsx(vt,{size:16})})]}),t.jsx("div",{className:"px-4 py-4",children:t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[t.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),t.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[t.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function Rr({item:e,type:s,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onCollectChatDebugBundle:i}){const c=s==="needs_attention"||s==="task_complete",l=s==="working",d=s==="earlier",m=s==="task_complete",{isReconnecting:u,isConnecting:f}=Es(e.conversation),b=ct(e.conversation),S=fs(e.conversation),g=Bc(e.conversation,{requiresAction:s==="needs_attention"}),h=c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":l?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",k=c?"bg-accent-primary shadow-glow":l?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":d?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",p=d?"text-text-secondary":"text-text-primary",x=d?"text-text-muted":"text-text-secondary",y=d?"text-text-secondary opacity-80":"text-text-muted",N=d?"text-text-muted opacity-80":"text-text-muted",j=!l&&!m,I="text-[color:var(--status-warning)]",M=w=>{if(!i)return;w.preventDefault(),w.stopPropagation();const v=i==null?void 0:i(e.conversation);Promise.resolve(v).catch($=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",$)})};return t.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${h}`,children:t.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[c||l?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.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${k}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(b)}),a&&t.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:w=>{w.preventDefault(),w.stopPropagation(),a()},"aria-label":`Hide ${b}`,title:"Hide conversation",children:[t.jsx(Ea,{size:11}),t.jsx("span",{children:"Hide"})]})]}),t.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:M,type:"button",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${p}`,children:b}),j&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${N}`,children:rc(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${x}`,children:[t.jsx("span",{className:"truncate",children:S}),t.jsx(Ls,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${I} 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…"})]}):g==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:I,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:e.preview})]}),c&&!m&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),m&&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"}),l&&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 ui({size:e=32}){return t.jsx("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}})})}function jx({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:f,onHideConversation:b,onOpenNewSession:S,onOpenMachine:g,onOpenSettings:h,onSectionChange:k,wsStatus:p="connected",isStandalone:x=!1,onCollectChatDebugBundle:y}){const[N,j]=o.useState(null),I=p==="disconnected"||p==="reconnecting"||p==="offline"||p==="auth_failed",M=c.length>0,w=s.length>0||r.length>0||n.length>0||a.length>0,v=e==="machines"?"Machines":"Chats",$=x?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",_=x?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",T=o.useCallback(async L=>{const C=Rs(L);if(!C)return;const A=Array.isArray(L.messages)?L.messages:[],K=vc({activeConv:L,visibleMessages:A,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:A.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),P=await m(C,"get_chat_debug_bundle",{...ts(L),delivery:"daemon_file",frontendSnapshot:K}),D=Qr(P),H=kc(D),Q=await jc(H);Q==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),nt.showToast(wc(D,{locatorCopyStatus:Q}),Q==="failed"?"warning":"success")},[d,m]),F=y||T,B=o.useCallback(()=>{N&&(b==null||b(N),j(null))},[N,b]);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 ${$}`,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:v}),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(ln,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:h,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(on,{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] ${_}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:I?t.jsx(zs,{icon:t.jsx(ui,{}),title:p==="offline"?"Network offline":p==="auth_failed"?"Session expired":"Reconnecting",subtitle:p==="offline"?"Waiting for network…":p==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?t.jsx(zs,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:x?"Waiting for your daemon":"Connect your machines",subtitle:x?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!x&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(gl,{})})}):t.jsx(ys,{children:c.map((L,C)=>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] ${C>0?"border-t border-border-subtle/70":""}`,onClick:()=>g(L.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(L.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:L.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:L.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[L.unread," new"]}):L.total>0?`${L.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:L.subtitle}),L.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[L.total," chat",L.total!==1?"s":"",L.unread>0?` · ${L.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},L.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(Ir,{title:"Needs attention",className:"mb-0"}),t.jsx(ys,{children:s.map((L,C)=>t.jsx("div",{className:C>0?"border-t border-border-subtle/70":"",children:t.jsx(Rr,{item:L,type:"needs_attention",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>j(L.conversation):void 0,onCollectChatDebugBundle:F})},L.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(Ir,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(ys,{children:r.map((L,C)=>t.jsx("div",{className:C>0?"border-t border-border-subtle/70":"",children:t.jsx(Rr,{item:L,type:"task_complete",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>j(L.conversation):void 0,onCollectChatDebugBundle:F})},L.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(Ir,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(ys,{children:n.map((L,C)=>t.jsx("div",{className:C>0?"border-t border-border-subtle/70":"",children:t.jsx(Rr,{item:L,type:"working",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>j(L.conversation):void 0,onCollectChatDebugBundle:F})},L.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(Ir,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(ys,{children:a.map((L,C)=>t.jsx("div",{className:C>0?"border-t border-border-subtle/70":"",children:t.jsx(Rr,{item:L,type:"earlier",getAvatarText:l,onOpenConversation:u,onRequestHideConversation:b?()=>j(L.conversation):void 0,onCollectChatDebugBundle:F})},L.conversation.tabKey))}):w?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):I?t.jsx(zs,{icon:t.jsx(ui,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):M?t.jsx(zs,{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(Ht,{size:20})}),title:"No conversations yet",subtitle:Oc,children:S&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:S,"aria-label":Et,title:Et,children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),t.jsx("span",{children:Et})]})}):t.jsx(zs,{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.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:t.jsx(ys,{className:"mt-4 border-dashed bg-bg-secondary/20",children:t.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),t.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[i.length," collapsed ",i.length===1?"conversation":"conversations"]})]}),t.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:f,children:"Restore all"})]})})})]}),e==="chats"&&S&&w&&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:S,"aria-label":Et,title:Et,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"})]})}),N&&t.jsx(wx,{conversation:N,onCancel:()=>j(null),onConfirm:B}),t.jsx(yl,{section:e,onSectionChange:k})]})}function kx(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 vl(e){const s=[e.workspace||"Workspace unknown"],r=ms(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=kx(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function gn({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:d,onConfirm:m}){const[u,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const b=nx(r),S=u.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(vt,{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:()=>{!b||a||d(b)},disabled:!b||a,children:[t.jsx(Pa,{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:u,onChange:g=>f(g.target.value),onKeyDown:g=>{g.key!=="Enter"||!S||a||(g.preventDefault(),d(S))},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:()=>{!S||a||d(S)},disabled:!S||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(g=>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:()=>d(g.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(us,{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:g.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:g.path})]})]},g.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(S||r),disabled:!S&&!r||a,children:c})]})]})})}function mo({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:f,showModelInput:b,modelValue:S,onModelChange:g,historyProviderNode:h,onConfirm:k,onCancel:p}){const x=n==null?void 0:n.find(y=>y.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:p,"aria-label":"Close launch confirmation",children:t.jsx(vt,{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:y=>i(y.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:n.map(y=>t.jsx("option",{value:y.key,children:y.label},y.key))}),(x==null?void 0:x.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:x.description})]}),h,r.map(y=>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:y.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:y.value})]},`${y.label}:${y.value}`)),b&&g&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:S||"",onChange:y=>g(y.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:d})]}),m&&f&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:u||"",onChange:y=>f(y.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:d})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:p,disabled:d,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:k,disabled:d,children:[t.jsx(cn,{size:14}),d?l:c]})]})]})})}function mi(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function cs(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 d of s.workspaces||[])i.push({key:`saved:${d.id}`,label:`${d.id===s.defaultWorkspaceId?"⭐ ":""}${mi(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(d=>d.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:mi(c),description:c,workspaceId:null,workspacePath:c}),n){const d=`saved:${n}`;if(i.some(m=>m.key===d))return{options:i,selectedKey:d}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Sx(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Nx(e){return[Sx(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Cx(e){return e.lastLaunchedAt?dn(e.lastLaunchedAt):""}function wl(e){return{metaText:Nx(e),updatedLabel:Cx(e)}}function Un(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function Tx({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var et,ut,ft,pt;const c=mr(),[l,d]=o.useState(!1),m=(((et=e.detectedIdes)==null?void 0:et.length)||0)>0,u=o.useMemo(()=>(e.workspaces||[]).map(Ne=>({id:Ne.id,path:Ne.path,label:Ne.label})),[e]),f=e.defaultWorkspaceId||null,[b,S]=o.useState(f||((ut=u[0])==null?void 0:ut.id)||""),[g,h]=o.useState(""),[k,p]=o.useState(""),[x,y]=o.useState([]),[N,j]=o.useState(!1),[I,M]=o.useState(""),[w,v]=o.useState(!1),[$,_]=o.useState(Un(m,s.length,r.length)),T=o.useRef(null),[F,B]=o.useState(null),L=o.useRef("__home__"),[C,A]=o.useState("__home__"),[K,P]=o.useState(""),[D,H]=o.useState(""),[Q,be]=o.useState(""),[de,te]=o.useState([]),[Z,ce]=o.useState(()=>gt().textQuery),[fe,J]=o.useState(()=>gt().workspaceQuery),[me,ve]=o.useState(()=>gt().modelQuery),[ae,pe]=o.useState(()=>gt().resumableOnly),[je,xe]=o.useState(()=>gt().sortMode),[ge,oe]=o.useState(!1),[le,ie]=o.useState(!1),Y=o.useRef(null),G=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const ue=b==="__custom__"?g.trim():((ft=u.find(Ne=>Ne.id===b))==null?void 0:ft.path)||"",ke=b==="__custom__"&&!!ue&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),se=b!=="__custom__"&&((pt=u.find(Ne=>Ne.id===b))==null?void 0:pt.path)||"",Re=o.useMemo(()=>(e.recentLaunches||[]).map(Ne=>Ne.workspace),[e]),$e=o.useCallback(async Ne=>{j(!0),M("");try{const Ue=await a(Ne);p(Ue.path),h(Ue.path),y(Ue.directories)}catch(Ue){M(Ue instanceof Error?Ue.message:"Could not load folder")}finally{j(!1)}},[a]),Oe=o.useCallback(()=>{var Ue;S("__custom__"),v(!0);const Ne=xn(e.platform,hn(g.trim(),se,Re,e.defaultWorkspacePath,(Ue=u.find(Xe=>Xe.id===f))==null?void 0:Ue.path,u.map(Xe=>Xe.path)));$e(Ne)},[g,f,$e,Re,se,e.platform,u]),He=o.useCallback(Ne=>{if(Ne!=null&&Ne.workspaceId){S(Ne.workspaceId),h("");return}if(Ne!=null&&Ne.workspacePath){S("__custom__"),h(Ne.workspacePath);return}S(""),h("")},[]),W=o.useCallback(Ne=>{if(S(Ne),Ne==="__custom__"){Oe();return}h("")},[Oe]),Ce=o.useCallback(Ne=>{S("__custom__"),h(Ne)},[]),Te=o.useCallback((Ne,Ue)=>{T.current=Ue,L.current=Ne.selectedWorkspaceKey||"__home__",A(Ne.selectedWorkspaceKey||"__home__"),P(Ne.initialArgs||""),H(Ne.initialModel||""),be(""),te([]);const Xe=Ne.providerType?`${e.id}:${Ne.providerType}`:null;if(up(G.current,Xe)){const Ve=gt();ce(Ve.textQuery),J(Ve.workspaceQuery),ve(Ve.modelQuery),pe(Ve.resumableOnly),xe(Ve.sortMode)}G.current=Xe,B(Ne),Ne.providerType&&i&&(oe(!0),i(Ne.providerType).then(Ve=>te(Ve||[])).catch(Ve=>console.warn("Failed to load saved sessions",Ve)).finally(()=>oe(!1)))},[i,e.id]),Le=o.useMemo(()=>Fc(de,{textQuery:Z,workspaceQuery:fe,modelQuery:me,resumableOnly:ae,sortMode:je}),[me,ae,de,je,Z,fe]);o.useEffect(()=>{Q&&(Le.some(Ne=>Ne.providerSessionId===Q)||be(""))},[Le,Q]);const Be=o.useCallback(()=>{T.current&&(ie(!0),T.current().finally(()=>{T.current=null,ie(!1),B(null)}))},[]),Fe=o.useCallback(()=>{T.current=null,B(null)},[]),Ye=o.useCallback(Ne=>{L.current=Ne,A(Ne)},[]);return o.useEffect(()=>{var Ne;Y.current!==e.id&&(Y.current=e.id,S(f||((Ne=u[0])==null?void 0:Ne.id)||"__custom__"),h(""),p(""),y([]),M(""),v(!1),ce(gt().textQuery),J(gt().workspaceQuery),ve(gt().modelQuery),pe(gt().resumableOnly),xe(gt().sortMode),G.current=null,_(Un(m,s.length,r.length)))},[r.length,s.length,f,m,e.id,u]),o.useEffect(()=>{var Ne;b!=="__custom__"&&(b&&u.some(Ue=>Ue.id===b)||S(f||((Ne=u[0])==null?void 0:Ne.id)||"__custom__"))},[f,b,u]),o.useEffect(()=>{$==="ide"&&m||$==="cli"&&s.length>0||$==="acp"&&r.length>0||_(Un(m,s.length,r.length))},[$,r.length,s.length,m]),{showAllRecent:l,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:f,workspaceChoice:b,customWorkspacePath:g,browseCurrentPath:k,browseDirectories:x,browseBusy:N,browseError:I,browseDialogOpen:w,activeLauncherKind:$,launchConfirm:F,launchConfirmWorkspaceKeyRef:L,launchConfirmWorkspaceKey:C,launchConfirmArgs:K,launchConfirmModel:D,launchConfirmResumeId:Q,launchConfirmSavedSessions:de,launchConfirmTextFilter:Z,launchConfirmWorkspaceFilter:fe,launchConfirmModelFilter:me,launchConfirmResumableOnly:ae,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:Le,launchConfirmSessionsLoading:ge,launchConfirmBusy:le,resolvedWorkspacePath:ue,canCreateMissingWorkspace:ke,openBrowseDialog:Oe,loadBrowsePath:$e,handleWorkspaceChoiceChange:W,chooseCustomWorkspacePath:Ce,setCustomWorkspacePath:h,setBrowseDialogOpen:v,setActiveLauncherKind:_,openLaunchConfirm:Te,handleConfirmLaunch:Be,closeLaunchConfirm:Fe,setWorkspaceSelectionFromOption:He,setLaunchConfirmWorkspaceKeyAndSync:Ye,setLaunchConfirmArgs:P,setLaunchConfirmModel:H,setLaunchConfirmResumeId:be,setLaunchConfirmTextFilter:ce,setLaunchConfirmWorkspaceFilter:J,setLaunchConfirmModelFilter:ve,setLaunchConfirmResumableOnly:pe,setLaunchConfirmSortMode:xe}}function Mx({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:d,section:m,showBottomNav:u,onBack:f,onSectionChange:b,onOpenConversation:S,onOpenRecent:g,onOpenMachineDetails:h,onMachineUpgrade:k,onLaunchDetectedIde:p,onAddWorkspace:x,onBrowseDirectory:y,onLaunchWorkspaceProvider:N,onListSavedSessions:j}){const I=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",M=r.slice(0,4),w=s.slice(0,3),v=Tx({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:y,onListSavedSessions:j}),$=o.useMemo(()=>M.map(C=>{const{metaText:A,updatedLabel:K}=wl(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:A,updatedLabel:K,onClick:()=>{const{options:P,selectedKey:D}=cs({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspacePath:C.workspace});v.openLaunchConfirm({title:C.kind==="ide"?ns("restart-ide",C.label):C.providerSessionId?eo(C.label):ns("start-fresh",C.label),description:C.kind==="ide"?as("restart-ide"):C.providerSessionId?to():as("start-fresh"),confirmLabel:C.kind==="ide"?_s("restart-ide"):C.providerSessionId?en(!0):_s("start-fresh"),busyLabel:C.kind==="ide"?Ps("restart-ide"):C.providerSessionId?Qa(!0):Ps("start-fresh"),workspaceOptions:P,selectedWorkspaceKey:D,details:[{label:"Mode",value:I(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const H=P.find(Q=>Q.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption(H),await g({...C,workspace:(H==null?void 0:H.workspacePath)??null})})}}}),[v,g,M]),_=o.useMemo(()=>w.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:ct(C.conversation),secondary:Xf(C.conversation,{timestampLabel:C.timestamp?rc(C.timestamp):null}),unread:C.unread,onClick:()=>S(C.conversation)})),[S,w]),T=v.showAllRecent?$:$.slice(0,4),F=$.length>0,B=_.length>0,L=d?"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 ${L} 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(Pa,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Ct(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[B&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:_.map(C=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),F&&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:T.map(C=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:C.primary}),C.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),$.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>v.setShowAllRecent(C=>!C),children:v.showAllRecent?"Show fewer":`Show ${$.length-4} more`})})]}),(v.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:v.workspaceChoice,onChange:C=>v.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:v.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[v.workspaceRows.map(C=>t.jsxs("option",{value:C.id,children:[C.id===v.defaultWorkspaceId?"⭐ ":"",mn(C.path,C.label)||C.path]},C.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),v.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(us,{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:v.resolvedWorkspacePath||v.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:v.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:()=>{v.resolvedWorkspacePath&&x(v.resolvedWorkspacePath)},disabled:!v.resolvedWorkspacePath||v.browseBusy,children:"Save as workspace"})]})]}),v.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[v.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${v.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:()=>v.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${v.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:()=>v.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${v.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:()=>v.setActiveLauncherKind("acp"),children:"ACP"})]}),v.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:v.activeLauncherKind==="ide"?"Choose an IDE":v.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:v.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:A,selectedKey:K}=cs({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspaceId:v.workspaceChoice!=="__custom__"?v.workspaceChoice:null,currentWorkspacePath:v.resolvedWorkspacePath});v.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:A,selectedWorkspaceKey:K,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const P=A.find(D=>D.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption(P),p(C.type,{workspacePath:(P==null?void 0:P.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(v.activeLauncherKind==="cli"?n:a).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const A=v.activeLauncherKind==="cli"?"cli":"acp",{options:K,selectedKey:P}=cs({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspaceId:v.workspaceChoice!=="__custom__"?v.workspaceChoice:null,currentWorkspacePath:v.resolvedWorkspacePath});v.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${A.toUpperCase()}`,workspaceOptions:K,selectedWorkspaceKey:P,details:[{label:"Mode",value:A.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:A==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const D=K.find(H=>H.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption(D),N(A,C.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:v.launchConfirmArgs,model:v.launchConfirmModel,resumeSessionId:v.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,v.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:()=>x(v.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:k,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:h,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"})]})]})]})]}),v.browseDialogOpen&&t.jsx(gn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:v.browseCurrentPath,directories:v.browseDirectories,busy:v.browseBusy,error:v.browseError,confirmLabel:"Use this folder",onClose:()=>v.setBrowseDialogOpen(!1),onNavigate:C=>{v.loadBrowsePath(C)},onConfirm:C=>{v.chooseCustomWorkspacePath(C),v.setBrowseDialogOpen(!1)}}),v.launchConfirm&&t.jsx(mo,{title:v.launchConfirm.title,description:v.launchConfirm.description,details:v.launchConfirm.details,workspaceOptions:v.launchConfirm.workspaceOptions,selectedWorkspaceKey:v.launchConfirmWorkspaceKey,onWorkspaceChange:v.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:v.launchConfirm.providerType?en(!!v.launchConfirmResumeId):v.launchConfirm.confirmLabel,busyLabel:v.launchConfirm.providerType?void 0:v.launchConfirm.busyLabel,busy:v.launchConfirmBusy,showArgsInput:v.launchConfirm.showArgsInput,argsValue:v.launchConfirmArgs,onArgsChange:v.setLaunchConfirmArgs,showModelInput:v.launchConfirm.showModelInput,modelValue:v.launchConfirmModel,onModelChange:v.setLaunchConfirmModel,historyProviderNode:v.launchConfirm.providerType&&(v.launchConfirmSessionsLoading||v.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"}),v.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Za()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:v.launchConfirmTextFilter,onChange:C=>v.setLaunchConfirmTextFilter(C.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:v.launchConfirmWorkspaceFilter,onChange:C=>v.setLaunchConfirmWorkspaceFilter(C.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:v.launchConfirmModelFilter,onChange:C=>v.setLaunchConfirmModelFilter(C.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),t.jsxs("select",{value:v.launchConfirmSortMode,onChange:C=>v.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.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:v.launchConfirmResumableOnly,onChange:C=>v.setLaunchConfirmResumableOnly(C.target.checked),disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:v.launchConfirmResumeId,onChange:C=>v.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:pp()}),v.filteredLaunchConfirmSavedSessions.map(C=>t.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]}),!v.launchConfirmSessionsLoading&&v.launchConfirmSavedSessions.length>0&&v.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),v.launchConfirmResumeId&&(()=>{const C=v.filteredLaunchConfirmSavedSessions.find(K=>K.providerSessionId===v.launchConfirmResumeId);if(!C)return null;const A=vl(C);return t.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:A.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:A.providerSessionId}),t.jsx("div",{className:"mt-1",children:A.metaLine}),A.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:A.updatedLabel}),A.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:A.preview})]})})()]}),onConfirm:v.handleConfirmLaunch,onCancel:v.closeLaunchConfirm}),u&&t.jsx(yl,{section:m,onSectionChange:b})]})}function Or(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Ax(e,s=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=s.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:Or(e)}function Ix(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 Rx(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:ms(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,d,m,u;const a=or(n)?"cli":Ss(n)?"acp":"ide",i=ms(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(or(n)?n.cliName||n.type:Ss(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ss(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(m=(d=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:d.at)==null?void 0:m.call(d,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Lx(e,s){const r=new Map;for(const n of s){const a=bs(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((f,b)=>b.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ha(n),d=a.filter(f=>f.unread||f.requiresAction).length,m=Ix(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?Jf(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 _x(e){return e==="chat"}function Lr(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 Px({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:b,onRequestedMobileSectionConsumed:S,setSelectedTabKey:g,setScreen:h,setSelectedMachineId:k,setSection:p,setMachineBackTarget:x,resetMachineAction:y}){const N=o.useRef(null),j=o.useCallback(I=>{if(!(I!=null&&I.sessionId))return;const M=Yr(I,c),w=Math.max(Date.now(),ss(I),M.lastUpdated||0);Lr("mark_read:start",{tabKey:I.tabKey,sessionId:I.sessionId,displayPrimary:ct(I),inboxBucket:M.inboxBucket,unread:M.unread,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,activityAt:ss(I),readAt:w}),l(bs(I)||I.routeId,"mark_session_seen",{sessionId:I.sessionId,providerSessionId:I.providerSessionId,seenAt:w,completionMarker:M.completionMarker}).then(v=>{Lr("mark_read:result",{tabKey:I.tabKey,sessionId:I.sessionId,result:v})}).catch(v=>{Lr("mark_read:error",{tabKey:I.tabKey,sessionId:I.sessionId,error:v instanceof Error?v.message:String(v)})})},[c,l]);return o.useEffect(()=>{var M;if(!n){_x(i)&&h("inbox"),g(((M=e[0])==null?void 0:M.tabKey)||null),N.current=null;return}if(i!=="chat"){N.current=null;return}const I=`${n.tabKey}:${n.sessionId||""}`;N.current!==I&&(N.current=I,j(n))},[e,j,i,n,h,g]),o.useEffect(()=>{if(!d)return;const I=e.find(M=>M.tabKey===d);I&&(g(I.tabKey),h("chat"),m==null||m())},[e,m,d,h,g]),o.useEffect(()=>{if(!u)return;const I=s.find(M=>M.id===u);I&&(k(I.id),y(),p("machines"),x("inbox"),h("machine"),f==null||f())},[s,f,u,y,x,h,p,k]),o.useEffect(()=>{b&&(p(b),h("inbox"),S==null||S())},[S,b,h,p]),o.useEffect(()=>{const I=r.filter(M=>M.inboxBucket==="task_complete"||M.unread);I.length!==0&&Lr("inbox_state",{screen:i,selectedTabKey:a,items:I.map(M=>{const w=Yr(M.conversation,c);return{liveState:w,tabKey:M.conversation.tabKey,sessionId:M.conversation.sessionId,displayPrimary:ct(M.conversation),serverBucket:w.inboxBucket,computedBucket:M.inboxBucket,serverUnread:w.unread,computedUnread:M.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:ss(M.conversation)}})})},[r,c,i,a]),{markConversationRead:j}}function Dx(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 Ex(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function $x({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[d,m]=o.useState(null),u=o.useCallback(()=>{i("idle"),l(""),m(null)},[]),f=o.useCallback(async(x,y,N)=>{var j;try{i("loading"),l(`Launching ${y}…`);const I={ideType:y,enableCdp:!0};(j=N==null?void 0:N.workspacePath)!=null&&j.trim()&&(I.workspace=N.workspacePath.trim()),await e(x,"launch_ide",I),i("done"),l(`${y} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),b=o.useCallback(async(x,y,N)=>{if(y.trim())try{i("loading"),l(N!=null&&N.createIfMissing?"Creating folder…":"Saving workspace…");const j=await e(x,"workspace_add",{path:y.trim(),createIfMissing:(N==null?void 0:N.createIfMissing)===!0});if(j!=null&&j.success){i("done"),l(N!=null&&N.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]),S=o.useCallback(async x=>{var y,N,j,I,M,w;try{i("loading"),l("Starting daemon upgrade…");const v=await e(x,"daemon_upgrade",{});if((y=v==null?void 0:v.result)!=null&&y.alreadyLatest){i("done"),l(`Already on v${((N=v==null?void 0:v.result)==null?void 0:N.version)||"latest"}.`);return}if((j=v==null?void 0:v.result)!=null&&j.upgraded||(I=v==null?void 0:v.result)!=null&&I.success){i("done"),l(`Upgrade to v${((M=v==null?void 0:v.result)==null?void 0:M.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((w=v==null?void 0:v.result)==null?void 0:w.error)||"Upgrade failed")}catch(v){i("error"),l(v instanceof Error?v.message:"Upgrade failed")}},[e]),g=o.useCallback(async(x,y,N,j)=>{var w,v,$;const I=Date.now(),M={machineId:x,kind:y,providerType:N,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:I};try{i("loading"),l(`Launching ${N}…`),m(M);const _={cliType:N};(w=j==null?void 0:j.workspacePath)!=null&&w.trim()?_.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(_.workspaceId=j.workspaceId),j!=null&&j.resumeSessionId&&(_.resumeSessionId=j.resumeSessionId),(v=j==null?void 0:j.args)!=null&&v.trim()&&(_.cliArgs=j.args.trim().split(/\s+/).filter(Boolean)),($=j==null?void 0:j.model)!=null&&$.trim()&&(_.initialModel=j.model.trim());const T=await e(x,"launch_cli",_),F=(T==null?void 0:T.result)||T,B=(F==null?void 0:F.sessionId)||(F==null?void 0:F.id);if(T!=null&&T.success&&B){m(null),i("done"),l(`${N} launched`),s(Yt(B));return}if(T!=null&&T.success){i("loading"),l(`${N} launch requested — waiting for session…`);return}m(null),i("error"),l((T==null?void 0:T.error)||(F==null?void 0:F.error)||`Could not launch ${y.toUpperCase()} workspace`)}catch(_){if(Ex(_)){i("loading"),l(`${N} launch requested — waiting for session…`);return}m(null),i("error"),l(_ instanceof Error?_.message:`Could not launch ${y.toUpperCase()} workspace`)}},[s,e]),h=o.useCallback(async(x,y)=>{try{const N=await e(x,"list_saved_sessions",{providerType:y,kind:"cli",limit:30}),j=(N==null?void 0:N.result)??N;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(N){return console.error("Failed to list saved sessions on mobile:",N),[]}},[e]),k=o.useCallback(async(x,y)=>bn(e,x,y),[e]);o.useEffect(()=>{if(!d)return;const x=fi(d.workspacePath),y=r.find(j=>{var _,T,F,B;if(!j||j.type==="adhdev-daemon"||Dx(j.daemonId||j.id)!==d.machineId||(j.transport==="acp"?"acp":j.transport==="pty"?"cli":null)!==d.kind||String(j.agentType||j.type||"")!==d.providerType)return!1;const v=String(j.providerSessionId||"");if(d.resumeSessionId&&v)return v===d.resumeSessionId;if(x){const L=fi(j.workspace||j.runtimeWorkspaceLabel);return L?L===x:!1}return Number(j.lastUpdated||j._lastUpdate||j.timestamp||((B=(F=(T=(_=j.activeChat)==null?void 0:_.messages)==null?void 0:T.at)==null?void 0:F.call(T,-1))==null?void 0:B.timestamp)||0)>=d.startedAt-5e3});if(!y)return;const N=Tc({entrySessionId:y.sessionId,entryInstanceId:y.instanceId,entryRouteId:y.id,conversations:n});N&&(m(null),i("done"),l(`${d.providerType} launched`),s(Yt(N)))},[n,r,s,d]),o.useEffect(()=>{if(!d)return;const x=window.setTimeout(()=>{m(y=>!y||y.startedAt!==d.startedAt?y:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(x)},[d]);const p=o.useCallback(async(x,y)=>{if(y.kind==="ide"&&y.providerType){await f(x,y.providerType,{workspacePath:y.workspace||null});return}(y.kind==="cli"||y.kind==="acp")&&y.providerType&&await g(x,y.kind,y.providerType,{workspacePath:y.workspace||null,resumeSessionId:y.providerSessionId||null})},[f,g]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:f,handleAddWorkspace:b,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:g,handleListSavedSessions:h,handleBrowseDirectory:k,handleOpenRecent:p}}function Bx({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:d,setMachineBackTarget:m}){const u=o.useCallback(p=>{i(p.tabKey),c("chat"),n(p)},[n,c,i]),f=o.useCallback(p=>{const x=e.find(y=>y.routeId===p.routeId&&y.streamSource==="native");x&&(i(x.tabKey),c("chat"),n(x))},[e,n,c,i]),b=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),S=o.useCallback((p,x="inbox")=>{l(p),a(),d("machines"),m(x),c("machine")},[a,m,c,d,l]),g=o.useCallback(p=>{const x=bs(p);x&&S(x,"chat")},[S]),h=o.useCallback(()=>{a(),c(r)},[r,a,c]),k=o.useCallback(p=>{d(p),c("inbox")},[c,d]);return{openConversation:u,openNativeConversation:f,backFromConversation:b,openMachine:S,openConversationMachine:g,backFromMachine:h,changeMachineSection:k}}function ps(e,s){return e.category!==s?!1:s==="ide"?!0:e.enabled===!0}function Kx(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Wx({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:b,onRequestedMobileSectionConsumed:S,onOpenHistory:g,onOpenRemote:h,onStopCli:k,wsStatus:p,isConnected:x,onShowAllHiddenConversations:y,onHideConversation:N,onOpenNewSession:j,liveSessionInboxState:I,setCliViewModeOverrides:M}){const[w,v]=o.useState(()=>{var se;return((se=e[0])==null?void 0:se.tabKey)||null}),[$,_]=o.useState(()=>e[0]?"chat":"inbox"),[T,F]=o.useState("chats"),[B,L]=o.useState(null),[C,A]=o.useState("inbox"),K=o.useRef([]),P=xs(),D="0.9.70",H=o.useMemo(()=>e.find(se=>se.tabKey===w)||e[0]||null,[e,w]),Q=o.useMemo(()=>H?r.find(se=>se.id===H.routeId):void 0,[r,H]),be=o.useMemo(()=>!H||Qe(H)||!st(H)?null:$s(H),[H]),de=o.useMemo(()=>r.filter(se=>se.type==="adhdev-daemon").sort(Oa),[r]),te=o.useMemo(()=>de.find(se=>se.id===B)||null,[de,B]),Z=pn({sendDaemonCommand:a,activeConv:H||void 0,setActionLogs:i,isStandalone:c}),ce=$x({sendDaemonCommand:a,navigate:P,ides:r,conversations:e}),fe=o.useMemo(()=>e.map(se=>{const Re=$==="chat"&&(H==null?void 0:H.tabKey)===se.tabKey,$e=un(se,I,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Re}),Oe=ss(se),He=$c(se);return{conversation:se,timestamp:Oe,preview:He,unread:$e.unread,requiresAction:$e.requiresAction,isWorking:$e.isWorking,inboxBucket:$e.inboxBucket}}),[e,I,$,H]),{markConversationRead:J}=Px({conversations:e,machineEntries:de,items:fe,selectedConversation:H,selectedTabKey:w,screen:$,liveSessionInboxState:I,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:b,onRequestedMobileSectionConsumed:S,setSelectedTabKey:v,setScreen:_,setSelectedMachineId:L,setSection:F,setMachineBackTarget:A,resetMachineAction:ce.resetMachineAction}),me=Bx({conversations:e,selectedConversation:H,machineBackTarget:C,markConversationRead:J,resetMachineAction:ce.resetMachineAction,setSelectedTabKey:v,setScreen:_,setSelectedMachineId:L,setSection:F,setMachineBackTarget:A}),ve=o.useMemo(()=>Or(fe.filter(se=>se.requiresAction)),[fe]),ae=o.useMemo(()=>Or(fe.filter(se=>se.unread&&!se.requiresAction)),[fe]),pe=o.useMemo(()=>Ax(fe.filter(se=>!se.unread&&!se.requiresAction&&se.isWorking),K.current),[fe]);o.useEffect(()=>{K.current=pe.map(se=>se.conversation.tabKey)},[pe]);const je=o.useMemo(()=>Or(fe.filter(se=>!se.unread&&!se.requiresAction&&!se.isWorking)),[fe]),xe=o.useMemo(()=>te?fe.filter(se=>bs(se.conversation)===te.id):[],[fe,te]),ge=o.useMemo(()=>Rx(te,r),[r,te]),oe=(te==null?void 0:te.version)||null,le=!!te&&!!oe&&!0&&oe!==D,ie=o.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),Y=o.useMemo(()=>ie.filter(se=>ps(se,"cli")).map(se=>({type:se.type,displayName:se.displayName||se.type,icon:se.icon})),[ie]),G=o.useMemo(()=>ie.filter(se=>ps(se,"acp")).map(se=>({type:se.type,displayName:se.displayName||se.type,icon:se.icon})),[ie]),ue=o.useMemo(()=>Lx(de,fe),[fe,de]),ke=o.useCallback(async se=>{te&&await ce.handleOpenRecent(te.id,se)},[ce,te]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:$==="chat"&&H?t.jsx(yx,{selectedConversation:H,isAcp:Qe(H),isStandalone:c,selectedIdeEntry:Q,actionLogs:n,userName:l,isSendingChat:Z.isSendingChat,sendFeedbackMessage:Z.sendFeedbackMessage,isFocusingAgent:Z.isFocusingAgent,handleModalButton:Z.handleModalButton,handleRelaunch:Z.handleRelaunch,onBack:me.backFromConversation,onOpenNativeConversation:me.openNativeConversation,onOpenMachine:me.openConversationMachine,onOpenHistory:g,onOpenRemote:h,onStopCli:k,cliViewMode:be,onSetCliViewMode:async se=>{await ll({conversation:H,mode:se,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:M})},handleSendChat:Z.handleSendChat,handleFocusAgent:Z.handleFocusAgent}):$==="machine"&&te?t.jsx(Mx,{selectedMachineEntry:te,selectedMachineConversations:xe,selectedMachineRecentLaunches:ge,cliProviders:Y,acpProviders:G,selectedMachineNeedsUpgrade:le,appVersion:D,machineAction:ce.machineAction,isStandalone:c,section:T,showBottomNav:C==="inbox",onBack:me.backFromMachine,onSectionChange:me.changeMachineSection,onOpenConversation:me.openConversation,onOpenRecent:ke,onOpenMachineDetails:()=>P(`/machines/${te.id}`),onMachineUpgrade:()=>ce.handleMachineUpgrade(te.id),onLaunchDetectedIde:(se,Re)=>ce.handleLaunchDetectedIde(te.id,se,Re),onAddWorkspace:(se,Re)=>ce.handleAddWorkspace(te.id,se,Re),onBrowseDirectory:se=>ce.handleBrowseDirectory(te.id,se),onLaunchWorkspaceProvider:(se,Re,$e)=>ce.handleLaunchWorkspaceProvider(te.id,se,Re,$e),onListSavedSessions:se=>ce.handleListSavedSessions(te.id,se)}):t.jsx(jx,{section:T,attentionItems:ve,unreadItems:ae,workingItems:pe,completedItems:je,hiddenConversations:s,machineCards:ue,getAvatarText:Kx,actionLogs:n,sendDaemonCommand:a,onOpenConversation:me.openConversation,onShowAllHidden:y,onHideConversation:N,onOpenNewSession:j,onOpenMachine:me.openMachine,onOpenSettings:()=>P("/settings"),onSectionChange:F,wsStatus:p,isConnected:x,isStandalone:c})})}function zn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Ox({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,d]=o.useState(!1),[m,u]=o.useState(null),f=o.useCallback(()=>{c.current=0,d(!1),u(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const b=o.useCallback(k=>{k.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,d(!0))},[]),S=o.useCallback(k=>{if(!k.dataTransfer.types.includes("text/tab-key"))return;if(k.preventDefault(),!zn(s,r)){u("merge");return}const p=k.currentTarget.getBoundingClientRect(),x=k.clientX-p.left,y=p.width/3;x<y?u("split-left"):x>y*2?u("split-right"):u("merge")},[s,r]),g=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,d(!1),u(null))},[]),h=o.useCallback(k=>{c.current=0,d(!1);const p=k.dataTransfer.getData("text/tab-key"),x=p?e.some(N=>N.tabKey===p):!1,y=m;if(u(null),i(),!!p){if(k.preventDefault(),y==="split-left"&&zn(s,r)){r==null||r(p,"split-left");return}if(y==="split-right"&&zn(s,r)){r==null||r(p,"split-right");return}if(x){a(p);return}n==null||n(p)}},[e,m,s,r,n,a,i]);return{dragOver:l,dropAction:m,resetDragState:f,handleDragEnter:b,handleDragOver:S,handleDragLeave:g,handleDrop:h}}function Fx(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 Hx({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,d]=o.useState(r??[]),[m,u]=o.useState(null),f=o.useRef(null),b=o.useRef(null),S=o.useRef(n),g=o.useRef(a);o.useEffect(()=>{S.current=n},[n]),o.useEffect(()=>{g.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{d(M=>{const w=Fx(M,e);return w.length===M.length&&w.every((v,$)=>v===M[$])?M:w})},[e]);const h=o.useMemo(()=>{const M=m??l;if(M.length===0)return e;const w=new Map(M.map((v,$)=>[v,$]));return[...e].sort((v,$)=>{const _=w.get(v.tabKey)??999,T=w.get($.tabKey)??999;return _-T})},[e,m,l]);o.useEffect(()=>{var w,v;if(h.length===0){i!==null&&(c(null),(w=S.current)==null||w.call(S,null));return}if(i&&h.some($=>$.tabKey===i))return;const M=h[0].tabKey;M!==i&&(c(M),(v=S.current)==null||v.call(S,M))},[h,i]);const k=o.useMemo(()=>h.find(M=>M.tabKey===i),[h,i]),p=o.useCallback(M=>{var w;c(M),(w=S.current)==null||w.call(S,M)},[]),x=o.useCallback((M,w,v)=>{d($=>{var B;const _=$.filter(L=>L!==M),T=_.indexOf(w);if(T<0)return $;const F=v==="left"?T:T+1;return _.splice(F,0,M),(B=g.current)==null||B.call(g,_),_}),u(null)},[]),y=o.useCallback((M,w,v)=>{const _=(l.length>0?l:e.map(B=>B.tabKey)).filter(B=>B!==M),T=_.indexOf(w);if(T<0)return;const F=v==="left"?T:T+1;_.splice(F,0,M),f.current=_,u(_)},[l,e]),N=o.useCallback(()=>{var w;const M=f.current;M&&(d(M),(w=g.current)==null||w.call(g,M))},[]),j=o.useCallback(()=>{f.current=null,u(null)},[]),I=o.useCallback(M=>{d(w=>{var $;const v=w.filter(_=>_!==M);return v.push(M),($=g.current)==null||$.call(g,v),v})},[]);return{activeTabId:i,activeConv:k,sortedConversations:h,previewOrderRef:f,draggingTabRef:b,selectTab:p,handleTabReorder:x,updatePreviewOrder:y,commitPreviewOrder:N,clearPreviewOrder:j,moveTabToEnd:I,setDraggingTabKey:M=>{b.current=M}}}function Ux({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 fo({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){if(a)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!i,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?Oc:r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!s?t.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[t.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),t.jsxs("div",{className:"text-center max-w-lg",children:[t.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),l&&t.jsx("div",{className:"flex items-center justify-center mb-4",children:t.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Et,"aria-label":Et,children:[t.jsx(Xi,{size:14}),t.jsx("span",{children:Et})]})}),c&&t.jsx(gl,{}),c&&t.jsx("div",{className:"mt-8",children:t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):t.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const jl="adhdev-tab-shortcuts";function kl(){try{return JSON.parse(localStorage.getItem(jl)||"{}")}catch{return{}}}function Sl({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>kl()),[l,d]=o.useState(null),m=o.useCallback(f=>{const b=[];return f.metaKey&&b.push(a?"⌘":"Meta"),f.ctrlKey&&b.push("Ctrl"),f.altKey&&b.push(a?"⌥":"Alt"),f.shiftKey&&b.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(b.push(f.key.length===1?f.key.toUpperCase():f.key),b.join("+"))},[a]),u=o.useCallback(f=>{c(f);try{localStorage.setItem(jl,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){d(null);return}const S=m(b);if(!S)return;const g={...i};for(const[h,k]of Object.entries(g))k===S&&delete g[h];g[l]=S,u(g),d(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,u,m]),o.useEffect(()=>{if(!e)return;const f=b=>{if(!(!b.ctrlKey&&!b.metaKey&&!b.altKey)){for(const[S,g]of Object.entries(i))if(s.includes(S)&&m(b)===g){b.preventDefault(),r(),n(S);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,s,r,n,m]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:d,saveShortcuts:u}}const Vn=e=>{e.preventDefault()},zx=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:f,onReorderTab:b,onCommitPreviewOrder:S,onClearPreviewOrder:g,onDragStateReset:h,onDragTabKeyChange:k,onReceiveTab:p,onOpenContextMenu:x,longPressTimer:y,isGroupActive:N}){const j=Es(s),I=j.isGenerating?"agent-tab-generating":j.isWaiting?"agent-tab-waiting":"",M=j.isReconnecting,w=o.useCallback(A=>{l.current=s.tabKey,k(s.tabKey),A.dataTransfer.setData("text/tab-key",s.tabKey),A.dataTransfer.effectAllowed="move"},[s.tabKey,l,k]),v=o.useCallback(()=>{l.current=null,k(null),S(),g(),h()},[l,k,S,g,h]),$=o.useCallback(A=>{const K=l.current;if(!(!K||K===s.tabKey)&&A.dataTransfer.types.includes("text/tab-key")){A.preventDefault(),A.stopPropagation();const P=A.currentTarget.getBoundingClientRect(),D=A.clientX<P.left+P.width/2?"left":"right";f(K,s.tabKey,D)}},[s.tabKey,l,f]),_=o.useCallback(A=>{A.preventDefault(),A.stopPropagation();const K=A.dataTransfer.getData("text/tab-key");if(K&&K!==s.tabKey){const P=A.currentTarget.getBoundingClientRect(),D=A.clientX<P.left+P.width/2?"left":"right";c.includes(K)?b(K,s.tabKey,D):p&&p(K)}g()},[s.tabKey,c,b,p,g]),T=o.useCallback(A=>{A.stopPropagation(),d(),m(s.tabKey),u(s)},[s,u,d,m]),F=o.useCallback(A=>{A.preventDefault(),x(A.clientX,A.clientY,s.tabKey)},[s.tabKey,x]),B=o.useCallback(A=>{const K=A.touches[0];y.current=setTimeout(()=>{x(K.clientX,K.clientY,s.tabKey)},600)},[s.tabKey,y,x]),L=o.useCallback(()=>{y.current&&clearTimeout(y.current)},[y]),C=["adhdev-dockview-tab",I,r&&"is-active",N&&"is-group-active",M&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:w,onDragEnd:v,onDragOver:$,onDrop:_,onClick:T,onContextMenu:F,onTouchStart:B,onTouchEnd:L,onTouchMove:L,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:"▲"}):M?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:ct(s),children:ct(s)}),t.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[M?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:rs(s)}):j.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[rs(s),t.jsx("span",{className:"connecting-dots"})]}):t.jsx("span",{className:"truncate",children:rs(s)}),t.jsx(Ls,{git:s.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),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 Vx({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:b,onDragTabKeyChange:S,onReceiveTab:g,onHideTab:h,isGroupActive:k,allowTabShortcuts:p=!0}){const[x,y]=o.useState(null),N=o.useRef(null),j=o.useRef(null),I=o.useMemo(()=>e.map(F=>F.tabKey),[e]);lr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(x==null?void 0:x.tabKey)||null});const{isMac:M,tabShortcuts:w,shortcutListening:v,setShortcutListening:$,saveShortcuts:_}=Sl({enabled:p,sortedTabKeys:e.map(F=>F.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!x)return;const F=B=>{const L=document.querySelector("[data-pane-context-menu]");L&&L.contains(B.target)||y(null)};return window.addEventListener("mousedown",F,!0),()=>window.removeEventListener("mousedown",F,!0)},[x]),o.useEffect(()=>{const F=j.current;if(!F)return;const B=L=>{Math.abs(L.deltaY)<=Math.abs(L.deltaX)||(L.preventDefault(),F.scrollLeft+=L.deltaY)};return F.addEventListener("wheel",B,{passive:!1}),()=>F.removeEventListener("wheel",B)},[]);const T=o.useCallback((F,B,L)=>{y({x:F,y:B,tabKey:L})},[]);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(F=>t.jsx(zx,{conv:F,isActive:s===F.tabKey,isDraggedTab:a.current===F.tabKey,isTaskCompleteUnread:n.has(F.tabKey),shortcut:p?w[F.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:b,onDragTabKeyChange:S,onReceiveTab:g,onOpenContextMenu:T,longPressTimer:N,isGroupActive:k},F.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),x&&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:x.x,top:x.y},children:[p&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Vn,onClick:F=>{F.stopPropagation(),$(x.tabKey),y(null)},children:["⌨ ",w[x.tabKey]?`Change shortcut (${w[x.tabKey]})`:"Set shortcut"]}),w[x.tabKey]&&t.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Vn,onClick:()=>{const F={...w};delete F[x.tabKey],_(F),y(null)},children:"✕ Remove shortcut"})]}),h&&t.jsxs(t.Fragment,{children:[p&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Vn,onClick:()=>{h(x.tabKey),y(null)},children:"🚫 Hide from Dashboard"})]})]}),p&&v&&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:F=>F.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. ",M?"⌘+1":"Ctrl+1",", ",M?"⌥+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 Gx({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:d,groupIndex:m,onFocus:u,isSplitMode:f,numGroups:b,onMoveTab:S,onReceiveTab:g,style:h,onActiveTabChange:k,initialActiveTabId:p,initialTabOrder:x,onTabOrderChange:y,onHideTab:N,isFocused:j,allowTabShortcuts:I=!0,onOpenNewSession:M,liveSessionInboxState:w}){const{sendCommand:v}=xt(),$=o.useRef(null),{activeTabId:_,activeConv:T,sortedConversations:F,draggingTabRef:B,selectTab:L,handleTabReorder:C,updatePreviewOrder:A,commitPreviewOrder:K,clearPreviewOrder:P,moveTabToEnd:D,setDraggingTabKey:H}=Hx({conversations:e,initialActiveTabId:p,initialTabOrder:x,onActiveTabChange:k,onTabOrderChange:y}),Q=pn({sendDaemonCommand:a,activeConv:T,setActionLogs:i,isStandalone:c}),{dragOver:be,dropAction:de,resetDragState:te,handleDragEnter:Z,handleDragOver:ce,handleDragLeave:fe,handleDrop:J}=Ox({conversations:e,numGroups:b,onMoveTab:S,onReceiveTab:g,onOwnTabDrop:D,onClearPreviewOrder:P}),me=T&&!Qe(T)&&$s(T)==="terminal",ve=o.useMemo(()=>T?s.find(xe=>xe.id===T.routeId):void 0,[s,T]),ae=o.useMemo(()=>T?n.filter(xe=>xe.routeId===T.tabKey):[],[n,T]),pe=o.useMemo(()=>new Set(F.filter(xe=>Hu(xe,w,{isOpenConversation:xe.tabKey===_})).map(xe=>xe.tabKey)),[_,w,F]);lr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:_,dragOver:be});const je=o.useCallback(xe=>{xe.streamSource==="agent-stream"&&xe.agentType&&v(xe.routeId,yc(),{agentType:xe.agentType,...xe.sessionId&&{targetSessionId:xe.sessionId}}).catch(()=>{})},[v]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...h,outline:be?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Vx,{conversations:F,activeTabId:_,groupIndex:m,numGroups:b,unreadTabKeys:pe,draggingTabRef:B,onFocus:u,onSelectTab:L,onConversationActivated:je,onPreviewReorder:A,onReorderTab:C,onCommitPreviewOrder:K,onClearPreviewOrder:P,onDragStateReset:te,onDragTabKeyChange:H,onMoveTab:S,onReceiveTab:g,onHideTab:N,isGroupActive:j??!1,allowTabShortcuts:I}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Z,onDragOver:ce,onDragLeave:fe,onDrop:J,children:[be&&t.jsx(Ux,{dropAction:de,canSplit:!!(b<4&&S)}),T?t.jsx(uo,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!me,ideEntry:ve,terminalRef:$,handleModalButton:Q.handleModalButton,handleRelaunch:Q.handleRelaunch,handleSendChat:Q.handleSendChat,isSendingChat:Q.isSendingChat,sendFeedbackMessage:Q.sendFeedbackMessage,handleFocusAgent:Q.handleFocusAgent,isFocusingAgent:Q.isFocusingAgent,actionLogs:ae,userName:d,isInputActive:!f||!!j}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(fo,{conversationsCount:e.length,isSplitMode:f,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:M})})]})]})}function qx({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:b,focusedGroup:S,focusGroup:g,moveTabToGroup:h,splitTabRelative:k,closeGroup:p,handleResizeStart:x,groupActiveTabIds:y,setGroupActiveTab:N,groupTabOrders:j,setGroupTabOrder:I,toggleHiddenTab:M,onOpenNewSession:w,allowTabShortcuts:v=!0,liveSessionInboxState:$}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((_,T)=>{const F=s&&n.length===r?`${n[T]}%`:void 0;return t.jsxs(Nt.Fragment,{children:[s&&T>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:B=>x(T-1,B),onDoubleClick:()=>p(T),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(Gx,{style:s?{flexBasis:F??`${100/r}%`,flexGrow:F?0:1,flexShrink:F?0:1}:void 0,conversations:_,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:b,groupIndex:T,isFocused:s&&S===T,onFocus:()=>g(T),isSplitMode:s,numGroups:r,onMoveTab:(B,L)=>{L==="left"&&T>0?h(B,T-1):L==="right"&&T<r-1?h(B,T+1):L==="split-left"&&r<4?k(B,T,"left"):L==="split-right"&&r<4&&k(B,T,"right")},onReceiveTab:B=>h(B,T),onActiveTabChange:B=>N(T,B),initialActiveTabId:y[T],initialTabOrder:j[T],onTabOrderChange:B=>I(T,B),onHideTab:M,onOpenNewSession:w,allowTabShortcuts:v,liveSessionInboxState:$})]},T)})})}function Nl({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?dt.onScreenshot("ide-page",(u,f)=>{if(u!==e)return;const b=new FileReader;b.onload=()=>i(b.result),b.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var u;return e?((u=dt.onStatus)==null?void 0:u.call(dt,(f,b)=>{f===e&&b!=null&&b.screenshotUsage&&l(b.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const m=e?dt.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&s?m.startScreenshots(s):m.stopScreenshots(s),()=>{m.stopScreenshots(s)}},[n,r,s,e]);const d=o.useCallback(async(m,u)=>{const f=e?dt.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(m,u,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:d}}const Cl="adhdev-dashboard-action-shortcuts",Yx=1200,Xx=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function Jx(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function rt(e,s){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return s?"⌘+⇧+Enter":"Ctrl+Shift+Enter";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+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return s?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";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+Shift+←";case"selectNextGroupTab":return s?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function Tl(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:rt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:rt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:rt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:rt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:rt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:rt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:rt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:rt("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:rt("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:rt("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:rt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:rt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:rt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:rt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:rt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:rt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:rt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:rt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:rt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:rt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:rt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:rt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:rt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:rt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:rt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:rt("toggleCliView",e)}]}function Ta(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function nn(e){const s=Object.fromEntries(Tl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Cl)||"{}"),n={...s,...r};for(const[a,i]of Xx)n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function Ml(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Qx({enabled:e=!0,onTrigger:s}){const r=Jx(),[n,a]=o.useState(()=>nn(r)),[i,c]=o.useState(null),[l,d]=o.useState([]),m=o.useRef({parts:[],timer:null}),u=o.useCallback(h=>{const k=[];return h.metaKey&&k.push(r?"⌘":"Meta"),h.ctrlKey&&k.push("Ctrl"),h.altKey&&k.push(r?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&k.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(k.push(Ml(h.key)),k.join("+"))},[r]),f=o.useCallback(h=>{a(h);try{localStorage.setItem(Cl,JSON.stringify(h))}catch{}},[]);o.useEffect(()=>{const h=nn(r),k=Object.entries(n),p=Object.entries(h);k.length===p.length&&k.every(([x,y])=>h[x]===y)||f(h)},[n,r,f]);const b=o.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),S=o.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},Yx))},[]);o.useEffect(()=>{if(!i)return;const h=k=>{if(k.preventDefault(),k.stopPropagation(),k.key==="Escape"){c(null),d([]);return}const p=u(k);if(!p)return;const y=!(k.metaKey||k.ctrlKey||k.altKey)&&/^[A-Z0-9]$/.test(p);if(l.length===0&&y){d([p]);return}const j=[...l,p].slice(0,2).join(" "),I={...n};for(const[M,w]of Object.entries(I))w===j&&delete I[M];I[i]=j,f(I),c(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[n,u,f,i,l]),o.useEffect(()=>{if(!e||i)return;const h=k=>{if(k.defaultPrevented)return;const p=u(k);if(!p)return;const x=k.metaKey||k.ctrlKey||k.altKey;if(Ta(k.target))return;const y=m.current.parts,N=x?[p]:[...y.slice(-1),p].slice(-2),j=N.join(" "),I=N[N.length-1],M=Object.entries(n).filter(([,T])=>!!T),w=M.find(([,T])=>T===j);if(w){k.preventDefault(),b(),s(w[0]);return}if(M.some(([,T])=>T.startsWith(`${j} `))){k.preventDefault(),m.current.parts=N,S();return}const $=M.find(([,T])=>T===I);if($){k.preventDefault(),b(),s($[0]);return}if(M.some(([,T])=>T.startsWith(`${I} `))){k.preventDefault(),m.current.parts=[I],S();return}b()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[n,S,e,u,s,b,i]),o.useEffect(()=>()=>b(),[b]);const g=o.useMemo(()=>Tl(r),[r]);return{isMac:r,actionDefinitions:g,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:d,saveShortcuts:f}}function Zx({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 Al(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function pi({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Al(n):!0}function eb({previousVisibleConversationCount:e,visibleConversationCount:s,ides:r}){return s>0||e<=0?!1:Al(r)}const Il=1e3,tb=4;function hi(e,s){return s?e.clientX>=s.left&&e.clientX<=s.right&&e.clientY>=s.top&&e.clientY<=s.bottom:!1}function xi(e,s,r){return Math.abs(s.clientX-e.clientX)>r||Math.abs(s.clientY-e.clientY)>r}function sb({detachDelayMs:e=Il,stillnessThresholdPx:s=tb,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let i=null,c=null,l=null,d=null,m=null,u=!1;const f=()=>{m!=null&&(a(m),m=null)},b=()=>{f(),l=null},S=()=>{f(),i=null,c=null,l=null,d=null,u=!1},g=()=>{!i||!l||!d||u||m!=null||(m=n(()=>{m=null,!(!i||!l||!d||u)&&hi(d,c)&&(xi(l,d,s)||(u=!0,r({panelId:i,clientX:d.clientX,clientY:d.clientY})))},e))},h=p=>{if(!(!i||u)){if(!hi(p,c)){d={clientX:p.clientX,clientY:p.clientY},b();return}(!l||xi(l,p,s))&&(f(),l={clientX:p.clientX,clientY:p.clientY}),d={clientX:p.clientX,clientY:p.clientY},g()}},k=p=>{!i||u||(p&&(d={clientX:p.clientX,clientY:p.clientY}),b())};return{startDrag:p=>{f(),i=p.panelId,c=p.selfPanelBounds??null,l=null,d={clientX:p.clientX,clientY:p.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:k,markNoDropTarget:k,markDockTarget:k,endDrag:S,isDragging:()=>i!=null,hasDetached:()=>u,dispose:S}}function rb(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}const Rl=o.createContext(null);function yn(){const e=o.useContext(Rl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Fr(e){return ct(e)||e.tabKey}function nb(e){return`remote:${e}`}function Rt(e){return e.startsWith("remote:")}function bi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function ab(e){e.preventDefault()}function Gn(e){var n;const s=e==null?void 0:e.defaultView;if(!s)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{s.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=s.requestAnimationFrame)==null||n.call(s,()=>{try{s.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function qn(e,s){e.classList.remove(ca.className,la.className),e.classList.add(s==="light"?ca.className:la.className)}function gi(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 ob(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 ib(e,s,r){var c;const n=[s];let a;for(const l of n){let d;for(const m of l){const u=e.addPanel({id:m.tabKey,component:"conversation",title:Fr(m),params:{kind:"conversation",tabKey:m.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function yi(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Rt(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!==Fr(n)&&a.api.setTitle(Fr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Fr(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 vi(e,s,r){var d,m;const n=r?nb(r):null;for(const u of[...e.panels])Rt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Pt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=Wc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!Rt(u.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function cb({params:e,api:s}){var f;const r=yn(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=pn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const b=[s.onDidActiveChange(S=>i(S.isActive)),s.onDidActiveGroupChange(S=>{if(!s.isActive&&!S.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const S of b)S.dispose()}},[s]);const d=o.useMemo(()=>c?r.ides.find(b=>b.id===c.routeId):void 0,[r.ides,c]),m=o.useMemo(()=>c?r.actionLogs.filter(b=>b.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(fo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const u=!Qe(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(uo,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:d,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:m,userName:r.userName,scrollToBottomRequestNonce:((f=r.scrollToBottomRequest)==null?void 0:f.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function lb({params:e}){var d;const s=yn(),r=o.useMemo(()=>Pt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>s.ides.find(m=>m.id===e.routeId),[s.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=Nl({doId:a,targetSessionId:r?gc(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(sc,{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 db(){const e=yn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(fo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function ub(e){var S,g;ob(e);const s=yn(),r=o.useCallback(h=>{"button"in h&&h.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const h=Pt([...s.conversationsByTabKey.values()],e.params.routeId),k=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,p=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${k?" is-active":""}${p?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(h==null?void 0:h.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:h!=null&&h.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:h.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=((g=e.api.group.activePanel)==null?void 0:g.id)===e.api.id,i=e.api.isGroupActive,c=un(n,s.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,d=c.isConnecting,m=c.isGenerating,u=c.isWaiting,f=c.unread,b=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:ct(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:h=>{var k;h.preventDefault(),r(h),s.openTabContextMenu({x:h.clientX,y:h.clientY,tabKey:n.tabKey,sourceDocument:((k=h.target)==null?void 0:k.ownerDocument)??document})},children:[f&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?t.jsx("div",{className:"tab-spinner"}):u?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:"○"}):d?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:ct(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:rs(n)}):d?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:rs(n)}):t.jsx("span",{children:rs(n)})})]}),b&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:b,children:b})]})}function mb({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:f,registerActionHandlers:b,onActiveTabChange:S,onOpenNewSession:g,onRequestScrollToBottom:h,requestedActiveTabKey:k,requestedRemoteIdeId:p,onRequestedActiveTabConsumed:x,scrollToBottomRequest:y,liveSessionInboxState:N,layoutProfile:j}){var Xe,Ve,tt;const{theme:I}=no(),{sendCommand:M}=xt(),w=o.useRef(null),v=o.useRef(null),$=o.useRef(null),_=o.useRef(!1),T=o.useRef(!1),F=o.useRef(!1),B=o.useRef(null),L=o.useRef([]),[C,A]=o.useState(null),[K,P]=o.useState(0),D=o.useRef(typeof window>"u"?{}:Ph(j)),H=o.useMemo(()=>new Map(e.map(O=>[O.tabKey,O])),[e]),Q=o.useMemo(()=>{const O=w.current;return O?O.groups.some(z=>{try{const q=z.model.location.type;return q!=="floating"&&q!=="popout"?!1:z.panels.some(re=>H.has(re.id))}catch{return!1}}):!1},[H,K,e]),be=o.useCallback(()=>{var O;(O=w.current)==null||O.focus()},[]),de=o.useCallback((O,z)=>{h==null||h(O,z)},[h]),te=o.useCallback(O=>{const z=document,q=O.document;for(const ne of z.querySelectorAll('link[rel="stylesheet"]')){const we=q.createElement("link");we.rel="stylesheet",we.href=ne.href,ne.crossOrigin&&(we.crossOrigin=ne.crossOrigin),q.head.appendChild(we)}for(const ne of z.querySelectorAll("style")){const we=q.createElement("style");we.textContent=ne.textContent,q.head.appendChild(we)}const re=[];for(const ne of z.styleSheets)try{for(const we of ne.cssRules)we instanceof CSSStyleRule&&(we.selectorText===":root"||we.selectorText==="html")&&re.push(we.cssText)}catch{}if(re.length>0){const ne=q.createElement("style");ne.textContent=re.join(`
|
|
52
|
-
`),q.head.appendChild(ne)}const E=z.documentElement.getAttribute("data-theme");E&&q.documentElement.setAttribute("data-theme",E),q.documentElement.style.colorScheme=E==="light"?"light":"dark",q.body.className=z.body.className;const X=z.documentElement.getAttribute("style");X&&q.documentElement.setAttribute("style",X);const ee=q.getElementById("dv-popout-window");ee instanceof HTMLElement&&(ee.classList.add("adhdev-dockview"),qn(ee,I))},[I]),Z=o.useCallback(()=>{var z;const O=w.current;if(O)for(const q of O.groups)try{const re=(z=q.element)==null?void 0:z.ownerDocument;if(!re||re===document)continue;const E=re.getElementById("dv-popout-window");E instanceof HTMLElement&&(E.classList.add("adhdev-dockview"),qn(E,I));const X=document.documentElement.getAttribute("data-theme");X&&re.documentElement.setAttribute("data-theme",X),re.documentElement.style.colorScheme=X==="light"?"light":"dark",re.body.className=document.body.className;const ee=document.documentElement.getAttribute("style");ee?re.documentElement.setAttribute("style",ee):re.documentElement.removeAttribute("style")}catch{}},[I]),ce=o.useCallback(O=>{const z=w.current;if(!z)return;const q=z.getPanel(O);q&&z.addPopoutGroup(q,{popoutUrl:"/popout.html",onDidOpen:({window:re})=>{te(re),ge();const E=H.get(O);re.document.title=E?`${ct(E)} — ADHDev`:"ADHDev — Popout"}})},[H,te]),fe=o.useCallback(O=>{const z=w.current,q=z==null?void 0:z.getPanel(O);if(!z||!q)return;const re=z.groups.filter(E=>{var X;try{return((X=E.element)==null?void 0:X.ownerDocument)===document}catch{return!0}});re.length>0?q.api.moveTo({group:re[0],position:"center"}):q.api.moveTo({position:"center"}),q.api.setActive()},[]),J=o.useCallback(O=>{var re;const z=w.current;if(!z)return!1;const q=z.getPanel(O);if(!q)return!1;try{return((re=q.group.element)==null?void 0:re.ownerDocument)!==document}catch{return!1}},[]),me=o.useCallback(O=>{J(O)&&fe(O),u(O)},[J,fe,u]),ve=o.useCallback(O=>{const z=w.current,q=z==null?void 0:z.getPanel(O);!z||!q||z.addFloatingGroup(q,{width:600,height:500})},[]),ae=o.useCallback(O=>{var q;const z=(q=w.current)==null?void 0:q.getPanel(O);if(!z)return!1;try{return z.group.model.location.type==="floating"}catch{return!1}},[]),pe=o.useCallback(()=>{var z,q;const O=(q=(z=w.current)==null?void 0:z.activePanel)==null?void 0:q.id;return!O||Rt(O)?null:H.has(O)?O:null},[H]),je=o.useCallback(O=>{const z=w.current,q=z==null?void 0:z.getPanel(O);if(!z||!q)return;const re=z.groups.filter(E=>{try{return E.model.location.type==="grid"}catch{return!0}});re.length>0?q.api.moveTo({group:re[0],position:"center"}):q.api.moveTo({position:"center"}),q.api.setActive()},[]),xe=o.useCallback(()=>{var X;const O=w.current;if(!O)return;const q=O.groups.filter(ee=>{var ne;try{return((ne=ee.element)==null?void 0:ne.ownerDocument)===document&&ee.model.location.type==="grid"}catch{return!1}})[0]||null,re=[...O.panels];for(const ee of re){const ne=(X=ee.group.element)==null?void 0:X.ownerDocument,we=ee.group.model.location.type;ne===document&&we==="grid"||(q&&q.id!==ee.group.id?ee.api.moveTo({group:q,position:"center"}):ee.api.moveTo({position:"center"}))}const E=O.activePanel;E&&(E.group.model.openPanel(E),E.api.setActive()),Gn(document)},[]),ge=o.useCallback(()=>{var z,q;const O=w.current;if(O)for(const re of O.groups){const E=(z=re.element)==null?void 0:z.ownerDocument;if(!E||E===document)continue;const X=E.getElementById("dv-popout-window");if(!(X instanceof HTMLElement))continue;let ee=null,ne=E.title||"ADHDev",we="Popout workspace";const Ae=re.activePanel;if(Ae)if(ee=Ae.id,Rt(Ae.id)){const Ie=((q=Ae.params)==null?void 0:q.routeId)||Ae.id.slice(7),Ge=Pt([...H.values()],Ie);ne=Wc(Ge),we=Ge!=null&&Ge.machineName?`Remote view · ${Ge.machineName}`:"Remote view"}else{const Ie=H.get(Ae.id);ne=Ie?ct(Ie):Ae.title||Ae.id,we=Ie?rs(Ie):"Dockview panel"}E.title=`${ne} — ADHDev`;const _e=Array.from(E.querySelectorAll("#adhdev-popout-header"));for(const Ie of _e)Ie.remove();const Se=E.createElement("div");Se.id="adhdev-popout-header",E.body.appendChild(Se),Se.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(";")),Se.innerHTML=`
|
|
53
|
-
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
54
|
-
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
55
|
-
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${bi(ne)}</div>
|
|
56
|
-
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${bi(we)}</div>
|
|
57
|
-
</div>
|
|
58
|
-
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
59
|
-
<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>
|
|
60
|
-
<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>
|
|
61
|
-
</div>
|
|
62
|
-
`,X.style.top="52px",X.style.height="calc(100% - 52px)";const Pe=Se.querySelector("[data-adhdev-popout-focus]");Pe&&(Pe.onclick=()=>{window.focus()});const Ee=Se.querySelector("[data-adhdev-popout-dock]");Ee&&(Ee.disabled=!ee,Ee.style.opacity=ee?"1":"0.5",Ee.style.cursor=ee?"pointer":"default",Ee.onclick=()=>{var Ie;ee&&fe(ee),(Ie=E.defaultView)==null||Ie.focus()})}},[H,fe]),oe=o.useCallback(O=>{var re;const z=w.current,q=z==null?void 0:z.getPanel(O);if(!(!z||!q)){q.group.model.openPanel(q),q.api.setActive(),de(O,"dockview-shortcut");try{const E=q.group.model.location;E.type==="popout"?E.getWindow().focus():Gn((re=q.group.element)==null?void 0:re.ownerDocument)}catch{}}},[de]),le=o.useCallback(O=>{const z=w.current,q=z==null?void 0:z.activePanel,re=(z==null?void 0:z.activeGroup)||(q==null?void 0:q.group);if(!z||!q||!re)return;const E=re.panels||[];if(E.length<=1)return;const X=E.findIndex(we=>we.id===q.id);if(X<0)return;const ee=(X+O+E.length)%E.length,ne=E[ee];ne&&(ne.group.model.openPanel(ne),ne.api.setActive(),Rt(ne.id)||de(ne.id,"dockview-shortcut"))},[de]),ie=o.useCallback(O=>{var Pe;const z=w.current,q=(z==null?void 0:z.activeGroup)||((Pe=z==null?void 0:z.activePanel)==null?void 0:Pe.group);if(!z||!q)return;const re=z.groups||[],E=re.find(Ee=>Ee.id===q.id);if(!E)return;const X=E.element.getBoundingClientRect(),ee=X.left+X.width/2,ne=X.top+X.height/2,we=(Ee,Ie,Ge,Ze)=>Math.max(0,Math.min(Ie,Ze)-Math.max(Ee,Ge)),Ae=Ee=>{const Ie=Ee.element.getBoundingClientRect(),Ge=Ie.left+Ie.width/2,Ze=Ie.top+Ie.height/2;let it=0,lt=0,ht=0,bt=!1;if(O==="left"?(bt=Ge<ee,it=Math.max(0,X.left-Ie.right),lt=Math.abs(Ze-ne),ht=we(X.top,X.bottom,Ie.top,Ie.bottom)):O==="right"?(bt=Ge>ee,it=Math.max(0,Ie.left-X.right),lt=Math.abs(Ze-ne),ht=we(X.top,X.bottom,Ie.top,Ie.bottom)):O==="above"?(bt=Ze<ne,it=Math.max(0,X.top-Ie.bottom),lt=Math.abs(Ge-ee),ht=we(X.left,X.right,Ie.left,Ie.right)):(bt=Ze>ne,it=Math.max(0,Ie.top-X.bottom),lt=Math.abs(Ge-ee),ht=we(X.left,X.right,Ie.left,Ie.right)),!bt)return Number.POSITIVE_INFINITY;const ze=ht>0?0:120;return it*3+lt+ze};let _e=null,Se=Number.POSITIVE_INFINITY;for(const Ee of re){if(Ee.id===E.id)continue;const Ie=Ae(Ee);Number.isFinite(Ie)&&(Ie>=Se||(Se=Ie,_e=Ee))}return _e||void 0},[]),Y=o.useCallback(O=>{var re;const z=ie(O);if(!z)return;const q=z.activePanel||z.panels[0];q&&(z.model.openPanel(q),q.api.setActive(),Rt(q.id)||de(q.id,"dockview-focus"),Gn((re=z.element)==null?void 0:re.ownerDocument))},[ie,de]),G=o.useCallback((O,z)=>{const q=w.current,re=q==null?void 0:q.activePanel,E=(q==null?void 0:q.activeGroup)||(re==null?void 0:re.group);if(!q||!re||!E)return;let X=ie(O);!X&&(z!=null&&z.createGroupIfMissing)&&(X=q.addGroup({referenceGroup:E,direction:O})),X&&(re.api.moveTo({group:X,position:"center"}),re.group.model.openPanel(re),re.api.setActive(),Rt(re.id)||de(re.id,z!=null&&z.createGroupIfMissing?"dockview-split":"dockview-move"))},[ie,de]),{isMac:ue,tabShortcuts:ke,shortcutListening:se,setShortcutListening:Re,saveShortcuts:$e}=Sl({sortedTabKeys:e.map(O=>O.tabKey),onFocus:be,onSelectTab:oe}),Oe=o.useCallback(()=>{var q;const O=w.current;if(!O)return;const z=O.activePanel;if(z){if(Rt(z.id)){const re=((q=z.params)==null?void 0:q.routeId)||z.id.slice(7),E=Pt(e,re);E!=null&&E.tabKey&&Re(E.tabKey);return}H.has(z.id)&&Re(z.id)}},[H,oe,Re,e]),He=o.useCallback(O=>{const z=[];return O.metaKey&&z.push(ue?"⌘":"Meta"),O.ctrlKey&&z.push("Ctrl"),O.altKey&&z.push(ue?"⌥":"Alt"),O.shiftKey&&O.key.length!==1&&z.push(ue?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(O.key)?null:(z.push(Ml(O.key)),z.join("+"))},[ue]),W=o.useCallback(O=>{var z,q;switch(O){case"splitActiveTabRight":G("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":G("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const re=pe();re&&ve(re);return}case"popoutActiveTab":{const re=pe();re&&ce(re);return}case"dockActiveTab":{const re=pe();if(!re)return;J(re)?fe(re):ae(re)&&je(re);return}case"focusLeftPane":Y("left");return;case"focusRightPane":Y("right");return;case"focusUpPane":Y("above");return;case"focusDownPane":Y("below");return;case"moveActiveTabToLeftPane":G("left");return;case"moveActiveTabToRightPane":G("right");return;case"moveActiveTabToUpPane":G("above");return;case"moveActiveTabToDownPane":G("below");return;case"selectPreviousGroupTab":le(-1);return;case"selectNextGroupTab":le(1);return;case"setActiveTabShortcut":Oe();return;case"hideCurrentTab":{const re=(q=(z=w.current)==null?void 0:z.activePanel)==null?void 0:q.id;re&&!Rt(re)&&me(re);return}default:return}},[le,je,Y,ve,pe,me,ae,J,fe,G,ce,Oe]);o.useEffect(()=>{if(!C)return;const O=C.sourceDocument,z=O.defaultView??window,q=re=>{const E=O.querySelector("[data-dockview-tab-context-menu]");E&&E.contains(re.target)||A(null)};return z.addEventListener("mousedown",q,!0),z!==window&&window.addEventListener("mousedown",()=>A(null),!0),()=>{z.removeEventListener("mousedown",q,!0),z!==window&&window.removeEventListener("mousedown",()=>A(null),!0)}},[C]);const Ce=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:H,hasDetachedConversationPanels:Q,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:g,liveSessionInboxState:N,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:me,userName:m,scrollToBottomRequest:y,tabShortcuts:ke,openTabContextMenu:({x:O,y:z,tabKey:q,sourceDocument:re})=>A({x:O,y:z,tabKey:q,sourceDocument:re??document}),popoutTab:ce,moveTabBackToMain:fe,isTabInPopout:J,floatTab:ve,isTabFloating:ae}),[n,s,H,Q,r,c,l,g,N,a,i,me,m,y,ke,ce,fe,J,ve,ae]),Te=C?Zx({isTabInPopout:J(C.tabKey),isTabFloating:ae(C.tabKey),tabShortcut:ke[C.tabKey],actionShortcuts:f}):[],Le=o.useCallback(O=>{var re;const z=w.current;if((((re=z==null?void 0:z.activePanel)==null?void 0:re.id)??null)===O.id){O.group.model.openPanel(O);return}O.group.model.openPanel(O),O.api.setActive()},[]),Be=o.useCallback((O,z="requested-tab")=>{if(!O)return!1;const q=w.current;if(!q)return!1;const re=q.getPanel(O);return re?(Le(re),de(O,z),x==null||x(),!0):!1},[Le,x,de]),Fe=o.useCallback(()=>{if(F.current)return!1;const O=Be(B.current,"stored-layout-restore");return O&&(F.current=!0),O},[Be]),Ye=o.useCallback(()=>{var z;const O=w.current;O&&_h(j,{activeTabId:((z=O.activePanel)==null?void 0:z.id)??null,layout:O.toJSON()})},[j]),et=o.useCallback(()=>{Dh(j,D.current)},[j]),ut=o.useCallback(O=>{var re,E,X,ee;const z=w.current;if(!z)return{kind:"grid"};const q=z.toJSON();for(const ne of q.floatingGroups||[])if((E=(re=ne.data)==null?void 0:re.views)!=null&&E.includes(O)&&ne.position)return{kind:"floating",position:ne.position};for(const ne of q.popoutGroups||[])if((ee=(X=ne.data)==null?void 0:X.views)!=null&&ee.includes(O))return{kind:"popout",position:ne.position,popoutUrl:ne.url};return{kind:"grid"}},[]),ft=o.useCallback(O=>{const z=w.current;if(!z)return;const q=z.getPanel(O),re=D.current[O];if(!q||!re||re.kind==="grid")return;if(q.group.model.location.type===re.kind){delete D.current[O],et();return}if(re.kind==="floating"){z.addFloatingGroup(q,{x:re.position.left??24,y:re.position.top??24,width:re.position.width,height:re.position.height}),delete D.current[O],et();return}delete D.current[O],et()},[et]);o.useEffect(()=>(b==null||b({setShortcutForActiveTab:Oe,restoreHiddenTabToSavedLocation:ft,activateConversationTab:oe,resetAllPanelsToMain:xe,activatePreviousTabInGroup:()=>le(-1),activateNextTabInGroup:()=>le(1),floatActiveTab:()=>{const O=pe();O&&ve(O)},popoutActiveTab:()=>{const O=pe();O&&ce(O)},dockActiveTab:()=>{const O=pe();O&&(J(O)?fe(O):ae(O)&&je(O))},splitActiveTabRight:()=>G("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>G("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Y("left"),focusRightPane:()=>Y("right"),focusUpPane:()=>Y("above"),focusDownPane:()=>Y("below"),moveActiveTabToLeftPane:()=>G("left"),moveActiveTabToRightPane:()=>G("right"),moveActiveTabToUpPane:()=>G("above"),moveActiveTabToDownPane:()=>G("below")}),()=>b==null?void 0:b(null)),[le,je,ve,Y,pe,ae,J,G,fe,ce,b,xe,ft,oe,Oe]),o.useEffect(()=>()=>{var O;(O=$.current)==null||O.call($),$.current=null},[]);const pt=o.useCallback(O=>{var q,re;w.current=O.api,(q=$.current)==null||q.call($),$.current=null;const z=Lh(j);if(B.current=(z==null?void 0:z.activeTabId)??null,z!=null&&z.layout&&O.api.fromJSON(z.layout,{reuseExistingPanels:!1}),T.current=pi({hasStoredLayout:!!(z!=null&&z.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(yi(O.api,e),vi(O.api,e,p)),O.api.totalPanels===0&&e.length>0){const E=ib(O.api,e,k);if(E){const X=O.api.getPanel(E);X&&Le(X)}}else!T.current&&!Be(k)&&Fe();if(_.current=!0,O.api.onDidActivePanelChange(E=>{var ee;if(B.current=(E==null?void 0:E.id)??null,F.current=!0,ge(),E&&Rt(E.id)){const ne=((ee=E.params)==null?void 0:ee.routeId)||E.id.slice(7),we=Pt(e,ne);S((we==null?void 0:we.tabKey)??null),Ye();return}if(S((E==null?void 0:E.id)??null),Ye(),!E)return;const X=H.get(E.id);(X==null?void 0:X.streamSource)==="agent-stream"&&X.agentType&&M(X.routeId,yc(),{agentType:X.agentType,...X.sessionId&&{targetSessionId:X.sessionId}}).catch(()=>{})}),O.api.onDidLayoutChange(()=>{Ye(),ge(),P(E=>E+1)}),rb()){const E=Se=>({clientX:Se.clientX,clientY:Se.clientY}),X=Se=>{const Pe=Se==null?void 0:Se.getBoundingClientRect();return Pe?{left:Pe.left,right:Pe.right,top:Pe.top,bottom:Pe.bottom}:null},ee=Se=>{var Ee;const Pe=(Ee=v.current)==null?void 0:Ee.getBoundingClientRect();return Pe?Se.clientX<Pe.left||Se.clientX>Pe.right||Se.clientY<Pe.top||Se.clientY>Pe.bottom:!1},ne=sb({detachDelayMs:Il,onDetach:({panelId:Se,clientX:Pe,clientY:Ee})=>{var ht,bt;const Ie=O.api.getPanel(Se);if(!Ie)return;try{if(Ie.group.model.location.type!=="grid")return}catch{return}const Ge=(ht=v.current)==null?void 0:ht.getBoundingClientRect(),Ze=(bt=Ie.group.element)==null?void 0:bt.getBoundingClientRect(),it=Math.round(Math.min(Math.max((Ze==null?void 0:Ze.width)??600,360),720)),lt=Math.round(Math.min(Math.max((Ze==null?void 0:Ze.height)??500,260),640));O.api.addFloatingGroup(Ie,{x:Ge?Math.max(0,Pe-Ge.left-32):void 0,y:Ge?Math.max(0,Ee-Ge.top-18):void 0,width:it,height:lt}),Ie.api.setActive(),Ye(),ge(),P(ze=>ze+1)}}),we=[O.api.onWillDragPanel(Se=>{if(!(Se.nativeEvent.defaultPrevented||Se.nativeEvent.shiftKey)){try{if(Se.panel.group.model.location.type!=="grid")return}catch{return}ne.startDrag({panelId:Se.panel.id,selfPanelBounds:X(Se.panel.group.element),...E(Se.nativeEvent)})}}),O.api.onWillShowOverlay(Se=>{if(ne.hasDetached()){Se.preventDefault();return}ne.markDockTarget(E(Se.nativeEvent))}),O.api.onWillDrop(Se=>{if(ne.hasDetached()){Se.preventDefault(),ne.endDrag();return}ne.markDockTarget(E(Se.nativeEvent))}),O.api.onDidDrop(()=>ne.endDrag()),O.api.onUnhandledDragOverEvent(Se=>{ne.isDragging()&&ne.markSelfPanel(E(Se.nativeEvent))})],Ae=Se=>{if(!ne.isDragging())return;const Pe=E(Se);ee(Pe)&&ne.markNonSelfPanel(Pe)},_e=()=>ne.endDrag();window.addEventListener("dragover",Ae,!0),window.addEventListener("drop",_e,!0),window.addEventListener("dragend",_e,!0),$.current=()=>{ne.dispose();for(const Se of we)Se.dispose();window.removeEventListener("dragover",Ae,!0),window.removeEventListener("drop",_e,!0),window.removeEventListener("dragend",_e,!0)}}O.api.onDidAddGroup(E=>{requestAnimationFrame(()=>{var X,ee;try{const ne=(X=E.element)==null?void 0:X.ownerDocument;if(!ne||ne===document)return;(ee=ne.getElementById("dv-popout-window"))==null||ee.classList.add("adhdev-dockview");const we=document.documentElement.getAttribute("data-theme");we&&ne.documentElement.setAttribute("data-theme",we),ne.body.className=document.body.className;const Ae=document.documentElement.getAttribute("style");Ae&&ne.documentElement.setAttribute("style",Ae)}catch{}ge(),P(ne=>ne+1)})}),S(((re=O.api.activePanel)==null?void 0:re.id)??null)},[Le,Be,H,r,d,j,S,Ye,k,p,M,ge,e]);o.useLayoutEffect(()=>{const O=w.current;if(!O||!_.current||T.current&&pi({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const z=L.current,q=new Set(z),re=e.map(_e=>_e.tabKey),E=new Set(re),X=eb({previousVisibleConversationCount:z.length,visibleConversationCount:e.length,ides:r});let ee=!1;for(const _e of z)E.has(_e)||X||(D.current[_e]=ut(_e),ee=!0);ee&&et(),X||(yi(O,e),vi(O,e,p));const ne=re.filter(_e=>!q.has(_e));let we=!1;for(const _e of ne){const Se=O.getPanel(_e),Pe=D.current[_e];if(!Se||!Pe||Pe.kind==="grid")continue;if(Se.group.model.location.type===Pe.kind){delete D.current[_e],we=!0;continue}if(Pe.kind==="floating"){O.addFloatingGroup(Se,{x:Pe.position.left??24,y:Pe.position.top??24,width:Pe.position.width,height:Pe.position.height}),delete D.current[_e],we=!0;continue}}if(we&&et(),L.current=re,k&&Be(k))return;!O.activePanel&&O.panels[0]&&Le(O.panels[0]),!!(O.activePanel&&O.getPanel(O.activePanel.id))||Fe()},[Le,Be,Fe,r,d,et,ut,k,p,e]),o.useEffect(()=>{_.current&&Be(k)},[Be,k]),o.useEffect(()=>{const O=q=>{const re=q.target;if(!re)return;const E=re.querySelector("[data-tab-key]")||re.closest("[data-tab-key]");if(E){const X=E.getAttribute("data-tab-key");if(X&&q.dataTransfer){const ee=re.closest(".dv-tab")||E.closest(".dv-tab")||E;q.dataTransfer.effectAllowed="move",q.dataTransfer.setData("text/tab-key",X),ee instanceof HTMLElement&&q.dataTransfer.setDragImage(ee,Math.max(12,Math.round(ee.clientWidth/2)),Math.max(10,Math.round(ee.clientHeight/2)))}}};window.addEventListener("dragstart",O);const z=gi(w.current);for(const q of z)q.addEventListener("dragstart",O);return()=>{window.removeEventListener("dragstart",O);for(const q of z)q.removeEventListener("dragstart",O)}},[K]),o.useEffect(()=>{var z;const O=(z=v.current)==null?void 0:z.querySelector(".adhdev-dockview");O instanceof HTMLElement&&qn(O,I),Z(),ge()},[ge,Z,I]),o.useEffect(()=>{ge()},[ge]),o.useEffect(()=>{const O=z=>{if(z.defaultPrevented||se)return;const q=He(z);if(!q)return;const re=z.metaKey||z.ctrlKey||z.altKey;Ta(z.target)&&!re||nn(ue).setActiveTabShortcut!==q||(z.preventDefault(),z.stopPropagation(),Oe())};return window.addEventListener("keydown",O,!0),()=>window.removeEventListener("keydown",O,!0)},[He,ue,se,Oe]),o.useEffect(()=>{const O=v.current;if(!O)return;const z=q=>{var ne,we;if(!q.isTrusted)return;const re=(we=(ne=q.target)==null?void 0:ne.closest)==null?void 0:we.call(ne,".dv-scrollable");if(!re)return;q.preventDefault(),q.stopPropagation();const E=Math.abs(q.deltaX),X=Math.abs(q.deltaY),ee=E>X?q.deltaX:q.deltaY;re.dispatchEvent(new WheelEvent("wheel",{deltaY:ee,deltaMode:q.deltaMode,bubbles:!1,cancelable:!0}))};return O.addEventListener("wheel",z,{passive:!1,capture:!0}),()=>O.removeEventListener("wheel",z,{capture:!0})},[]),o.useEffect(()=>{const O=gi(w.current);if(O.length===0)return;const z=O.map(q=>{let re=[],E=null;const X=()=>{E!=null&&q.clearTimeout(E),E=null,re=[]},ee=()=>{E!=null&&q.clearTimeout(E),E=q.setTimeout(()=>{E=null,re=[]},1200)},ne=Ae=>{if(!Ae.ctrlKey&&!Ae.metaKey&&!Ae.altKey)return;const _e=He(Ae);if(!_e)return;const Se=kl();for(const[Pe,Ee]of Object.entries(Se))if(e.some(Ie=>Ie.tabKey===Pe)&&Ee===_e){Ae.preventDefault(),oe(Pe);return}},we=Ae=>{if(Ae.defaultPrevented||se)return;const _e=He(Ae);if(!_e)return;const Se=Ae.metaKey||Ae.ctrlKey||Ae.altKey;if(Ta(Ae.target))return;const Pe=nn(ue),Ee=Object.entries(Pe).filter(([ze,ye])=>!!ye&&(ze==="splitActiveTabRight"||ze==="splitActiveTabDown"||ze==="floatActiveTab"||ze==="popoutActiveTab"||ze==="dockActiveTab"||ze==="focusLeftPane"||ze==="focusRightPane"||ze==="focusUpPane"||ze==="focusDownPane"||ze==="moveActiveTabToLeftPane"||ze==="moveActiveTabToRightPane"||ze==="moveActiveTabToUpPane"||ze==="moveActiveTabToDownPane"||ze==="selectPreviousGroupTab"||ze==="selectNextGroupTab"||ze==="setActiveTabShortcut"||ze==="hideCurrentTab")),Ie=Se?[_e]:[...re.slice(-1),_e].slice(-2),Ge=Ie.join(" "),Ze=Ie[Ie.length-1],it=Ee.find(([,ze])=>ze===Ge);if(it){Ae.preventDefault(),X(),W(it[0]);return}if(Ee.some(([,ze])=>ze.startsWith(`${Ge} `))){Ae.preventDefault(),re=Ie,ee();return}const ht=Ee.find(([,ze])=>ze===Ze);if(ht){Ae.preventDefault(),X(),W(ht[0]);return}if(Ee.some(([,ze])=>ze.startsWith(`${Ze} `))){Ae.preventDefault(),re=[Ze],ee();return}X()};return q.addEventListener("keydown",ne),q.addEventListener("keydown",we),()=>{X(),q.removeEventListener("keydown",ne),q.removeEventListener("keydown",we)}});return()=>{for(const q of z)q()}},[He,ue,K,oe,se,W,e]);const Ne=I==="light"?ca:la,Ue=((tt=(Ve=(Xe=w.current)==null?void 0:Xe.activePanel)==null?void 0:Ve.group.element)==null?void 0:tt.ownerDocument)??document;return t.jsxs(Rl.Provider,{value:Ce,children:[t.jsx("div",{ref:v,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(vd,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:cb,remote:lb},defaultTabComponent:ub,watermarkComponent:db,onReady:pt,singleTabMode:"default",tabAnimation:"smooth",theme:Ne,popoutUrl:"/popout.html"})}),C&&rr.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:C.x,top:C.y},children:Te.map(O=>{if(O.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},O.id);let z=t.jsx(hu,{size:13,className:"shrink-0 opacity-70"}),q=()=>{};switch(O.id){case"dockInWindow":case"dockBackToGrid":z=t.jsx(bu,{size:13,className:"shrink-0 opacity-70"}),q=()=>{je(C.tabKey),A(null)};break;case"moveBackToMain":z=t.jsx(pu,{size:13,className:"shrink-0 opacity-70"}),q=()=>{fe(C.tabKey),A(null)};break;case"floatAsPanel":z=t.jsx(xu,{size:13,className:"shrink-0 opacity-70"}),q=()=>{ve(C.tabKey),A(null)};break;case"openInNewWindow":z=t.jsx(fu,{size:13,className:"shrink-0 opacity-70"}),q=()=>{ce(C.tabKey),A(null)};break;case"setShortcut":q=re=>{re.stopPropagation(),Re(C.tabKey),A(null)};break;case"removeShortcut":z=t.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),q=()=>{const re={...ke};delete re[C.tabKey],$e(re),A(null)};break;case"hideTab":z=t.jsx(Ea,{size:13,className:"shrink-0 opacity-70"}),q=()=>{me(C.tabKey),A(null)};break}return t.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${O.tone==="muted"?"text-text-muted":""}`,onMouseDown:ab,onClick:q,children:[z,t.jsx("span",{className:"flex-1 min-w-0",children:O.label}),O.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:O.shortcut}):null]},O.id)})}),C.sourceDocument.body),se&&rr.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:()=>Re(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:O=>O.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",ue?"⌘+1":"Ctrl+1",", ",ue?"⌥+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"})]})}),Ue.body)]})}const Ll="adhdev-recent-launch-args-v1",fb=8;function pb(e){return String(e||"").trim().replace(/\s+/g," ")}function _l(e,s){return`${e.trim()}::${s.trim()}`}function Pl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Ll)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function hb(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Ll,JSON.stringify(e))}catch{}}function Dl(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Pl().byKey[_l(r,n)])==null?void 0:i.items)||[]}function El(e,s,r){var u;const n=String(e||"").trim(),a=String(s||"").trim(),i=pb(r);if(!n||!a||!i)return;const c=Pl(),l=_l(n,a),d=((u=c.byKey[l])==null?void 0:u.items)||[],m=[i,...d.filter(f=>f!==i)].slice(0,fb);c.byKey[l]={items:m},hb(c)}function $l(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Hr({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 xb({savedSessionsLoading:e,savedSessionsLoaded:s,savedSessionsCount:r=0}){return e?"Refreshing saved history…":s?r>0?`${r} saved ${r===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function Bl({busy:e,savedSessionsLoading:s,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:i,onRefresh:c,onOpenHistory:l,onClearSelection:d}){const m=i?vl(i):null,u=xb({savedSessionsLoading:s,savedSessionsLoaded:n,savedSessionsCount:a});return t.jsxs(Hr,{title:"Saved history",description:Za(),action:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||s,onClick:c,children:s?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:l,children:xp()})]}),children:[m?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:m.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),t.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:"Clear"})]})}):t.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&t.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Kl({setup:e,providerName:s,className:r=""}){return e?t.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[t.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",s?` for ${s}`:""]}),e.instructions&&t.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&t.jsxs("span",{children:["Server: ",t.jsx("code",{children:e.serverName})]}),e.configFormat&&t.jsxs("span",{children:["Format: ",t.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&t.jsxs("span",{children:["Config path: ",t.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&t.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&t.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}function Yn(e){var n;if(!e)return null;const s=e.availableProviders||[];return s.some(a=>ps(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(a=>ps(a,"acp"))?"acp":null}function _r(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function bb({machines:e,ides:s,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListMeshes:l,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var ze,ye;const u=mr(),f=o.useMemo(()=>[...e].sort(Oa),[e]),[b,S]=o.useState(((ze=f[0])==null?void 0:ze.id)||""),g=o.useMemo(()=>f.find(U=>U.id===b)||f[0],[b,f]),h=o.useMemo(()=>((g==null?void 0:g.workspaces)||[]).map(U=>({id:U.id,path:U.path,label:U.label})),[g]),k=(g==null?void 0:g.defaultWorkspaceId)||null,[p,x]=o.useState("workspace"),[y,N]=o.useState(""),[j,I]=o.useState(""),[M,w]=o.useState([]),[v,$]=o.useState(""),[_,T]=o.useState(!1),[F,B]=o.useState(null),[L,C]=o.useState(""),[A,K]=o.useState(Yn(f[0])),[P,D]=o.useState(""),[H,Q]=o.useState(""),[be,de]=o.useState([]),[te,Z]=o.useState(""),[ce,fe]=o.useState([]),[J,me]=o.useState(!1),[ve,ae]=o.useState(!1),[pe,je]=o.useState(""),[xe,ge]=o.useState(!1),[oe,le]=o.useState(()=>gt()),[ie,Y]=o.useState(null),[G,ue]=o.useState(!1),[ke,se]=o.useState(""),[Re,$e]=o.useState(null),[Oe,He]=o.useState(!1),[W,Ce]=o.useState(""),[Te,Le]=o.useState([]),[Be,Fe]=o.useState(!1),[Ye,et]=o.useState(""),[ut,ft]=o.useState(!1),pt=o.useRef(null),Ne=o.useRef(0);o.useEffect(()=>{var U;!b&&((U=f[0])!=null&&U.id)&&S(f[0].id)},[b,f]),o.useEffect(()=>{!g||!(!g.workspaces||!g.availableProviders||!g.detectedIdes||!g.recentLaunches)||u(g.id,{minFreshMs:3e4}).catch(()=>{})},[u,g]);const Ue=o.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(U=>ps(U,"cli")),[g]),Xe=o.useMemo(()=>((g==null?void 0:g.availableProviders)||[]).filter(U=>ps(U,"acp")),[g]),Ve=o.useMemo(()=>((g==null?void 0:g.detectedIdes)||[]).map(U=>({id:U.type,label:U.name||U.type,meta:U.running?"Detected locally":"Available to open"})),[g]),tt=o.useMemo(()=>A==="cli"?Ue.map(U=>({id:U.type,label:U.displayName||U.type,meta:"CLI provider"})):A==="acp"?Xe.map(U=>({id:U.type,label:U.displayName||U.type,meta:"ACP provider"})):Ve,[Xe,A,Ue,Ve]),O=o.useMemo(()=>M.find(U=>U.id===v)||null,[M,v]),z=o.useMemo(()=>Ue.find(U=>U.type===P)||null,[Ue,P]),q=o.useMemo(()=>xl(z==null?void 0:z.meshCoordinator,{meshId:(O==null?void 0:O.id)||"",workspace:(O==null?void 0:O.workspace)||""}),[z,O]),re=Re||q,E=o.useCallback(async U=>{T(!0),C("");try{const R=await l(U);w(R),$(V=>{var he;return R.some(De=>De.id===V)?V:((he=R[0])==null?void 0:he.id)||""}),B(U)}catch(R){w([]),$(""),B(U),C(R instanceof Error?R.message:"Could not load meshes")}finally{T(!1)}},[l]);o.useEffect(()=>{var R;if(!g)return;if(pt.current!==g.id){pt.current=g.id,x("workspace"),N(k||((R=h[0])==null?void 0:R.id)||"__home__"),I(""),w([]),$(""),B(null),C(""),K(Yn(g)),D(""),Q(""),Z(""),fe([]),ae(!1),je(""),le(gt()),se(""),$e(null);return}N(V=>{var he;return V==="__custom__"||V==="__home__"||h.some(De=>De.id===V)?V:k||((he=h[0])==null?void 0:he.id)||"__home__"}),K(V=>V==="ide"&&Ve.length>0||V==="cli"&&Ue.length>0||V==="acp"&&Xe.length>0?V:Yn(g))},[Xe.length,Ue.length,k,Ve.length,g,h]),o.useEffect(()=>{!g||p!=="mesh"||F===g.id||_||E(g.id)},[E,F,_,g,p]),o.useEffect(()=>{p==="mesh"&&A!=="cli"&&Ue.length>0&&K("cli")},[A,Ue.length,p]),o.useEffect(()=>{var U;A&&(tt.some(R=>R.id===P)||D(((U=tt[0])==null?void 0:U.id)||""))},[A,tt,P]),o.useEffect(()=>{$e(null)},[g==null?void 0:g.id,v,P,p]);const X=o.useCallback(async(U,R)=>{const V=Ne.current+1;return Ne.current=V,me(!0),je(""),m(U,R).then(he=>{Ne.current===V&&fe(he)}).catch(he=>{Ne.current===V&&(fe([]),je(he instanceof Error?he.message:"Could not load saved sessions"))}).finally(()=>{Ne.current===V&&(me(!1),ae(!0))})},[m]),ee=o.useCallback((U,R)=>{de(Dl(U,R))},[]);o.useEffect(()=>{Ne.current+=1,Z(""),le(gt()),!g||!P||A==="ide"?de([]):ee(g.id,P),ae(!1),fe([]),je(""),me(!1)},[A,ee,X,g,P]),o.useEffect(()=>{if(!te)return;const U=ce.find(R=>R.providerSessionId===te);U!=null&&U.canResume||Z("")},[ce,te]);const ne=y==="__custom__"?j.trim():y==="__home__"?"":((ye=h.find(U=>U.id===y))==null?void 0:ye.path)||"",we=o.useMemo(()=>g?s.filter(U=>U.id!==g.id&&U.daemonId===g.id).map(U=>U.workspace):[],[s,g]),Ae=o.useMemo(()=>((g==null?void 0:g.recentLaunches)||[]).map(U=>U.workspace),[g]),_e=o.useCallback(U=>{const R=String(U.workspace||"").trim();if(!R)return;const V=h.find(he=>_r(he.path)===_r(R));if(V){N(V.id),I("");return}N("__custom__"),I(R)},[h]),Se=o.useCallback(U=>{const R=String(U.workspace||"").trim();if(!R)return{workspaceId:null,workspacePath:null};const V=h.find(he=>_r(he.path)===_r(R));return V?{workspaceId:V.id,workspacePath:null}:{workspaceId:null,workspacePath:R}},[h]),Pe=o.useMemo(()=>ce.find(U=>U.providerSessionId===te)||null,[ce,te]),Ee=o.useMemo(()=>{var R;if(A!=="cli"||!g||!P)return null;const U=((R=Ue.find(V=>V.type===P))==null?void 0:R.displayName)||P;return{routeId:g.id,daemonId:g.id,providerSessionId:te||void 0,transport:"pty",mode:"chat",agentName:U,agentType:P,status:"idle",title:U,messages:[],ideType:P,workspaceName:ne,workspacePath:ne,displayPrimary:U,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${g.id}:${P}`,machineName:Ct(g,{fallbackId:g.id})}},[A,Ue,ne,g,te,P]),Ie=o.useCallback(()=>{var R;if(!g)return;N("__custom__"),He(!0),et("");const U=xn(g.platform,hn(j.trim(),ne,we,Ae,g.defaultWorkspacePath,(R=h.find(V=>V.id===k))==null?void 0:R.path,h.map(V=>V.path)));Fe(!0),n(g.id,U).then(V=>{Ce(V.path),I(V.path),Le(V.directories)}).catch(V=>{et(V instanceof Error?V.message:"Could not load folder")}).finally(()=>Fe(!1))},[j,k,Ae,we,n,ne,g,h]),Ge=o.useCallback(U=>{g&&(Fe(!0),et(""),n(g.id,U).then(R=>{Ce(R.path),I(R.path),Le(R.directories)}).catch(R=>{et(R instanceof Error?R.message:"Could not load folder")}).finally(()=>Fe(!1)))},[n,g]),Ze=o.useCallback(async()=>{if(!g||!ne)return;ft(!0),se("");const U=await a(g.id,ne);if(ft(!1),!U.ok){se(U.error||"Could not save workspace");return}se("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,ne,g]),it=o.useCallback(async()=>{if(!g)return;if(p==="mesh"){if(!v||!P)return;ue(!0),se(""),$e(null);const V=await d(g.id,v,P);if(ue(!1),!V.ok){if(V.code==="mesh_coordinator_manual_mcp_setup_required"&&V.manualSetup){$e(V.manualSetup),se("Manual MCP setup required before this provider can act as mesh coordinator.");return}se(V.error||"Could not start mesh coordinator");return}r();return}if(!A||!P)return;ue(!0),se("");const U=H.trim()?H.trim().split(/\s+/).filter(Boolean):[],R=A==="ide"?await i(g.id,P,{workspacePath:ne||null}):await c(g.id,A,P,{workspaceId:y!=="__home__"&&y!=="__custom__"?y:null,workspacePath:y==="__custom__"&&ne||null,resumeSessionId:A==="cli"&&te?te:null,cliArgs:U});if(ue(!1),!R.ok){se(R.error||"Could not start session");return}A!=="ide"&&H.trim()&&(El(g.id,P,H),ee(g.id,P)),r()},[A,H,ee,r,i,d,c,ne,g,v,te,P,y,p]),lt=p==="mesh"?"Start mesh coordinator":A?Hc(A,A==="cli"&&!!te):"Start",ht=p==="mesh"?"Starting coordinator…":A?Uc(A,A==="cli"&&!!te):"Starting…",bt=f.length>5;return g?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:t.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh or resume saved history."})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:r,"aria-label":"Close new session dialog",children:t.jsx(vt,{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(Hr,{title:"Machine",children:bt?t.jsx("select",{"aria-label":"Machine",value:g.id,onChange:U=>S(U.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:G,children:f.map(U=>t.jsx("option",{value:U.id,children:Ct(U,{fallbackId:U.id})},U.id))}):t.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:f.map(U=>{const R=Ct(U,{fallbackId:U.id}),V=g.id===U.id;return t.jsxs("button",{type:"button","aria-label":`Select machine ${R}`,"aria-pressed":V,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${V?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>S(U.id),disabled:G,title:R,children:[t.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${U.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),t.jsx("span",{className:"truncate",children:R})]},U.id)})})}),t.jsxs(Hr,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:p==="workspace"?t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ie,disabled:G,children:"Browse…"}):void 0,children:[t.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(U=>t.jsxs("button",{type:"button",role:"radio","aria-checked":p===U.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${p===U.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{x(U.id),se(""),U.id==="mesh"&&g&&F!==g.id&&!_&&E(g.id)},disabled:G,children:[t.jsx("div",{className:"text-sm font-semibold",children:U.label}),t.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:U.desc})]},U.id))}),p==="workspace"?t.jsxs(t.Fragment,{children:[t.jsxs("select",{value:y,onChange:U=>{const R=U.target.value;N(R),R==="__custom__"?Ie():se("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:G,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),h.map(U=>t.jsxs("option",{value:U.id,children:[U.id===k?"⭐ ":"",mn(U.path,U.label)||U.path]},U.id)),t.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y==="__home__"?"Launch without a workspace.":ne||"Select a workspace folder."}),y==="__custom__"&&ne&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ie,disabled:G,children:[t.jsx(us,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ze,disabled:G||ut,children:ut?"Saving…":"Save workspace"})]})]}):t.jsxs("div",{className:"space-y-3",children:[_&&t.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!_&&L&&t.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:L}),!_&&!L&&M.length===0&&t.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),M.length>0&&t.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:M.map(U=>t.jsxs("button",{type:"button",role:"radio","aria-checked":v===U.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===U.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(U.id),disabled:G,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:U.name}),t.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[U.repoIdentity||"Repo mesh",typeof U.nodesCount=="number"?` · ${U.nodesCount} node${U.nodesCount===1?"":"s"}`:""]}),U.workspace&&t.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",U.workspace]})]},U.id))}),O&&t.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator 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:Ue.length>0},{id:"ide",label:"IDE",enabled:Ve.length>0},{id:"acp",label:"ACP",enabled:Xe.length>0}].map(U=>{const R=U.enabled&&(p!=="mesh"||U.id==="cli");return t.jsx("button",{type:"button",className:`btn btn-sm ${A===U.id?"btn-primary":"btn-secondary"}`,onClick:()=>K(U.id),disabled:!R||G,children:U.label},U.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:A==="ide"?"Choose IDE":A==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[tt.map(U=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===U.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>D(U.id),disabled:G,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:U.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:U.meta})]},U.id)),tt.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."})]})]}),p==="mesh"&&re&&t.jsx(Kl,{setup:re,providerName:(z==null?void 0:z.displayName)||(z==null?void 0:z.name)||P}),p!=="mesh"&&A!=="ide"&&t.jsxs(Hr,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:H,onChange:U=>Q(U.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:G}),be.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:be.map(U=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>Q(U),disabled:G,title:U,children:U},U))})]}),p!=="mesh"&&A==="cli"&&t.jsx(Bl,{busy:G,savedSessionsLoading:J,savedSessionsError:pe,selectedSession:Pe,onRefresh:()=>{!g||!P||X(g.id,P)},onOpenHistory:()=>{!g||!P||(ge(!0),$l({hasLoadedInitialResults:ve,isLoading:J})&&X(g.id,P))},onClearSelection:()=>Z("")}),ke&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ke.includes("saved")||ke.includes("requested")||ke.includes("Manual MCP setup")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:ke})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:G,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:it,disabled:G||(p==="mesh"?!v||!P||A!=="cli"||_:!A||!P||y==="__custom__"&&!ne),children:[t.jsx(cn,{size:14}),G?ht:lt]})]})]})}),Oe&&t.jsx(gn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:W,directories:Te,busy:Be,error:Ye,onClose:()=>He(!1),onNavigate:Ge,onConfirm:U=>{I(U),Ce(U),N("__custom__"),He(!1)}}),xe&&Ee&&t.jsx(so,{activeConv:Ee,ides:[],isCreatingChat:!1,isRefreshingHistory:J,savedSessions:ce,isSavedSessionsLoading:J,isResumingSavedSessionId:ie,savedHistoryFilters:oe,missingWorkspaceResumePath:ne||null,onSavedHistoryFiltersChange:le,onClose:()=>ge(!1),onNewChat:()=>{Z(""),ge(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!g||!P||X(g.id,P)},onResumeSavedSession:U=>{if(!g||!P||ie||!U.canResume)return;const R=Se(U);Z(U.providerSessionId),_e(U),Y(U.providerSessionId),ge(!1),ue(!0),se(""),c(g.id,"cli",P,{workspaceId:R.workspaceId,workspacePath:R.workspacePath,resumeSessionId:U.providerSessionId}).then(V=>{if(!V.ok){se(V.error||"Could not resume session");return}r()}).finally(()=>{ue(!1),Y(V=>V===U.providerSessionId?null:V)})}})]}):null}function gb(e,s){const{sendCommand:r}=xt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);o.useEffect(()=>{if(!e||!s){a(null);return}c(!0),r(e,"git_remote_url",{workspace:s}).then(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>c(!1))},[e,s,r]);const l=yb(n);return{remoteUrl:n,githubUrl:l,loading:i}}function yb(e){if(!e)return null;const s=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(s)return`https://github.com/${s[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const Wl=5e3;function vb(e){return`git:${e}`}function wb({workspace:e,includeDiffSummary:s=!1,intervalMs:r=Wl}){return{type:"subscribe",topic:"workspace.git",key:vb(e),params:{workspace:e,includeDiffSummary:s,intervalMs:r}}}function po(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function hs(e,s){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const r=e;if(typeof r.error=="string"&&r.error.trim())return r.error;if(typeof r.message=="string"&&r.message.trim())return r.message}return s}function jb(e){const s=po(e);return(s==null?void 0:s.success)===!1?{status:null,error:hs(s,"Git status request failed")}:s!=null&&s.status?{status:s.status,error:null}:{status:null,error:hs(s,"Git status response did not include status")}}function kb(e){const s=po(e);return(s==null?void 0:s.success)===!1?{diffSummary:null,error:hs(s,"Git diff summary request failed")}:s!=null&&s.diffSummary?{diffSummary:s.diffSummary,error:null}:{diffSummary:null,error:hs(s,"Git diff summary response did not include diffSummary")}}function Xn(e){return e===void 0||typeof e=="boolean"}function Sb(e){if(!e||typeof e!="object")return!1;const s=e;return typeof s.path=="string"&&typeof s.diff=="string"&&Xn(s.binary)&&Xn(s.truncated)&&Xn(s.staged)}function Nb(e){const s=po(e);return(s==null?void 0:s.success)===!1?{diff:null,error:hs(s,"Git file diff request failed")}:Sb(s==null?void 0:s.diff)?{diff:s.diff,error:null}:{diff:null,error:hs(s,"Git file diff response did not include a valid diff object")}}function Cb({daemonId:e,workspace:s,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Wl}){const{sendCommand:i,sendData:c}=xt(),l=typeof s=="string"?s.trim():"",d=!!(r&&e&&l),[m,u]=o.useState(null),[f,b]=o.useState(null),[S,g]=o.useState(!1),[h,k]=o.useState(null),p=o.useCallback(async()=>{if(!(!d||!e||!l)){g(!0),k(null);try{const y=jb(await i(e,"git_status",{workspace:l}));if(y.error){u(null),b(null),k(y.error);return}if(u(y.status),!n){b(null);return}const N=kb(await i(e,"git_diff_summary",{workspace:l}));if(N.error){b(null),k(N.error);return}b(N.diffSummary)}catch(y){k(hs(y,"Git status request failed"))}finally{g(!1)}}},[d,e,n,i,l]),x=o.useMemo(()=>l?wb({workspace:l,includeDiffSummary:n,intervalMs:a}):null,[n,a,l]);return o.useEffect(()=>{if(!d||!e||!l||!x){u(null),b(null),g(!1),k(null);return}const y=c?Ft.subscribe({sendData:c},e,x,N=>{var j,I;N.workspace===l&&(u(N.status),b(N.diffSummary??null),k(((j=N.status)==null?void 0:j.error)||((I=N.diffSummary)==null?void 0:I.error)||null),g(!1))},{retryIntervalMs:1e3}):null;return p(),()=>{y==null||y()}},[d,e,p,x,c,l]),{status:m,diffSummary:f,loading:S,error:h,refresh:p}}const Tb={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},Mb={added:"text-emerald-400",modified:"text-orange-400",deleted:"text-red-400",renamed:"text-sky-400",copied:"text-sky-400",untracked:"text-zinc-400",conflict:"text-red-400 font-bold"};function wi(e){return e.split("/").pop()??e}function Ab(e){const s=e.lastIndexOf("/");return s>0?e.slice(0,s):""}function Ib({files:e,truncated:s,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?t.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):t.jsxs("div",{className:`flex flex-col ${a}`,children:[t.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(i=>{const c=n===i.path,l=Tb[i.status]??"?",d=Mb[i.status]??"text-zinc-400",m=Ab(i.path),u=wi(i.path),f=i.staged?t.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return t.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${c?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(i),children:[t.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:i.status,children:l}),t.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&t.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),t.jsx("span",{className:"text-text-primary",children:u}),i.oldPath&&t.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",wi(i.oldPath)]}),f]}),!i.binary&&(i.insertions>0||i.deletions>0)&&t.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[i.insertions>0&&t.jsxs("span",{className:"text-emerald-500",children:["+",i.insertions]}),i.insertions>0&&i.deletions>0&&t.jsx("span",{className:"text-text-secondary",children:" "}),i.deletions>0&&t.jsxs("span",{className:"text-red-400",children:["-",i.deletions]})]}),i.binary&&t.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${i.path}-${i.staged?"S":"U"}`)})}),s&&t.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",t.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function Rb(e,s){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-emerald-500/10 text-emerald-300":e.startsWith("-")&&!e.startsWith("---")?r="bg-red-500/10 text-red-300":e.startsWith("@@")?r="text-sky-400":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(r="text-text-secondary"),t.jsx("div",{className:`px-3 ${r}`,children:t.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},s)}function Lb({diff:e,binary:s,truncated:r,loading:n,error:a,className:i=""}){const c=o.useRef(null);if(o.useEffect(()=>{c.current&&(c.current.scrollTop=0)},[e]),n)return t.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${i}`,children:"Loading diff…"});if(a)return t.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${i}`,children:a});if(s)return t.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"Binary file — diff not available."});if(!e)return t.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"No diff available."});const l=e.split(`
|
|
63
|
-
`);return t.jsxs("div",{ref:c,className:`overflow-auto ${i}`,children:[t.jsx("div",{className:"py-1",children:l.map((d,m)=>Rb(d,m))}),r&&t.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",t.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function _b(e,s){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${s.files.length} file(s) +${s.totalInsertions}/-${s.totalDeletions}`);const n={};for(const a of s.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,i]of Object.entries(n))r.push(`${a}: ${i.slice(0,5).join(", ")}${i.length>5?` (+${i.length-5} more)`:""}`);return r.join(`
|
|
64
|
-
`)}function Ol({daemonId:e,workspace:s,onClose:r}){const{sendCommand:n}=xt(),{status:a,diffSummary:i,loading:c,error:l,refresh:d}=Cb({daemonId:e,workspace:s,includeDiffSummary:!0}),[m,u]=o.useState(null),[f,b]=o.useState(null),[S,g]=o.useState(""),[h,k]=o.useState(!1),[p,x]=o.useState(!1),[y,N]=o.useState(null),[j,I]=o.useState(null),{githubUrl:M}=gb(e,s),w=o.useCallback(async B=>{if(!((m==null?void 0:m.path)===B.path&&!m.loading)){u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const L=await n(e,"git_diff_file",{workspace:s,path:B.path,staged:B.staged}),C=Nb(L);if(C.error||!C.diff){u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C.error??"Failed to load diff"});return}u({path:B.path,diff:C.diff.diff,binary:C.diff.binary??!1,truncated:C.diff.truncated??!1,loading:!1,error:null})}catch(L){const C=L instanceof Error?L.message:"Failed to load diff";u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C})}}},[e,n,m,s]),v=o.useCallback(B=>{g(""),k(!1),N(null),I(null),b(B)},[]),$=o.useCallback(()=>{b(null),N(null),x(!1)},[]),_=o.useCallback(async()=>{var B,L,C;if(f){x(!0),N(null);try{let A;f==="checkpoint"?A=await n(e,"git_checkpoint",{workspace:s,message:S,includeUntracked:h}):f==="stash"?A=await n(e,"git_stash_push",{workspace:s,message:S,includeUntracked:h}):f==="stash_pop"?A=await n(e,"git_stash_pop",{workspace:s}):f==="checkout_files"&&m&&(A=await n(e,"git_checkout_files",{workspace:s,paths:[m.path]}));const K=(A==null?void 0:A.result)??A;if((K==null?void 0:K.success)===!1||K!=null&&K.error){N((K==null?void 0:K.error)??"Action failed"),x(!1);return}f==="checkpoint"?I(`Checkpoint created: ${((L=(B=K==null?void 0:K.checkpoint)==null?void 0:B.commit)==null?void 0:L.slice(0,7))??"done"}`):f==="stash"?I(`Stashed as ${((C=K==null?void 0:K.stash)==null?void 0:C.stashRef)??"stash@{0}"}`):f==="stash_pop"?I("Stash restored"):(I("File reverted"),u(null)),b(null),await d()}catch(A){N(A instanceof Error?A.message:"Action failed")}finally{x(!1)}}},[f,n,e,s,S,h,m,d]),T=!!(a!=null&&a.hasConflicts),F=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:B=>{B.target===B.currentTarget&&r()},children:t.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[t.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[t.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),t.jsx("p",{className:"truncate text-xs text-text-secondary",children:s}),M&&t.jsx("a",{href:`${M}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),t.jsx("button",{onClick:d,disabled:c,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),t.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:t.jsx(vt,{className:"h-4 w-4"})})]}),a&&t.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&t.jsxs("span",{title:a.headMessage??void 0,children:[t.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&t.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&t.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&t.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&t.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&t.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&t.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&t.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&t.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&t.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),F===0&&!a.error&&t.jsx("span",{className:"text-emerald-500",children:"clean"}),i&&i.files.length>0&&t.jsxs("span",{className:"text-text-secondary",children:[i.files.length," file",i.files.length!==1?"s":"",i.totalInsertions>0&&t.jsxs("span",{className:"text-emerald-500",children:[" +",i.totalInsertions]}),i.totalDeletions>0&&t.jsxs("span",{className:"text-red-400",children:[" -",i.totalDeletions]})]})]}),l&&t.jsx("div",{className:"shrink-0 border-b border-border/50 bg-red-500/10 px-4 py-2 text-xs text-red-400",children:l}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[c&&!i&&t.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),i&&t.jsx(Ib,{files:i.files,truncated:i.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:w}),!c&&!i&&!l&&t.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),t.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?t.jsx(Lb,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):t.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),j&&t.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[t.jsx("span",{children:j}),t.jsx("button",{onClick:()=>I(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[t.jsx("button",{onClick:()=>v("checkpoint"),disabled:T,title:T?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),t.jsx("button",{onClick:()=>v("stash"),disabled:T,title:T?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),t.jsx("button",{onClick:()=>v("stash_pop"),disabled:T||!(a!=null&&a.stashCount),title:T?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),t.jsx("button",{onClick:()=>v("checkout_files"),disabled:!m,title:m?`Revert changes to ${m.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),i&&i.files.length>0&&t.jsx("button",{onClick:()=>{const B=_b((a==null?void 0:a.branch)??null,i);navigator.clipboard.writeText(B),I("Copied to clipboard"),setTimeout(()=>I(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),f&&t.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:t.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[t.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[f==="checkpoint"&&"Create checkpoint commit",f==="stash"&&"Stash changes",f==="stash_pop"&&"Restore latest stash?",f==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(f==="checkpoint"||f==="stash")&&t.jsxs(t.Fragment,{children:[t.jsx("input",{type:"text",value:S,onChange:B=>g(B.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-alt px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),t.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:h,onChange:B=>k(B.target.checked)}),"Include untracked files"]})]}),y&&t.jsx("p",{className:"text-xs text-red-400",children:y}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx("button",{onClick:$,disabled:p,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),t.jsx("button",{onClick:_,disabled:p||(f==="checkpoint"||f==="stash")&&!S.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:p?"Working…":"Confirm"})]})]})})]})})}function Pb({isMobile:e,showMobileChatMode:s,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,d]=o.useState(!1),[m,u]=o.useState(!1),[f,b]=o.useState(!1),[S,g]=o.useState("quickstart"),[h,k]=o.useState("workspace"),p=o.useMemo(()=>!s&&!e,[s,e]),x=o.useCallback(w=>{a(w),w&&c(!1)},[]),y=o.useCallback(w=>{c(w),w&&a(!1)},[]),N=o.useCallback(()=>{g(r===0?"quickstart":"shortcuts"),k("workspace"),d(!0),a(!1),c(!1)},[r]),j=o.useCallback(()=>{d(!1)},[]),I=o.useCallback(()=>{u(!0)},[]),M=o.useCallback(()=>{u(!1)},[]);return o.useEffect(()=>{if(!p){b(!1);return}b(!0);const w=window.setTimeout(()=>{b(!1)},1e4);return()=>window.clearTimeout(w)},[p]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:f,guideTab:S,shortcutSection:h,isDesktopDashboard:p,setGuideTab:g,setShortcutSection:k,handleInboxOpenChange:x,handleHiddenOpenChange:y,handleOpenShortcutHelp:N,closeShortcutHelp:j,openNewSession:I,closeNewSession:M}}function Db(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 Eb(e){return e instanceof Error?e.message:String(e||"")}function $b(e){const s=Eb(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Bb({showMobileChatMode:e,isMobile:s,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:f,ides:b,actionLogs:S,sendDaemonCommand:g,setActionLogs:h,setCliViewModeOverrides:k,isStandalone:p,initialDataLoaded:x,userName:y,requestedMobileTabKey:N,onRequestedMobileTabConsumed:j,requestedMachineId:I,onRequestedMachineConsumed:M,requestedMobileSection:w,onRequestedMobileSectionConsumed:v,containerRef:$,isSplitMode:_,numGroups:T,groupSizes:F,groupedConvs:B,clearedTabs:L,focusedGroup:C,focusGroup:A,moveTabToGroup:K,splitTabRelative:P,closeGroup:D,handleResizeStart:H,groupActiveTabIds:Q,setGroupActiveTab:be,groupTabOrders:de,setGroupTabOrder:te,toggleHiddenTab:Z,visibleConversations:ce,requestedDesktopTabKey:fe,onRequestedDesktopTabConsumed:J,onDesktopActiveTabChange:me,onRequestScrollToBottom:ve,onHideConversation:ae,onShowHiddenConversation:pe,onShowAllHiddenConversations:je,scrollToBottomRequest:xe,machineEntries:ge,layoutProfile:oe,onBrowseMachineDirectory:le,onSaveMachineWorkspace:ie,onLaunchMachineIde:Y,onLaunchMachineProvider:G,onListMachineMeshes:ue,onLaunchMeshCoordinator:ke,onListMachineSavedSessions:se,notifications:Re,notificationUnreadCount:$e,liveSessionInboxState:Oe,onMarkNotificationRead:He,onMarkNotificationUnread:W,onDeleteNotification:Ce}){const Te=Nt.useRef(null),{inboxOpen:Le,hiddenOpen:Be,shortcutHelpOpen:Fe,newSessionOpen:Ye,guideNudgeVisible:et,guideTab:ut,shortcutSection:ft,isDesktopDashboard:pt,setGuideTab:Ne,setShortcutSection:Ue,handleInboxOpenChange:Xe,handleHiddenOpenChange:Ve,handleOpenShortcutHelp:tt,closeShortcutHelp:O,openNewSession:z,closeNewSession:q}=Pb({isMobile:s,showMobileChatMode:e,visibleConversationCount:ce.length}),[re,E]=Nt.useState(null),X=Nt.useCallback((ye,U)=>{E({daemonId:ye,workspace:U})},[]),ee=Nt.useCallback(ye=>{var U;rr.flushSync(()=>{pe(ye)}),(U=Te.current)==null||U.restoreHiddenTabToSavedLocation(ye.tabKey)},[pe]),ne=Nt.useCallback(ye=>{var R;const U=u.find(V=>ga(V,ye))||f.find(V=>ga(V,ye));U&&(f.some(V=>V.tabKey===U.tabKey)&&ee(U),me(U.tabKey),(R=Te.current)==null||R.activateConversationTab(U.tabKey),ve(U.tabKey,"notification-open")),He(ye.id),Xe(!1)},[ee,f,u,me,He,ve]),we=Nt.useCallback(()=>{var U;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((U=Te.current)==null||U.resetAllPanelsToMain(),Ve(!1))},[Ve]),Ae=Nt.useCallback(async ye=>{var De;if(!r)return;const U=(De=r.modalButtons)==null?void 0:De[ye];if(!U)return;const R=Rs(r);if(!R)return;const V=U.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),he=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(V);try{await g(R,"resolve_action",{button:U,action:he?"approve":"reject",buttonIndex:ye,...ts(r)})}catch(Me){$b(Me)||console.error("[Shortcut approval] Failed:",Me)}},[r,g]),{isMac:_e,actionDefinitions:Se,actionShortcuts:Pe,shortcutListening:Ee,shortcutListeningDraft:Ie,setShortcutListening:Ge,setShortcutListeningDraft:Ze,saveShortcuts:it}=Qx({enabled:pt&&!Fe,onTrigger:ye=>{var U,R,V,he,De,Me,Ke,at,St,mt,zt,pr,hr,xr,br,gr;if(ye==="openShortcutHelp"){tt();return}if(ye==="openNewSession"){z();return}if(ye==="hideCurrentTab"){r&&ae(r);return}if(ye==="toggleHiddenTabs"){Ve(!Be);return}if(ye==="openHistoryForActiveTab"){r&&!Qe(r)&&i(r);return}if(ye==="openRemoteForActiveTab"){r&&!st(r)&&!Qe(r)&&c(r);return}if(ye==="splitActiveTabRight"){(U=Te.current)==null||U.splitActiveTabRight();return}if(ye==="splitActiveTabDown"){(R=Te.current)==null||R.splitActiveTabDown();return}if(ye==="floatActiveTab"){(V=Te.current)==null||V.floatActiveTab();return}if(ye==="popoutActiveTab"){(he=Te.current)==null||he.popoutActiveTab();return}if(ye==="dockActiveTab"){(De=Te.current)==null||De.dockActiveTab();return}if(ye==="focusLeftPane"){(Me=Te.current)==null||Me.focusLeftPane();return}if(ye==="focusRightPane"){(Ke=Te.current)==null||Ke.focusRightPane();return}if(ye==="focusUpPane"){(at=Te.current)==null||at.focusUpPane();return}if(ye==="focusDownPane"){(St=Te.current)==null||St.focusDownPane();return}if(ye==="moveActiveTabToLeftPane"){(mt=Te.current)==null||mt.moveActiveTabToLeftPane();return}if(ye==="moveActiveTabToRightPane"){(zt=Te.current)==null||zt.moveActiveTabToRightPane();return}if(ye==="moveActiveTabToUpPane"){(pr=Te.current)==null||pr.moveActiveTabToUpPane();return}if(ye==="moveActiveTabToDownPane"){(hr=Te.current)==null||hr.moveActiveTabToDownPane();return}if(ye==="triggerPrimaryApprovalAction"){Ae(0);return}if(ye==="triggerSecondaryApprovalAction"){Ae(1);return}if(ye==="triggerTertiaryApprovalAction"){Ae(2);return}if(ye==="setActiveTabShortcut"){(xr=Te.current)==null||xr.setShortcutForActiveTab();return}if(ye==="selectPreviousGroupTab"){(br=Te.current)==null||br.activatePreviousTabInGroup();return}if(ye==="selectNextGroupTab"){(gr=Te.current)==null||gr.activateNextTabInGroup();return}!r||!st(r)||Qe(r)||ye==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),lt=Nt.useCallback(()=>{O(),Ge(null),Ze([])},[O,Ge,Ze]),ht=Nt.useMemo(()=>ft==="all"?Se:Se.filter(ye=>Db(ye)===ft),[Se,ft]),bt=Nt.useCallback(()=>{const ye=Object.fromEntries(Se.map(U=>[U.id,""]));it(ye)},[Se,it]),ze=Nt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const ye=Object.fromEntries(Se.map(U=>[U.id,U.defaultShortcut]));it(ye)},[Se,it]);return Nt.useEffect(()=>{const ye=U=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?U.metaKey&&U.key.toLowerCase()==="w":U.ctrlKey&&U.key.toLowerCase()==="w")&&(U.preventDefault(),r&&ae&&ae(r))};return window.addEventListener("keydown",ye),()=>window.removeEventListener("keydown",ye)},[r,ae]),Nt.useEffect(()=>{if(!Fe||Ee)return;const ye=U=>{U.key==="Escape"&&(U.preventDefault(),lt())};return window.addEventListener("keydown",ye,!0),()=>window.removeEventListener("keydown",ye,!0)},[lt,Fe,Ee]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(dp,{activeConv:r,wsStatus:n,isConnected:a,conversations:ce,hiddenConversations:f,onOpenHistory:i,onHideConversation:ae,onShowConversation:ee,onShowAllHidden:je,onResetPanelsToMain:we,notifications:Re,notificationUnreadCount:$e,onOpenNotification:ne,onMarkNotificationRead:He,onMarkNotificationUnread:W,onDeleteNotification:Ce,inboxOpen:Le,onInboxOpenChange:Xe,hiddenOpen:Be,onHiddenOpenChange:Ve,onOpenNewSession:s?void 0:z,onOpenDashboardGuide:tt,guideNudgeVisible:et,actionShortcuts:Pe,onOpenRemote:()=>{!r||st(r)||Qe(r)||c(r)},onStopCli:l,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:X}),e?t.jsx(Wx,{conversations:u,hiddenConversations:f,ides:b,actionLogs:S,sendDaemonCommand:g,setActionLogs:h,setCliViewModeOverrides:k,isStandalone:p,userName:y,requestedActiveTabKey:N,onRequestedActiveTabConsumed:j,requestedMachineId:I,onRequestedMachineConsumed:M,requestedMobileSection:w,onRequestedMobileSectionConsumed:v,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowAllHiddenConversations:je,onHideConversation:ae,onOpenNewSession:z,liveSessionInboxState:Oe}):s?t.jsx(qx,{containerRef:$,isSplitMode:_,numGroups:T,groupSizes:F,groupedConvs:B,clearedTabs:L,ides:b,actionLogs:S,sendDaemonCommand:g,setActionLogs:h,isStandalone:p,hasRegisteredMachines:ge.length>0,userName:y,focusedGroup:C,focusGroup:A,moveTabToGroup:K,splitTabRelative:P,closeGroup:D,handleResizeStart:H,groupActiveTabIds:Q,setGroupActiveTab:be,groupTabOrders:de,setGroupTabOrder:te,toggleHiddenTab:Z,onOpenNewSession:z,allowTabShortcuts:!1,liveSessionInboxState:Oe}):t.jsx(mb,{visibleConversations:ce,clearedTabs:L,ides:b,actionLogs:S,sendDaemonCommand:g,setActionLogs:h,isStandalone:p,hasRegisteredMachines:ge.length>0,initialDataLoaded:x,userName:y,toggleHiddenTab:Z,actionShortcuts:Pe,registerActionHandlers:ye=>{Te.current=ye},onActiveTabChange:me,requestedActiveTabKey:fe,onRequestedActiveTabConsumed:J,onRequestScrollToBottom:ve,scrollToBottomRequest:xe,onOpenNewSession:z,liveSessionInboxState:Oe,layoutProfile:oe}),Ye&&t.jsx(bb,{machines:ge,ides:b,onClose:q,onBrowseDirectory:le,onSaveWorkspace:ie,onLaunchIde:Y,onLaunchProvider:G,onListMeshes:ue,onLaunchMeshCoordinator:ke,onListSavedSessions:se}),re&&t.jsx(Ol,{daemonId:re.daemonId,workspace:re.workspace,onClose:()=>E(null)}),Fe&&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:lt,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:ye=>ye.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:lt,"aria-label":"Close dashboard guide",children:t.jsx(vt,{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(ye=>t.jsx("button",{type:"button",className:`btn btn-sm ${ut===ye.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ne(ye.id),children:ye.label},ye.id))}),ut==="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."]})]})]})]}),ut==="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."]})]})]})]}),ut==="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(ye=>t.jsx("button",{type:"button",className:`btn btn-sm ${ft===ye.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ue(ye.id),children:ye.label},ye.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:bt,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:ze,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:ht.map(ye=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ee===ye.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:ye.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ye.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:ye.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:Ee===ye.id?Ie.length>0?`${Ie.join(" ")} ...`:"Listening...":Pe[ye.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Ge(ye.id),Ze([])},children:Ee===ye.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const U={...Pe};U[ye.id]="",it(U)},children:"Disable"})]})]})},ye.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",_e?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const Jn=[{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 Kb({onClose:e}){const[s,r]=o.useState(0),n=Jn[s],a=s===Jn.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(vt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Jn.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:`
|
|
65
|
-
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
66
|
-
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
67
|
-
`})]})}function Wb({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",d=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)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"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 Ob({ideData:e,allIdes:s,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>Vc(s),[s]),d=o.useMemo(()=>e?ro(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=o.useMemo(()=>d.find(h=>h.streamSource==="native"),[d]),u=o.useMemo(()=>d.filter(h=>h.streamSource==="agent-stream"),[d]),f=o.useMemo(()=>e?Pt(d,e.id):null,[d,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!f)return;const h=f.streamSource==="native"?"native":f.tabKey;!h||i===h||i==="native"&&c(h)},[i,f,a]),o.useEffect(()=>{var h;i!=="native"&&(u.some(k=>k.tabKey===i)||c(((h=u[0])==null?void 0:h.tabKey)||"native"))},[i,u]),o.useEffect(()=>{i==="native"&&(m||u[0]&&c(u[0].tabKey))},[i,m,u]);const b=o.useMemo(()=>i==="native"&&m?m:u.find(h=>h.tabKey===i)||f||m||u[0],[i,m,f,u]),S=o.useMemo(()=>u.map(h=>({tabKey:h.tabKey,title:Kc(h)||n,status:h.status})),[u,n]),g=o.useCallback(h=>{if(h)return d.find(k=>ga(k,{sessionId:h,routeId:h,tabKey:h,providerSessionId:h}))},[d]);return{activeChatTab:i,setActiveChatTab:c,activeConv:b,conversations:d,extensionTabs:S,hasExtensions:S.length>0,resolveConversationByTarget:g}}function Fb({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:d,onOpenHistory:m,onConversationChange:u,onClose:f}){const[b,S]=o.useState("split"),[g,h]=o.useState(()=>qt(e)?"native":e.tabKey),k=o.useRef(null),p=o.useMemo(()=>s||r.find(A=>A.id===e.routeId),[e.routeId,s,r]),x=o.useMemo(()=>ot((p==null?void 0:p.type)||""),[p==null?void 0:p.type]),{conversations:y,extensionTabs:N,hasExtensions:j}=Ob({ideData:p,allIdes:r,connectionStates:n,ideName:x||"IDE",preferredTabKey:qt(e)?void 0:e.tabKey}),I=o.useMemo(()=>p?Pt(y,p.id):null,[p,y]);o.useEffect(()=>{const A=k.current,K={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(k.current=K,!(A&&A.routeId===K.routeId&&A.tabKey===K.tabKey&&A.streamSource===K.streamSource)){if(qt(e)){h("native");return}h(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(g==="native"){if(y.some(A=>A.streamSource==="native"))return;(I==null?void 0:I.streamSource)==="agent-stream"&&h(I.tabKey);return}if(!y.some(A=>A.tabKey===g)){if((I==null?void 0:I.streamSource)==="agent-stream"){h(I.tabKey);return}h("native")}},[y,g,I]);const M=o.useMemo(()=>g==="native"?y.find(A=>A.streamSource==="native")||e:y.find(A=>A.tabKey===g)||e,[e,y,g]),w=nl(M),v=o.useMemo(()=>w.status||w.modalMessage||w.modalButtons?{...M,...w.status?{status:w.status}:{},...w.modalMessage!==void 0?{modalMessage:w.modalMessage}:{},...w.modalButtons!==void 0?{modalButtons:w.modalButtons}:{}}:M,[M,w]),$=dr(v),_=pn({sendDaemonCommand:i,activeConv:v,setActionLogs:c,isStandalone:l}),{connScreenshot:T,screenshotUsage:F,handleRemoteAction:B}=Nl({doId:$,targetSessionId:gc(v),connState:v.connectionState||"new",viewMode:b}),L=o.useMemo(()=>a.filter(A=>A.routeId===v.tabKey),[a,v.tabKey]);o.useEffect(()=>{u==null||u(v)},[v,u]),o.useEffect(()=>{const A=K=>{K.key==="Escape"&&f()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[f]);const C=o.useCallback(A=>{A.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:f,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:C,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(Tt,{size:16})}),t.jsx("span",{className:"truncate",children:Ua(M)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:f,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(A=>{const K=b===A;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${K?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>S(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?t.jsx(tu,{size:15}):t.jsx(Tt,{size:15})},A)})}),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:()=>m(M),title:"Chat History",children:[t.jsx(Da,{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:f,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${b==="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:[b!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${b==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(Wb,{hasExtensions:j,ideName:x||"IDE",activeChatTab:g,extensionTabs:N,onSelectTab:h}),t.jsx(nc,{activeConv:v,onModalButton:_.handleModalButton}),t.jsx(ja,{activeConv:v,ideEntry:p,showMetaChips:!1,handleSendChat:_.handleSendChat,isSendingChat:_.isSendingChat,sendFeedbackMessage:_.sendFeedbackMessage,handleFocusAgent:_.handleFocusAgent,isFocusingAgent:_.isFocusingAgent,actionLogs:L,userName:d})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${b==="split"?"order-1 md:order-2":""}`,children:t.jsx(sc,{addLog:()=>{},connState:v.connectionState||"new",connScreenshot:T,screenshotUsage:F,transportType:v.transport,onAction:B})})]})]})})}function Hb({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=Zf(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 Ub({historyModal:e,remoteDialog:s,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return t.jsxs(t.Fragment,{children:[t.jsx(np,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&t.jsx(so,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),s.conversation&&t.jsx(Fb,{activeConv:s.conversation,ideEntry:s.ideEntry,ides:s.ides,connectionStates:s.connectionStates,actionLogs:s.actionLogs,sendDaemonCommand:s.sendDaemonCommand,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone,userName:s.userName,onOpenHistory:s.onOpenHistory,onConversationChange:s.onConversationChange,onClose:s.onClose}),r.open&&r.targetConv&&(st(r.targetConv)||Qe(r.targetConv))&&t.jsx(Hb,{activeConv:r.targetConv,canSaveAndStop:st(r.targetConv)&&!Qe(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),t.jsx(zc,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&t.jsx(Kb,{onClose:i.onClose})]})}function zb({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(cr,{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=Ct(c,{fallbackId:c.id}),d=n[c.id],m=c.version||c.daemonVersion||"unknown",u=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:l}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="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:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:u?"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(vt,{size:16})})]})}function Vb(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Gb(e){const s=e.machine;return typeof(s==null?void 0:s.cpus)!="number"||typeof(s==null?void 0:s.totalMem)!="number"||typeof(s==null?void 0:s.arch)!="string"||typeof(s==null?void 0:s.release)!="string"}function qb(e){return{metadataDaemonIds:e.map(s=>s.id),runtimeDaemonIds:e.filter(s=>Gb(s)).map(s=>s.id)}}function Yb(){var wo,jo,ko,So;const{sendCommand:e}=xt(),s=mr(),r=rl(),n=La(),a=xs(),[i,c]=wd(),l=i.get("activeTab"),d=((wo=n.state)==null?void 0:wo.openRemoteForTabKey)||null,m=((jo=n.state)==null?void 0:jo.openMachineId)||null,u=((ko=n.state)==null?void 0:ko.mobileSection)||null,f=Dc(),b=f.ides||[],S=f.initialLoaded??!0,{updateRouteChats:g,setToasts:h}=f,[k,p]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),x=f.toasts||[],y=f.wsStatus||"connected",N=f.isConnected??!0,j=f.connectionStates||{},I=f.showReconnected||!1,{layoutProfile:M,groupAssignments:w,updateGroupAssignments:v,focusedGroup:$,updateFocusedGroup:_,focusGroup:T,groupActiveTabIds:F,updateGroupActiveTabIds:B,setGroupActiveTab:L,groupTabOrders:C,updateGroupTabOrders:A,setGroupTabOrder:K,groupSizes:P,updateGroupSizes:D,isMobile:H,hasHydratedStoredLayout:Q,hydrateStoredLayout:be,focusConversationTab:de}=Bh(),[te,Z]=o.useState(()=>io());o.useEffect(()=>sh(Z),[]);const ce=o.useMemo(()=>Vb({isMobile:H,mobileViewMode:te}),[H,te]),[fe,J]=o.useState([]),[me,ve]=o.useState({}),[ae,pe]=o.useState({});lr("Dashboard",{ideCount:b.length,toastCount:x.length,focusedGroup:$,groupCount:Object.keys(w).length,actionLogCount:fe.length});const je=o.useMemo(()=>b.filter(qe=>qe.type==="adhdev-daemon").sort(Oa),[b]),xe=je[0],ge=!!xe;o.useEffect(()=>{const{metadataDaemonIds:qe,runtimeDaemonIds:It}=qb(je);for(const Bs of qe)s(Bs,{minFreshMs:3e4}).catch(()=>{});for(const Bs of It)r(Bs,{minFreshMs:3e4}).catch(()=>{})},[s,r,je]);const oe=(xe==null?void 0:xe.terminalBackend)||null,le=xe?Ct(xe,{fallbackId:xe.id}):null,ie=(xe==null?void 0:xe.id)||null,Y=o.useMemo(()=>fh(b,me),[b,me]),{hiddenTabs:G,hideTarget:ue,toggleTarget:ke,showTarget:se,showAllTabs:Re}=mh(),{conversations:$e,visibleConversations:Oe,visibleTabKeys:He,resolveConversationBySessionId:W,resolveConversationByTarget:Ce}=kh({ides:Y,connectionStates:j,clearedTabs:ae,hiddenTabs:G}),Te=o.useMemo(()=>new Map($e.map(qe=>[qe.tabKey,qe])),[$e]);If(Oe,ce),o.useEffect(()=>{Object.keys(me).length!==0&&ve(qe=>ph(qe,b))},[b,me]);const Le=o.useMemo(()=>Fu(b),[b]),{notifications:Be,unreadCount:Fe}=Zh({conversations:$e,liveSessionInboxState:Le}),{handleMarkDashboardNotificationRead:Ye,handleMarkDashboardNotificationUnread:et,handleDeleteDashboardNotification:ut}=ex({notifications:Be,sendDaemonCommand:e}),{containerRef:ft,normalizedGroupAssignments:pt,numGroups:Ne,isSplitMode:Ue,groupedConvs:Xe,moveTabToGroup:Ve,closeGroup:tt,handleResizeStart:O,splitTabRelative:z}=zh({groupAssignments:w,updateGroupAssignments:v,updateFocusedGroup:_,updateGroupActiveTabIds:B,updateGroupTabOrders:A,groupSizes:P,updateGroupSizes:D,isMobile:H,visibleConversations:Oe,visibleTabKeys:He}),{activeConv:q,openDesktopConversation:re,requestScrollToBottom:E,scrollToBottomRequest:X,setDesktopActiveTab:ee}=mx({isMobile:H,conversations:$e,visibleConversations:Oe,groupActiveTabIds:F,focusedGroup:$,groupedConvs:Xe,setSearchParams:c});hx({activeConv:q,isMobile:H,liveSessionInboxState:Le,sendDaemonCommand:e});const{requestedDesktopTabKey:ne,requestedMobileTabKey:we,consumeRequestedActiveTab:Ae}=Sh({isMobile:H,urlActiveTab:l,resolveConversationBySessionId:W,setSearchParams:c}),{remoteDialogConv:_e,remoteDialogIdeEntry:Se,remoteDialogActiveConv:Pe,setRemoteDialogActiveConv:Ee,openRemoteDialog:Ie,closeRemoteDialog:Ge,cliStopDialogOpen:Ze,cliStopTargetConv:it,requestCliStop:lt,cancelCliStop:ht,confirmCliStop:bt}=gx({isMobile:H,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:ne,conversations:$e,ides:b,resolveConversationByTarget:Ce,activeConv:q,sendDaemonCommand:e}),{historyModalOpen:ze,openHistoryModal:ye,closeHistoryModal:U,historyTargetConv:R,isSavedSessionHistoryTarget:V,isHistoryCreatingChat:he,isHistoryRefreshingHistory:De,handleHistorySwitchSession:Me,handleHistoryNewChat:Ke,handleHistoryRefresh:at,savedHistorySessions:St,savedHistoryFilters:mt,setSavedHistoryFilters:zt,missingWorkspaceResumePath:pr,isSavedHistoryLoading:hr,resumingSavedHistorySessionId:xr,handleRefreshSavedHistory:br,handleResumeSavedHistorySession:gr}=xx({activeConv:q,remoteDialogConv:_e,remoteDialogActiveConv:Pe,ides:b,sendDaemonCommand:e,updateRouteChats:g,setToasts:h,setClearedTabs:pe,setSearchParams:c}),Vl=o.useMemo(()=>Oe,[Oe]),yr=H&&te==="chat",Gl=o.useMemo(()=>$e.filter(qe=>co(G,qe)),[$e,G]),go=o.useCallback(qe=>{const It=new URLSearchParams(i);It.set("activeTab",qe),c(It,{replace:!0})},[i,c]),{trackPendingLaunch:ql}=cx({ides:b,conversations:$e,onOpenSession:go}),{handleBrowseMachineDirectory:Yl,handleSaveMachineWorkspace:Xl,handleLaunchMachineIde:Jl,handleLaunchMachineProvider:Ql,handleListMachineMeshes:Zl,handleLaunchMeshCoordinator:ed,handleListMachineSavedSessions:td,setActiveCliViewMode:sd}=lx({sendDaemonCommand:e,trackPendingLaunch:ql,onOpenSession:go,activeConv:q,ides:b,setCliViewModeOverrides:ve});hh({visibleConversations:Oe,clearedTabs:ae,setClearedTabs:pe,setActionLogs:J}),Nh({ides:b,sendDaemonCommand:e,setToasts:h,resolveConversationByTarget:Ce});const{isRefreshingHistory:rd,handleRefreshHistory:nd}=pl({sendDaemonCommand:e,activeConv:q,chats:(So=b.find(qe=>qe.id===(q==null?void 0:q.routeId)))==null?void 0:So.chats,updateRouteChats:g,setToasts:h,setClearedTabs:pe});Wh({urlActiveTab:H&&!yr?l:null,conversations:$e,resolveConversationBySessionId:W,normalizedGroupAssignments:pt,hasHydratedStoredLayout:H&&!yr?Q:!0,hydrateStoredLayout:H&&!yr?be:()=>{},focusConversationTab:de,setSearchParams:c,historyModalOpen:ze,activeConv:q,isRefreshingHistory:rd,ides:b,handleRefreshHistory:nd});const ad=o.useMemo(()=>!q||!st(q)||Qe(q)?null:$s(q),[q]),{versionMismatchDaemons:od,hasRequiredVersionDaemons:yo,appVersion:id,versionBannerDismissed:cd,setVersionBannerDismissed:ld,upgradingDaemons:dd,handleBannerUpgrade:ud}=Vh({ides:b,sendDaemonCommand:e}),vo=o.useCallback(qe=>{se(qe),re(qe)},[re,se]),md=o.useCallback(qe=>{ue(qe)},[ue]);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(ap,{terminalBackend:oe,isStandalone:ge,machineLabel:le,machineKey:ie}),(!cd||yo)&&t.jsx(zb,{daemons:od,targetVersion:id,required:yo,upgradingDaemons:dd,onUpgrade:ud,onDismiss:()=>ld(!0)}),t.jsx(Bb,{showMobileChatMode:yr,isMobile:H,activeConv:q,wsStatus:y,isConnected:N,onOpenHistory:qe=>{qe&&Ee(qe),ye()},onOpenRemote:Ie,onStopCli:lt,activeCliViewMode:ad,onSetActiveCliViewMode:sd,mobileChatConversations:Vl,ides:b,actionLogs:fe,sendDaemonCommand:e,setActionLogs:J,setCliViewModeOverrides:ve,isStandalone:ge,initialDataLoaded:S,userName:f.userName,requestedMobileTabKey:we,onRequestedMobileTabConsumed:Ae,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:ft,isSplitMode:Ue,numGroups:Ne,groupSizes:P,groupedConvs:Xe,clearedTabs:ae,focusedGroup:$,focusGroup:T,moveTabToGroup:Ve,splitTabRelative:z,closeGroup:tt,handleResizeStart:O,groupActiveTabIds:F,setGroupActiveTab:L,groupTabOrders:C,setGroupTabOrder:K,toggleHiddenTab:qe=>ke(Te.get(qe)||{tabKey:qe}),visibleConversations:Oe,hiddenConversations:Gl,requestedDesktopTabKey:ne,onRequestedDesktopTabConsumed:Ae,onDesktopActiveTabChange:ee,onRequestScrollToBottom:E,onHideConversation:md,onShowHiddenConversation:vo,onShowAllHiddenConversations:Re,scrollToBottomRequest:X,machineEntries:je,layoutProfile:M,onBrowseMachineDirectory:Yl,onSaveMachineWorkspace:Xl,onLaunchMachineIde:Jl,onLaunchMachineProvider:Ql,onListMachineMeshes:Zl,onLaunchMeshCoordinator:ed,onListMachineSavedSessions:td,notifications:Be,notificationUnreadCount:Fe,liveSessionInboxState:Le,onMarkNotificationRead:Ye,onMarkNotificationUnread:et,onDeleteNotification:ut}),t.jsx("style",{children:`
|
|
68
|
-
body { overflow: hidden; overscroll-behavior: none; }
|
|
69
|
-
`}),t.jsx(Ub,{historyModal:{open:ze,targetConv:R,ides:b,isCreatingChat:he,isRefreshingHistory:V?!1:De,savedSessions:St,savedHistoryFilters:mt,missingWorkspaceResumePath:pr||null,onSavedHistoryFiltersChange:zt,isSavedSessionsLoading:hr,isResumingSavedSessionId:xr,onClose:U,onNewChat:Ke,onSwitchSession:Me,onRefreshHistory:V?br:at,onResumeSavedSession:gr},remoteDialog:{conversation:_e,ideEntry:Se,ides:b,connectionStates:j,actionLogs:fe,sendDaemonCommand:e,setActionLogs:J,isStandalone:ge,userName:f.userName,onOpenHistory:qe=>{qe&&Ee(qe),ye()},onConversationChange:Ee,onClose:Ge},cliStopDialog:{open:Ze,targetConv:it,onCancel:ht,onStopNow:async()=>{await bt("hard")},onSaveAndStop:async()=>{await bt("save")}},connectionBanner:{wsStatus:y,showReconnected:I,loginUrl:f.connectionLoginUrl,onReconnect:f.retryServerConnection},toastOverlay:{toasts:x,onDismiss:qe=>h(It=>It.filter(Bs=>Bs.id!==qe)),onClick:qe=>{if(qe.targetKey){const It=Ce(qe.targetKey);It&&(de(It.tabKey,pt),vo(It),E(It.tabKey,"toast-open"))}}},onboarding:{open:k,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}p(!1)}}})]})}function Xb({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,d]=o.useState(null),[m,u]=o.useState(null),[f,b]=o.useState(!1),[S,g]=o.useState(null),[h,k]=o.useState(!1),[p,x]=o.useState(""),y=o.useRef(null),N=o.useCallback(P=>{y.current=P},[]),j=o.useCallback((P,D,H=!1)=>{c(Q=>[...Q.slice(-100),{timestamp:Date.now(),level:P,message:D}]),setTimeout(()=>{var Q;return(Q=a.current)==null?void 0:Q.scrollIntoView({behavior:"smooth"})},100),H&&nt.showToast(D,P==="error"||P==="warn"?"warning":"success")},[a]),I=o.useCallback(P=>{const D=P instanceof Error?P.message:String(P||"");return D.includes("P2P command timeout")||D.includes("P2P not connected")||D.includes("P2P not available")},[]),M=o.useCallback(async(P,D)=>{var H;if(!e||l)return!1;d(P),j("info",`Launching ${ot(P)}${D!=null&&D.workspace?` in ${D.workspace}`:""}...`);try{const Q={ideType:P,enableCdp:!0};(H=D==null?void 0:D.workspace)!=null&&H.trim()?Q.workspace=D.workspace.trim():D!=null&&D.useDefaultWorkspace&&(Q.useDefaultWorkspace=!0);const be=await r(e,"launch_ide",Q);return j(be!=null&&be.success?"info":"error",be!=null&&be.success?`${ot(P)} launched`:`Failed: ${be==null?void 0:be.error}`,!0),!!(be!=null&&be.success)}catch(Q){return j("error",`Launch error: ${Q.message}`,!0),!1}finally{d(null)}},[e,l,j,r]),w=o.useCallback(async P=>{if(!e)return{success:!1};const{cliType:D,dir:H,workspaceId:Q,useDefaultWorkspace:be,useHome:de,argsStr:te,model:Z,resumeSessionId:ce}=P;if(!D)return j("warn","Select a CLI or ACP provider first",!0),{success:!1};const fe=te?te.split(/\s+/).filter(Boolean):void 0,J=(H==null?void 0:H.trim())||(Q?"(saved id)":be?"(default workspace)":de?"(home)":"");j("info",`Launching ${D}${J?` in ${J}`:""}${Z?` (model: ${Z})`:""}...`),u(D);try{const me={cliType:D,cliArgs:fe,initialModel:Z||void 0};H!=null&&H.trim()?me.dir=H.trim():Q?me.workspaceId=Q:be?me.useDefaultWorkspace=!0:de&&(me.useHome=!0),ce&&(me.resumeSessionId=ce);const ve=await r(e,"launch_cli",me),ae=(ve==null?void 0:ve.result)||ve;return ve!=null&&ve.success?(j("info",`${D} launched`,!0),(ae==null?void 0:ae.launchSource)==="home"?j("info","📂 Running in home directory (explicit choice)"):(ae==null?void 0:ae.launchSource)==="defaultWorkspace"&&j("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ae==null?void 0:ae.sessionId}):(j("error",`Failed: ${(ve==null?void 0:ve.error)||(ae==null?void 0:ae.error)}`,!0),(ve==null?void 0:ve.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&g({cliType:D,argsStr:te,model:Z}),{success:!1,sessionId:ae==null?void 0:ae.sessionId})}catch(me){return I(me)?(j("warn",`${D} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(j("error",`Launch error: ${me.message}`,!0),{success:!1})}finally{u(null)}},[e,j,I,r]),v=o.useCallback(async(P,D,H,Q)=>e?P?D.trim()?w({cliType:P,dir:D,argsStr:H,model:Q}):(g({cliType:P,argsStr:H,model:Q}),{success:!1}):(j("warn","Select a provider",!0),{success:!1}):{success:!1},[e,j,w]),$=o.useCallback(async(P,D,H)=>{if(e&&window.confirm(`Stop ${P}?
|
|
70
|
-
This will terminate the process.`))try{const Q=await r(e,"stop_cli",{cliType:P,dir:D,targetSessionId:H});Q!=null&&Q.success?j("info",`${P} stopped`,!0):j("error",`Stop failed: ${(Q==null?void 0:Q.error)||"Unknown error"}`,!0)}catch(Q){j("error",`Stop failed: ${Q.message}`,!0)}},[e,j,r]),_=o.useCallback(async P=>{try{await r(P.daemonId,"restart_ide",{ideType:P.type}),j("info",`${ot(P.type)} restart initiated`,!0)}catch(D){j("error",`Restart failed: ${D.message}`,!0)}},[j,r]),T=o.useCallback(async P=>{if(window.confirm(`Stop ${ot(P.type)}?
|
|
71
|
-
This will disconnect CDP and optionally kill the process.`))try{const D=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});D!=null&&D.success?j("info",`${ot(P.type)} stopped`,!0):j("error",`Stop failed: ${(D==null?void 0:D.error)||"Unknown error"}`,!0)}catch(D){j("error",`Stop failed: ${D.message}`,!0)}},[j,r]),F=o.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});j("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){j("error",`Detection failed: ${P.message}`,!0)}},[e,j,r]),B=o.useCallback(async P=>{if(!e||!P.trim())return!1;b(!0);try{const D=await r(e,"workspace_add",{path:P.trim()});return D!=null&&D.success?(j("info",`Workspace added: ${P.trim()}`),!0):(j("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return j("error",D.message),!1}finally{b(!1)}},[e,j,r]),L=o.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){b(!0);try{const D=await r(e,"workspace_remove",{id:P});D!=null&&D.success?j("info","Workspace removed",!0):j("error",(D==null?void 0:D.error)||"workspace_remove failed",!0)}catch(D){j("error",D.message,!0)}finally{b(!1)}}},[e,j,r]),C=o.useCallback(async P=>{var D;if(e){b(!0);try{const H=await r(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(H!=null&&H.success){j("info",P?"Default workspace updated":"Default workspace cleared",!0);const Q=typeof H.defaultWorkspacePath=="string"?H.defaultWorkspacePath:"";Q&&((D=y.current)==null||D.call(y,Q))}else j("error",(H==null?void 0:H.error)||"workspace_set_default failed",!0)}catch(H){j("error",H.message,!0)}finally{b(!1)}}},[e,j,r]),A=o.useCallback(async P=>{var H;if(!e||!P.trim())return;const D=P.trim();b(!0);try{const Q=await r(e,"workspace_set_default",{path:D});Q!=null&&Q.success?(j("info","Default workspace set from history"),(H=y.current)==null||H.call(y,D)):j("error",(Q==null?void 0:Q.error)||"Could not set default (path missing on disk?)")}catch(Q){j("error",Q.message)}finally{b(!1)}},[e,j,r]),K=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:p}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:p})}catch(P){j("warn",`Live nickname updated, but account sync failed: ${P.message}`)}j("info",`Nickname set to "${p||"(cleared)"}"`),k(!1)}catch(P){j("error",`Failed: ${P.message}`)}},[e,p,s,j,n,r]);return{logs:i,launchingIde:l,launchingAgentType:m,workspaceBusy:f,launchPick:S,setLaunchPick:g,editingNickname:h,setEditingNickname:k,nicknameInput:p,setNicknameInput:x,addLog:j,handleLaunchIde:M,runLaunchCliCore:w,handleLaunchCli:v,handleStopCli:$,handleRestartIde:_,handleStopIde:T,handleDetectIdes:F,handleWorkspaceAdd:B,handleWorkspaceRemove:L,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:A,handleSaveNickname:K,setOnDefaultWorkspaceChanged:N}}function Jb({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var _;const{workspaceBusy:l,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=i,[f,b]=o.useState(!1),[S,g]=o.useState(""),[h,k]=o.useState([]),[p,x]=o.useState(!1),[y,N]=o.useState(""),j=o.useCallback(async T=>{x(!0),N("");try{const F=await bn(c,e,T);g(F.path),k(F.directories)}catch(F){N(F instanceof Error?F.message:"Could not load folder")}finally{x(!1)}},[e,c]),I=o.useCallback(()=>{b(!0);const T=[...r.map(B=>B.workspace),...n.map(B=>B.workspace),...a.map(B=>B.workspace)],F=xn(s.platform,hn(T,s.defaultWorkspacePath,(s.workspaces||[]).map(B=>B.path)));j(F)},[a,n,r,j,s.defaultWorkspacePath,s.platform,s.workspaces]),M=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,w=s.availableMem??s.freeMem??s.totalMem,v=M&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-w)/s.totalMem*100))):0,$=((_=s.loadavg)==null?void 0:_[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(kr,{icon:t.jsx(Yi,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?qu(s.uptime):"Waiting…"}),t.jsx(kr,{icon:t.jsx(Tt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(kr,{icon:t.jsx($a,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(kr,{icon:t.jsx(ru,{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(_o,{value:M?Math.min(Math.round($/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:M?`${$.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(_o,{value:v,max:100,label:"Memory",color:"#3b82f6",detail:M?`${Cn(s.totalMem-w)} / ${Cn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Cn(s.totalMem)} total`})]})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[t.jsx(us,{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:T=>void u(T.target.value===""?null:T.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(T=>t.jsx("option",{value:T.id,children:T.label||T.path},T.id))]}),s.defaultWorkspacePath&&t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:l,onClick:I,children:"Select workspace…"}),t.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&t.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(T=>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:[T.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:mn(T.path,T.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:T.path,children:T.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void m(T.id),children:"Remove"})]},T.id))})]}),f&&t.jsx(gn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:S,directories:h,busy:p,error:y,confirmLabel:"Add workspace",onClose:()=>b(!1),onNavigate:T=>{j(T)},onConfirm:T=>{(async()=>{if(!T)return;await d(T)&&b(!1)})()}})]})}function Qb(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 Zb(e,s,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=r!=null&&r.filterSchema?r.filterSchema(i):i;if(c.length===0)continue;const l=s.find(d=>d.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 Qn(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 ji(e){if(!e||typeof e!="object")return null;if(Qn(e))return e;const s=e,r=s.result;return Qn(r)?r:Qn(s.sourceConfig)?s.sourceConfig:null}function eg(e){const s=e.trim();return s||null}const ki=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],tg=[{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 sg({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[d,m]=o.useState([]),[u,f]=o.useState(""),[b,S]=o.useState([]),[g,h]=o.useState(""),k=o.useRef(null),p=o.useRef(null),x=w=>{m(v=>v.includes(w)?v.filter($=>$!==w):[...v,w])},y=()=>m([...ki]),N=()=>m([]);o.useEffect(()=>{var w;(w=k.current)==null||w.scrollIntoView({behavior:"smooth"})},[b]),o.useEffect(()=>()=>{p.current&&clearInterval(p.current)},[]);const j=o.useCallback(()=>{p.current&&clearInterval(p.current),p.current=setInterval(async()=>{try{const w=await r(e,"provider_auto_fix_status",{providerType:s.type});(w==null?void 0:w.running)===!1&&a==="running"&&(i("done"),S(v=>[...v,`
|
|
72
|
-
✅ Auto-fix completed!`]),p.current&&clearInterval(p.current))}catch{}},3e3)},[e,s.type,r,a]),I=async()=>{if(d.length!==0){i("running"),S(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),h("");try{const w=await r(e,"provider_auto_fix",{providerType:s.type,functions:d,agent:c,...u?{comment:u}:{}});w!=null&&w.success&&(w!=null&&w.started||w!=null&&w.running)?(S(v=>[...v,"✅ Agent started. Monitoring progress..."]),j()):(i("error"),h((w==null?void 0:w.error)||"Failed to start auto-fix"))}catch(w){i("error"),h((w==null?void 0:w.message)||"Connection failed")}}},M=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),S(w=>[...w,`
|
|
73
|
-
⚠️ Auto-fix cancelled.`]),i("done"),p.current&&clearInterval(p.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:w=>w.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:tg.map(w=>t.jsxs("button",{onClick:()=>l(w.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===w.value?w.color+"66":"var(--border-subtle)",background:c===w.value?w.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===w.value?w.color:"var(--text-primary)"},children:w.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:w.desc})]},w.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:y,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:N,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:ki.map(w=>t.jsxs("button",{onClick:()=>x(w),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(w)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(w)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(w)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(w)?"☑ ":"☐ ",w]},w))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:u,onChange:w=>f(w.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[b.map((w,v)=>t.jsx("div",{className:w.startsWith("✅")?"text-green-400":"",style:w.startsWith("❌")||w.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:w},v)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:k})]}),g&&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:g})]})]}),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"&&d.length>0&&`${d.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[a==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:I,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&t.jsx("button",{onClick:M,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"),S([]),h("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function rg({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var j;const i=s.filter(I=>I.category==="ide"),[c,l]=o.useState(((j=i[0])==null?void 0:j.type)||""),[d,m]=o.useState(""),[u,f]=o.useState(""),[b,S]=o.useState(!1),[g,h]=o.useState(""),[k,p]=o.useState(!1),x=I=>{const M=I.toLowerCase().replace(/[^a-z0-9-]/g,"");m(M),(!u||u===y(d))&&f(y(M))},y=I=>I.split("-").map(M=>M.charAt(0).toUpperCase()+M.slice(1)).join(" "),N=async()=>{if(!(!d||!u||!c)){S(!0),h("");try{const I=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:c});I!=null&&I.success||I!=null&&I.created?(p(!0),a==null||a(d)):h((I==null?void 0:I.error)||"Failed to create provider")}catch(I){h((I==null?void 0:I.message)||"Connection failed")}S(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:I=>I.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:k?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:d})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(I=>t.jsxs("button",{onClick:()=>l(I.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===I.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===I.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:I.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===I.type?"#a78bfa":"var(--text-secondary)"},children:I.displayName})]},I.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:d,onChange:I=>x(I.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),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:u,onChange:I=>f(I.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),g&&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:g})]})}),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:k?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:N,disabled:!d||!u||b,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||b?.4:1},children:b?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Si(e){return e==="cli"||e==="acp"}function ng(e){switch(e){case"detected":return"Detected";case"not_detected":return"Not detected";case"enabled_unchecked":return"Enabled, not checked";case"disabled":return"Disabled";default:return"Disabled"}}function ag(e){switch(e){case"detected":return"bg-green-500/[0.10] border-green-500/25 text-green-400";case"not_detected":return"bg-red-500/[0.10] border-red-500/25 text-red-400";case"enabled_unchecked":return"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400";case"disabled":default:return"bg-white/[0.04] border-white/[0.10] text-text-muted"}}function Ni(e){if(!e)return"No result yet";const s=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${s}: ${r} — ${n}`:`${s}: ${r}`}function og({machineId:e,providers:s,sendDaemonCommand:r}){var B;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,d]=o.useState(null),[m,u]=o.useState("all"),[f,b]=o.useState(null),[S,g]=o.useState(!1),[h,k]=o.useState(null),[p,x]=o.useState("normal"),[y,N]=o.useState(""),[j,I]=o.useState(!1),M=o.useCallback(async()=>{if(e)try{const L=await r(e,"get_provider_source_config",{}),C=ji(L);C&&(k(C),x(C.sourceMode),N(C.explicitProviderDir||""))}catch{}},[e,r]),w=o.useCallback(async()=>{if(e){c(!0);try{const L=await r(e,"get_provider_settings",{}),C=Qb(L);if(C){const A=Zb(C,s,{filterSchema:K=>K.filter(P=>P.key!=="enabled")});A.sort((K,P)=>K.category.localeCompare(P.category)||K.displayName.localeCompare(P.displayName)),a(A)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&w(),h||M()},[]);const v=async(L,C,A)=>{d(`${L}.${C}`),a(K=>K.map(P=>P.type===L?{...P,values:{...P.values,[C]:A}}:P));try{const K=await r(e,"set_provider_setting",{providerType:L,key:C,value:A});K!=null&&K.success||w()}catch{w()}d(null)},$=async(L,C)=>{await v(L,"enabled",C),await w()},_=async L=>{d(`${L}.detect`);try{await r(e,"detect_provider",{providerType:L})}finally{await w(),d(null)}},T=async L=>{await v(L,"executablePath",""),await v(L,"executableArgs",""),await w()},F=async()=>{I(!0);try{const L=await r(e,"set_provider_source_config",{providerSourceMode:p,providerDir:eg(y)}),C=ji(L);C?(k(C),x(C.sourceMode),N(C.explicitProviderDir||"")):await M(),await w()}catch{await M()}I(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(L=>t.jsx("button",{onClick:()=>u(L),className:`machine-btn text-[10px] px-2 py-0.5 ${m===L?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:L.toUpperCase()},L))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>g(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),t.jsx("button",{onClick:w,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),t.jsx("button",{onClick:M,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:p,onChange:L=>x(L.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:y,onChange:L=>N(L.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void F(),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:"})," ",(h==null?void 0:h.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(h==null?void 0:h.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((B=h==null?void 0:h.providerRoots)==null?void 0:B.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(L=>L.category===m).length>1&&(()=>{const L=n.filter(P=>P.category===m),C=new Map;for(const P of L)for(const D of P.schema){if(D.type!=="boolean")continue;const H=C.get(D.key),Q=!!(P.values[D.key]??D.default);H?(H.onCount+=Q?1:0,H.total+=1):C.set(D.key,{label:D.label||D.key,onCount:Q?1:0,total:1})}const A=[...C.entries()].filter(([,P])=>P.total===L.length);if(A.length===0)return null;const K=async(P,D)=>{for(const H of L)await v(H.type,P,D)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",L.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:A.map(([P,D])=>{const H=D.onCount===D.total,Q=D.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:D.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",D.onCount,"/",D.total,")"]}),t.jsx("button",{onClick:()=>void K(P,!0),disabled:H,className:`machine-btn text-[9px] px-1.5 py-px ${H?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void K(P,!1),disabled:Q,className:`machine-btn text-[9px] px-1.5 py-px ${Q?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},P)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(L=>m==="all"||L.category===m).map(L=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:L.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:L.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:L.category==="acp"?"rgba(139,92,246,0.08)":L.category==="cli"?"rgba(59,130,246,0.08)":L.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:L.category==="acp"?"#a78bfa":L.category==="cli"?"#60a5fa":L.category==="ide"?"#86efac":"var(--status-warning)"},children:L.category}),Si(L.category)&&(()=>{const C=s.find(P=>P.type===L.type),A=(C==null?void 0:C.enabled)===!0||L.values.enabled===!0,K=(C==null?void 0:C.machineStatus)||(A?"enabled_unchecked":"disabled");return t.jsxs(t.Fragment,{children:[t.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${ag(K)}`,children:ng(K)}),t.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[t.jsx("button",{onClick:()=>void $(L.type,!A),disabled:l===`${L.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${A?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:A?"Disable":"Enable"}),t.jsx("button",{onClick:()=>void _(L.type),disabled:!A||l===`${L.type}.detect`,title:A?"Run detection for the configured executable":"Enable this provider before detection",className:`machine-btn text-[9px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${A?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),t.jsx("button",{onClick:()=>void T(L.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),L.category==="ide"&&t.jsx("button",{onClick:()=>b(s.find(C=>C.type===L.type)||{type:L.type,name:L.displayName,displayName:L.displayName,icon:L.icon,category:L.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),Si(L.category)&&(()=>{const C=s.find(A=>A.type===L.type);return t.jsxs("div",{className:"mb-2.5 grid gap-1 rounded-lg border border-white/[0.06] bg-bg-primary/40 px-3 py-2 text-[10px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",Ni(C==null?void 0:C.lastDetection)]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Ni(C==null?void 0:C.lastVerification)]}),t.jsx("div",{className:"text-[9px] text-text-muted",children:"Supported catalog entry only becomes launchable after Enable + Detect succeeds. Custom executable path/args below are machine-local overrides."})]})})(),t.jsx("div",{className:"flex flex-col gap-2",children:L.schema.map(C=>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:[C.label||C.key,l===`${L.type}.${C.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),C.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:C.description})]}),t.jsx("div",{className:"shrink-0",children:C.type==="boolean"?t.jsx("button",{onClick:()=>v(L.type,C.key,!(L.values[C.key]??C.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:L.values[C.key]??C.default?"#8b5cf6":"var(--border-subtle)"},children:t.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:L.values[C.key]??C.default?21:3}})}):C.type==="number"?t.jsx("input",{type:"number",value:Number(L.values[C.key]??C.default??0)||0,min:C.min,max:C.max,onChange:A=>{const K=parseInt(A.target.value)||0;C.min!==void 0&&K<C.min||C.max!==void 0&&K>C.max||v(L.type,C.key,K)},className:"machine-input w-20 text-center text-[11px]"}):C.type==="select"&&C.options?t.jsx("select",{value:String(L.values[C.key]??C.default??""),onChange:A=>v(L.type,C.key,A.target.value),className:"machine-input text-[11px]",children:C.options.map(A=>t.jsx("option",{value:A,children:A},A))}):t.jsx("input",{type:"text",value:String(L.values[C.key]??C.default??""),onBlur:A=>v(L.type,C.key,A.target.value),className:"machine-input w-[120px] text-[11px]"})})]},C.key))})]},L.type))}),f&&t.jsx(sg,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>b(null)}),S&&t.jsx(rg,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>g(!1),onCreated:()=>{g(!1),w()}})]})}const ig=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function cg({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function lg(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function dg(e){return e.trim().toLowerCase()}function vn(e,s){const r=dg(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function ho(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Ds(e,s=220){const r=ho(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function ug(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 mg(e,s){return e.filter(r=>vn([r.level,r.message],s))}function Ci(e){return`${e.timestamp}:${e.level}:${e.message}`}function fg(e,s,r=300){if(s.entries.length>0){const n=new Map;for(const c of e.entries)n.set(Ci(c),c);for(const c of s.entries)n.set(Ci(c),c);const a=Array.from(n.values()).sort((c,l)=>c.timestamp-l.timestamp).slice(-r),i=a.reduce((c,l)=>Math.max(c,Number(l.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:i}}return s.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:s.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function pg(e,s,r=120){if(s.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of s)n.set(a.id,a);return Array.from(n.values()).sort((a,i)=>a.ts-i.ts).slice(-r)}function hg(e,s){return e.split(`
|
|
74
|
-
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>vn([r],s))}function xg(e,s){return e.filter(r=>vn([r.level,r.category,r.stage,r.interactionId,ho(r.payload)],s))}function bg(e,s){return e.filter(r=>vn([r.kind,r.topic,r.interactionId,ho(r.payload)],s))}function Ti(e){return e==="warn"||e==="error"}function gg({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=>Ti(a.level)).length+r.filter(a=>Ti(a.level)).length}}function yg({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(`
|
|
75
|
-
`)):s.length>0&&a.push(["[daemon logs]",...s].join(`
|
|
76
|
-
`)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${Ds(i.payload,500)}`.trim())].join(`
|
|
77
|
-
`)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${Ds(i.payload,500)}`.trim())].join(`
|
|
78
|
-
`)),a.join(`
|
|
79
|
-
|
|
80
|
-
`)}function vg({machineId:e,sendDaemonCommand:s}){const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[d,m]=o.useState([]),[u,f]=o.useState([]),[b,S]=o.useState(null),[g,h]=o.useState(!0),[k,p]=o.useState("info"),[x,y]=o.useState("all"),[N,j]=o.useState(!0),[I,M]=o.useState(!0),[w,v]=o.useState(""),[$,_]=o.useState(""),[T,F]=o.useState(0),B=o.useRef(0),L=o.useRef(0),C=o.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),A=o.useRef([]),K=o.useCallback(()=>{const te={entries:[],kind:"empty",rawText:"",lastTs:0};C.current=te,B.current=0,n([]),l(""),i("empty"),j(!0)},[]),P=o.useCallback(()=>{A.current=[],L.current=0,m([]),M(!0)},[]),D=o.useCallback(te=>{te!==k&&(K(),p(te))},[k,K]),H=o.useCallback(te=>{y(Z=>Z===te?Z:te)},[]),Q=o.useCallback(()=>{K(),P(),f([]),S(null),v(""),_(""),Ts.clear()},[K,P]),be=o.useCallback(()=>{F(te=>te+1)},[]),de=o.useCallback(async()=>{if(!e)return;const te=B.current,Z=L.current,[ce,fe]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:k,since:te}),s(e,"get_debug_trace",cg({count:120,since:Z,category:x}))]);if(ce.status==="fulfilled"){const J=ce.value,me=(J==null?void 0:J.result)||J,ve=ug(me),ae=fg(C.current,ve,300);C.current=ae,B.current=ae.lastTs,j(!1),v((J==null?void 0:J.success)===!1?String((J==null?void 0:J.error)||"Could not load daemon logs"):""),i(ae.kind),l(ae.rawText),n(ae.entries)}else j(!1),v(ce.reason instanceof Error?ce.reason.message:"Could not load daemon logs");if(fe.status==="fulfilled"){const J=fe.value,me=(J==null?void 0:J.result)||J;if((J==null?void 0:J.success)===!1)_(String((J==null?void 0:J.error)||"Could not load daemon trace"));else if(Array.isArray(me==null?void 0:me.trace)){const ve=me.trace,ae=pg(A.current,ve,120),pe=ve.reduce((je,xe)=>Math.max(je,Number(xe.ts||0)),Z);A.current=ae,pe>Z&&(L.current=pe),_(""),m(ae)}else _("");M(!1)}else M(!1),_(fe.reason instanceof Error?fe.reason.message:"Could not load daemon trace");f(Ts.list({limit:120})),S(Date.now())},[k,e,s,x]);return o.useEffect(()=>{P()},[P,x]),o.useEffect(()=>{if(!e||(de(),!g))return;const te=setInterval(()=>{de()},3e3);return()=>clearInterval(te)},[g,de,e,T]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:d,webEvents:u,lastUpdatedAt:b,autoRefresh:g,logLevel:k,traceCategory:x,daemonLoading:N,traceLoading:I,daemonFetchError:w,traceFetchError:$,setAutoRefresh:h,setLogLevel:D,setTraceCategory:H,refresh:be,clear:Q}}function wg({daemonLoading:e,traceLoading:s,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:i,daemonRawLineCount:c,traceCount:l,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":i>0||c>0?"ok":"empty",detail:r||(a==="text"?`${c} raw file-fallback line(s)`:`${i} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":s?"loading":l>0?"ok":"empty",detail:n||`${l} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function Mi(e){return e==="warn"||e==="error"}function jg(e){const s=e.toLowerCase();return/\[(err|error)\]/i.test(e)||s.includes(" error ")||s.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||s.includes(" warning ")||s.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function kg(e,s){const r=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(r){const n=Date.parse(r[0]);if(Number.isFinite(n))return n}return Number.MAX_SAFE_INTEGER-1e5+s}function Ai(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Sg(e){const s=Ds(e.payload,320);return s?`${e.category}.${e.stage} ${s}`:`${e.category}.${e.stage}`}function Ng(e){const s=Ds(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return s?`${e.kind}${r} ${s}`:`${e.kind}${r}`}function Cg({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.forEach((i,c)=>{a.push({id:`daemon-log-${i.timestamp}-${c}`,source:"daemon_log",ts:Number(i.timestamp||0),severity:i.level,message:i.message,raw:i.message})}),n.forEach(i=>{a.push({id:`browser-event-${i.id}`,source:"browser_event",ts:Number(i.ts||0),severity:"info",message:Ng(i),topic:i.topic,interactionId:i.interactionId,payload:i.payload})}),r.forEach(i=>{a.push({id:`daemon-trace-${i.id}`,source:"daemon_trace",ts:Number(i.ts||0),severity:i.level,message:Sg(i),category:i.category,stage:i.stage,interactionId:i.interactionId,payload:i.payload})}),s.forEach((i,c)=>{a.push({id:`raw-file-${c}`,source:"raw_file",ts:kg(i,c),severity:jg(i),message:i,raw:i})}),a.sort((i,c)=>i.ts!==c.ts?i.ts-c.ts:Ai(i.source)-Ai(c.source))}function Tg(e){return`${e.source}:${e.severity}:${e.message}`}function Mg(e){const s=e.filter(n=>Mi(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Mi(n.severity))continue;const a=Tg(n),i=r.get(a);i?(i.count+=1,i.firstTs=Math.min(i.firstTs,n.ts),i.lastTs=Math.max(i.lastTs,n.ts)):r.set(a,{key:a,source:n.source,severity:n.severity,message:n.message,count:1,firstTs:n.ts,lastTs:n.ts})}return{totalCount:e.length,issueCount:s.length,latestIssue:s[0]||null,repeatedPatterns:Array.from(r.values()).filter(n=>n.count>1).sort((n,a)=>a.count!==n.count?a.count-n.count:a.lastTs-n.lastTs).slice(0,5)}}function Ag(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Ii(e){const s=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Ag(e.ts)} ${e.severity.toUpperCase()} ${e.source}${s}${r} ${e.message}`.trim()}function Ig({events:e,summary:s,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${s.totalCount}`,`issue_events: ${s.issueCount}`].join(`
|
|
81
|
-
`)),a.push(["[source status]",...r.map(c=>`${c.label}: ${c.status} - ${c.detail}`)].join(`
|
|
82
|
-
`)),s.latestIssue&&a.push(["[latest issue]",Ii(s.latestIssue)].join(`
|
|
83
|
-
`)),s.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...s.repeatedPatterns.map(c=>`${c.count}x ${c.severity.toUpperCase()} ${c.source} ${c.message}`)].join(`
|
|
84
|
-
`));const i=e.slice(-n);return a.push(["[timeline]",...i.length>0?i.map(Ii):["No diagnostic events captured."]].join(`
|
|
85
|
-
`)),a.join(`
|
|
86
|
-
|
|
87
|
-
`)}function Rg(e,s){return s==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):s==="info"?e.filter(r=>r.level!=="debug"):e}function Lg(e,s){return s==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):s==="info"?e.filter(r=>r.level!=="debug"):e}function _g({daemonLogs:e,daemonRawText:s,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:i,quickFilter:c,searchQuery:l,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f}){const b=lg(n,i),S=mg(e,l),g=hg(s,l),h=xg(b,l),k=bg(a,l),p=Rg(S,c),x=c==="all"?g:[],y=Lg(h,c),N=c==="issues"?[]:k,j=gg({daemonLogs:S,daemonRawLines:g,trace:h,webEvents:k}),I=Cg({daemonLogs:p,daemonRawLines:x,trace:y,webEvents:N}),M=Mg(I),w=wg({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f,daemonLogKind:r,daemonLogsCount:S.length,daemonRawLineCount:g.length,traceCount:h.length,webEventCount:k.length});return{filteredDaemonLogs:S,filteredDaemonRawLines:g,filteredTraceEntries:h,filteredWebEvents:k,visibleDaemonLogs:p,visibleDaemonRawLines:x,visibleTraceEntries:y,visibleWebEvents:N,quickFilterCounts:j,diagnosticEvents:I,diagnosticsSummary:M,sourceStates:w}}function Pg(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Fl(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Ma(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 Zn(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 xo(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Dg({event:e}){return t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ma(e.severity)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:Fl(e.ts)}),t.jsx("span",{children:e.severity.toUpperCase()}),t.jsx("span",{children:xo(e.source)}),e.category&&e.stage&&t.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&t.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&t.jsxs("span",{children:["ix=",e.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function Eg({quickFilter:e,quickFilterCounts:s,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return 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:"View"}),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+ (${s.info})`},{id:"issues",label:`Issues (${s.issues})`},{id:"all",label:`All (${s.all})`}].map(f=>t.jsx("button",{type:"button",onClick:()=>a(f.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===f.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:f.label},f.id))}),t.jsx("input",{value:r,onChange:f=>i(f.target.value),placeholder:"Search diagnostics…",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.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),t.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function $g({logLevel:e,traceCategory:s,onLogLevelChange:r,onTraceCategoryChange:n}){return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:t.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>t.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),t.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:ig.map(a=>t.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${s===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function Bg({diagnosticsSummary:e,diagnosticEventsCount:s,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:i,daemonFetchError:c,traceFetchError:l}){var u,f;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((f=e.latestIssue)==null?void 0:f.severity)==="warn"?"warning":"good",m=c||l?"danger":i?"good":"neutral";return t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${Zn(e.issueCount>0?"warning":"good")}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[s," visible event(s) · ",e.issueCount," issue signal(s)"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${Zn(d)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[xo(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),t.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:Fl(e.latestIssue.ts)})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${Zn(m)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:c||l?"Needs attention":i?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Pg(a)]}),t.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(b=>t.jsxs("div",{children:[b.label,": ",b.status]},b.id))})]})]})}function Kg({patterns:e}){return e.length===0?null:t.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),t.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(s=>t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[t.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[s.count,"× ",s.severity.toUpperCase()," · ",xo(s.source)]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:s.message})]},s.key))})]})}function Wg({streams:e,sectionsOpen:s,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:i,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:d,searchQuery:m}){return 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:()=>r(u=>({...u,timeline:!u.timeline})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.timeline?"Hide":"Show"})]}),s.timeline&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&t.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&t.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&t.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>t.jsx(Dg,{event:u},u.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:()=>r(u=>({...u,daemon:!u.daemon})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${i.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.daemon?"Hide":"Show"})]}),s.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:[e.daemonLoading&&a.length===0&&i.length===0&&!e.daemonFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&i.length===0&&e.daemonRawText&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&i.map((u,f)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${f}`)),e.daemonLogKind!=="text"&&a.map((u,f)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Ma(u.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),t.jsx("span",{className:"break-words",children:u.message})]},`log-${f}`))]})]}),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:()=>r(u=>({...u,trace:!u.trace})),children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.trace?"Hide":"Show"})]}),s.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:[e.traceLoading&&c.length===0&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&c.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&c.length===0&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No trace entries match the current search.":e.traceCategory==="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."}),c.map(u=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Ma(u.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),t.jsx("span",{children:u.level.toUpperCase()}),t.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&t.jsxs("span",{children:["ix=",u.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ds(u.payload,360)||"No payload"})]},u.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:()=>r(u=>({...u,web:!u.web})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.web?"Hide":"Show"})]}),s.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:[l.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),l.map(u=>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(u.ts).toLocaleTimeString()}),t.jsx("span",{children:u.kind}),u.topic&&t.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&t.jsxs("span",{children:["ix=",u.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ds(u.payload,360)||"No payload"})]},u.id))]})]})]})}function Og({machineId:e,sendDaemonCommand:s}){const r=vg({machineId:e,sendDaemonCommand:s}),[n,a]=o.useState("info"),[i,c]=o.useState(""),[l,d]=o.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=o.useRef(null),u=o.useRef(!1),f=o.useMemo(()=>_g({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:i,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,i,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);o.useEffect(()=>{if(r.autoRefresh&&f.diagnosticEvents.length>0){const g=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=m.current)==null||h.scrollIntoView({behavior:g}),u.current=!0},50)}},[f.diagnosticEvents.length,r.autoRefresh]);const b=o.useCallback(async()=>{var h;const g=yg({daemonLogs:f.visibleDaemonLogs,daemonRawLines:f.visibleDaemonRawLines,trace:f.visibleTraceEntries,webEvents:f.visibleWebEvents});if(!g.trim()){nt.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(g)),nt.showToast("Copied visible logs to clipboard.","success")}catch(k){nt.showToast(k instanceof Error?k.message:"Could not copy visible logs","warning")}},[f.visibleDaemonLogs,f.visibleDaemonRawLines,f.visibleTraceEntries,f.visibleWebEvents]),S=o.useCallback(async()=>{var h;const g=Ig({events:f.diagnosticEvents,summary:f.diagnosticsSummary,sources:f.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(g)),nt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(k){nt.showToast(k instanceof Error?k.message:"Could not copy diagnostic bundle","warning")}},[f.diagnosticEvents,f.diagnosticsSummary,f.sourceStates]);return t.jsxs("div",{className:"space-y-4",children:[t.jsx(Eg,{quickFilter:n,quickFilterCounts:f.quickFilterCounts,searchQuery:i,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{S()},onCopyVisible:()=>{b()},onToggleAutoRefresh:()=>r.setAutoRefresh(g=>!g),onRefresh:r.refresh,onClear:r.clear}),t.jsx($g,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),t.jsx(Bg,{diagnosticsSummary:f.diagnosticsSummary,diagnosticEventsCount:f.diagnosticEvents.length,sourceStates:f.sourceStates,searchQuery:i,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),t.jsx(Kg,{patterns:f.diagnosticsSummary.repeatedPatterns}),t.jsx(Wg,{streams:r,sectionsOpen:l,setSectionsOpen:d,diagnosticEvents:f.diagnosticEvents,visibleDaemonLogs:f.visibleDaemonLogs,visibleDaemonRawLines:f.visibleDaemonRawLines,visibleTraceEntries:f.visibleTraceEntries,visibleWebEvents:f.visibleWebEvents,quickFilter:n,searchQuery:i}),t.jsx("div",{ref:m})]})}function Fg(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 Hl(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 Hg(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=Hl((i==null?void 0:i.meta)||void 0),d=((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")&&(d||l)?r.push(i):n.push(i)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function Ug(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ea(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 ta(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function sa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ri(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function zg(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Vg(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 Gg(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 qg({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,d]=o.useState(!1),m=lh(e,{enabled:!!e,includeSessions:!0,limit:Ho,intervalMs:mf}),u=m.diagnostics,f=m.loading,b=m.applyDiagnostics,S=o.useMemo(()=>Fg({diagnostics:u,loading:f,refreshing:l,error:n}),[u,f,l,n]),g=o.useMemo(()=>new Map(s.map(_=>[_.sessionId||_.id,_])),[s]),h=o.useCallback(async()=>{if(e){d(!0);try{const _=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Ho}),T=ta(_);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");b(T.diagnostics||T.result||null),a("")}catch(_){const T=_ instanceof Error?_.message:"Could not load hosted runtime diagnostics";a(T)}finally{d(!1)}}},[b,e,r]);o.useEffect(()=>{!e||u||f||l||h()},[u,f,e,h,l]);const k=o.useCallback(async(_,T)=>{const F=`${_}:${T.sessionId}`;if(!(_==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
|
|
88
|
-
This will terminate the hosted runtime.`))){c(F);try{const B=await r(e,_,{sessionId:T.sessionId}),L=ta(B);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Session host action failed");const C=_==="session_host_resume_session"?"resumed":_==="session_host_restart_session"?"restarted":"stopped";nt.showToast(`Session host ${C}: ${T.displayName}`,"success"),await h()}catch(B){const L=B instanceof Error?B.message:"Session host action failed";nt.showToast(L,"warning"),a(L)}finally{c(B=>B===F?null:B)}}},[e,h,r]),p=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
89
|
-
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 T=await r(e,"session_host_prune_duplicate_sessions",{}),F=ta(T);if(!(F!=null&&F.success))throw new Error((F==null?void 0:F.error)||"Duplicate prune failed");const B=F.result||{},L=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,C=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;nt.showToast(`Pruned ${L} duplicate runtime(s) across ${C} group(s)`,"success"),await h()}catch(T){const F=T instanceof Error?T.message:"Duplicate prune failed";nt.showToast(F,"warning"),a(F)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,h,r]),x=o.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((_,T)=>(T.lastActivityAt||0)-(_.lastActivityAt||0)),[u==null?void 0:u.sessions]),y=o.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:Hg(x),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,x]),N=y.liveRuntimes,j=y.recoverySnapshots,I=y.inactiveRecords,M=o.useMemo(()=>Gg(N),[N]),w=o.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),v=o.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[u==null?void 0:u.recentLogs]),$=(_,T)=>{var H;const F=i===`session_host_resume_session:${_.sessionId}`,B=i===`session_host_restart_session:${_.sessionId}`,L=i===`session_host_stop_session:${_.sessionId}`,C=Hl(_.meta),A=g.get(_.sessionId),K=_.attachedClients.length===1?"1 client":`${_.attachedClients.length} clients`,P=T==="recovery"?"Recover":"Resume",D=Ug(T);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:_.displayName||(A==null?void 0:A.cliName)||_.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Vg(_.lifecycle)}`,children:_.lifecycle}),C&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:_.workspaceLabel||(A==null?void 0:A.runtimeWorkspaceLabel)||_.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:_.runtimeKey}),_.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",_.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((H=_.writeOwner)==null?void 0:H.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:zg(_.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(zi,{size:11})," ",K]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Ri(_.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(_.lifecycle==="interrupted"||_.lifecycle==="failed"||_.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{k("session_host_resume_session",_)},children:F?`${P}ing…`:P}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{k("session_host_restart_session",_)},children:B?"Restarting…":"Restart"}),T==="live"&&(_.lifecycle==="running"||_.lifecycle==="starting"||_.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:()=>{k("session_host_stop_session",_)},children:L?"Stopping…":"Stop"})]})]})},_.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(ds,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:hp()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[M>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{p()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${M})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${S.toneClass}`,children:S.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:f||l,children:[t.jsx(cr,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!u&&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(ar,{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})]})]})}),u&&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:u.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:u.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:Ri(u.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:sa(u.hostStartedAt)})]})]}),v&&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(ar,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:v.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[sa(v.timestamp),v.sessionId?` · ${v.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($a,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ea("live")}),N.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:N.map(_=>$(_,"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(ds,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ea("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(_=>$(_,"recovery"))})]}),I.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ea("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(_=>$(_,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),w.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:w.map(_=>{var F;const T=x.find(B=>B.sessionId===_.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:(T==null?void 0:T.displayName)||((F=g.get(_.sessionId))==null?void 0:F.cliName)||_.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[_.action,_.lifecycle?` · ${_.lifecycle}`:"",_.detail?` · ${_.detail}`:"",_.error?` · ${_.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${_.success===!1?"text-red-300":"text-text-secondary"}`,children:sa(_.timestamp)})]},`${_.sessionId}:${_.timestamp}:${_.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Yg({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 ra({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 na({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 Xg({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),d=r.slice(0,4),u=er(e,"0.9.70");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(ra,{icon:t.jsx(Ht,{size:13}),children:"Current Chats"}),t.jsx(na,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const b=ya(f);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:ct(f)}),b>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:dn(b)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:fs(f)})]},f.tabKey)})})})]}),d.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ra,{icon:t.jsx(Yi,{size:13}),children:"Recent Launches"}),t.jsx(na,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const{metaText:b,updatedLabel:S}=wl(f);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),S&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:S})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:b})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ra,{icon:t.jsx(ar,{size:13}),children:"Daemon Update"}),t.jsx(na,{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:u?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"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(cr,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Jg(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function Qg({machine:e,selectedWorkspace:s,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:i,onCustomPathChange:c,onOpenBrowseDialog:l}){return t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:s,onChange:d=>{const m=d.target.value;if(i(m),m==="__custom__"&&a){l();return}m!=="__custom__"&&c("")},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:(e.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>t.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",mn(d.path,d.label)]},d.id)),t.jsx("option",{value:"__custom__",children:a?"📁 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:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),s==="__custom__"&&(a?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:l,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>c(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:s==="__custom__"?r?t.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:s===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const Zg={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 Pr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function aa({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const f=xs(),{handleLaunchIde:b,handleStopCli:S,handleRestartIde:g,handleStopIde:h,handleDetectIdes:k,launchingIde:p,launchingAgentType:x,addLog:y}=c,[N,j]=o.useState(null),I=o.useCallback(R=>{R&&f(Yt(R))},[f]),M=Zg[e],w=e==="ide",v=e==="acp",$=o.useMemo(()=>n.filter(R=>ps(R,e)),[e,n]),_=o.useMemo(()=>new Map($.map(R=>[R.type,R.displayName||R.type])),[$]),[T,F]=o.useState(""),[B,L]=o.useState(""),[C,A]=o.useState([]),[K,P]=o.useState(""),[D,H]=o.useState(""),[Q,be]=o.useState([]),[de,te]=o.useState(!1),[Z,ce]=o.useState(!1),[fe,J]=o.useState(""),[me,ve]=o.useState(!1),[ae,pe]=o.useState(()=>gt()),[je,xe]=o.useState(null),[ge,oe]=o.useState(m?"__custom__":d||s.defaultWorkspaceId||""),[le,ie]=o.useState(m||""),[Y,G]=o.useState([]),[ue,ke]=o.useState(!1),[se,Re]=o.useState(""),[$e,Oe]=o.useState([]),[He,W]=o.useState(!1),[Ce,Te]=o.useState(""),Le=o.useRef(null),[Be,Fe]=o.useState(null),Ye=o.useRef("__home__"),[et,ut]=o.useState("__home__"),[ft,pt]=o.useState(!1),Ne=o.useRef(0),Ue=Y.filter(R=>!a.some(V=>V.type===R&&jt(V.status)!=="stopped")),Xe=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!ge&&oe(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(m){oe("__custom__"),ie(m);return}d&&(oe(d),ie(""))},[d,m]),o.useEffect(()=>{w||T&&($.some(R=>R.type===T)||(F(""),H("")))},[$,w,T]);const Ve=(()=>{if(ge==="__custom__")return le.trim();if(!ge)return"";const R=(s.workspaces||[]).find(V=>V.id===ge);return(R==null?void 0:R.path)||""})(),tt=o.useCallback(R=>{const V=Xe.current[R];V&&(clearTimeout(V),delete Xe.current[R]),G(he=>he.includes(R)?he.filter(De=>De!==R):he)},[]),O=o.useRef(new Set),z=o.useCallback(async R=>{if(l){W(!0),Te("");try{const V=await bn(l,r,R);Re(V.path),ie(V.path),Oe(V.directories)}catch(V){Te(V instanceof Error?V.message:"Could not load folder")}finally{W(!1)}}},[r,l]),q=o.useCallback(()=>{if(!l)return;oe("__custom__"),ke(!0);const R=a.map(he=>he.workspace),V=xn(s.platform,hn(le.trim(),Ve,m,R,s.defaultWorkspacePath,(s.workspaces||[]).map(he=>he.path)));z(V)},[le,m,z,s.defaultWorkspacePath,s.platform,s.workspaces,a,Ve,l]),re=o.useCallback(R=>{const V=String(R.workspace||"").trim();if(!V)return;const he=(s.workspaces||[]).find(De=>Pr(De.path)===Pr(V));if(he){oe(he.id),ie("");return}oe("__custom__"),ie(V)},[s.workspaces]),E=o.useCallback(R=>{const V=String(R.workspace||"").trim();if(!V)return{workspaceId:null,workspacePath:"",useHome:!0};const he=(s.workspaces||[]).find(De=>Pr(De.path)===Pr(V));return he?{workspaceId:he.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:V,useHome:!1}},[s.workspaces]),X=o.useCallback(async R=>{if(!l||!R||e!=="cli"){be([]),te(!1),ce(!1),J("");return}const V=Ne.current+1;Ne.current=V,te(!0),J("");try{const he=await l(r,"list_saved_sessions",{providerType:R,kind:"cli",limit:30});if(Ne.current!==V)return;const De=(he==null?void 0:he.result)??he;be(Array.isArray(De==null?void 0:De.sessions)?De.sessions:[])}catch(he){if(Ne.current!==V)return;be([]),J(he instanceof Error?he.message:"Could not load saved sessions")}finally{Ne.current===V&&(te(!1),ce(!0))}},[e,r,l]),ee=o.useMemo(()=>{if(e!=="cli"||!T)return null;const R=_.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:D||void 0,transport:"pty",mode:"chat",agentName:R,agentType:T,status:"idle",title:R,messages:[],ideType:T,workspaceName:Ve,workspacePath:Ve,displayPrimary:R,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,_,Ve,D,T]),ne=o.useCallback(R=>{if(e==="ide"||!R){A([]);return}A(Dl(r,R))},[e,r]);o.useEffect(()=>{Ne.current+=1,H(""),ne(T),ce(!1),be([]),J(""),te(!1)},[e,ne,X,T]);const we=o.useMemo(()=>Q.find(R=>R.providerSessionId===D)||null,[Q,D]);o.useEffect(()=>{if(!D)return;const R=Q.find(V=>V.providerSessionId===D);R!=null&&R.canResume||H("")},[Q,D]);const Ae=o.useCallback((R,V)=>{Le.current=V,Ye.current=R.selectedWorkspaceKey||"__home__",ut(R.selectedWorkspaceKey||"__home__"),Fe(R)},[]),_e=o.useCallback(()=>{Le.current&&(pt(!0),Le.current().finally(()=>{Le.current=null,pt(!1),Fe(null)}))},[]),Se=o.useCallback(R=>{if(!R)return;G(he=>he.includes(R)?he:[...he,R]);const V=Xe.current[R];V&&clearTimeout(V),Xe.current[R]=setTimeout(()=>{G(he=>he.includes(R)?he.filter(De=>De!==R):he),delete Xe.current[R]},2e4)},[]);o.useEffect(()=>{for(const V of a)jt(V.status)!=="stopped"&&(Y.includes(V.type)&&!O.current.has(V.type)&&(O.current.add(V.type),y("info",`${_.get(V.type)||V.type} launched`,!0)),tt(V.type));const R=new Set(a.filter(V=>jt(V.status)!=="stopped").map(V=>V.type));O.current.forEach(V=>{!Y.includes(V)&&!R.has(V)&&O.current.delete(V)})},[y,tt,a,Y,_]),o.useEffect(()=>()=>{Object.values(Xe.current).forEach(clearTimeout),Xe.current={}},[]);const[Pe,Ee]=o.useState({}),[Ie,Ge]=o.useState(null);o.useEffect(()=>{if(!w||!r||!l)return;(async()=>{try{const V=await l(r,"get_ide_extensions",{}),he=(V==null?void 0:V.result)||V;he!=null&&he.success&&(he!=null&&he.ideExtensions)&&Ee(he.ideExtensions)}catch{}})()},[w,r,l]);const Ze=R=>w?ot(R.type):e==="cli"?R.cliName:R.acpName,it=w?s.detectedIdes||[]:[],lt=o.useCallback(async R=>{const V=(R==null?void 0:R.type)||T,he=(R==null?void 0:R.workspacePath)??Ve;if(w){await b(V,he?{workspace:he}:void 0)&&Se(V);return}const De=await c.runLaunchCliCore({cliType:V,dir:R!=null&&R.workspaceId?void 0:he||void 0,workspaceId:(R==null?void 0:R.workspaceId)||void 0,useHome:(R==null?void 0:R.useHome)||!(R!=null&&R.workspaceId)&&!he,argsStr:(R==null?void 0:R.argsStr)??(B||void 0),model:(R==null?void 0:R.model)??(v&&K||void 0),resumeSessionId:(R==null?void 0:R.resumeSessionId)||!v&&e==="cli"&&V===T&&D||void 0});if(De.success||De.pending){const Me=(R==null?void 0:R.argsStr)??B;!w&&(Me!=null&&Me.trim())&&(El(r,V,Me),ne(V)),Se(V),De.success&&De.sessionId&&I(De.sessionId)}},[c,b,v,w,B,K,ne,Se,r,I,Ve,D,T]),ht=Hc(w?"ide":v?"acp":"cli",!w&&!v&&!!D),bt=Uc(w?"ide":v?"acp":"cli",!w&&!v&&!!D),ze=()=>{var Me;const R=w?ot(T):_.get(T)||T,V=!w&&!v&&!!D,{options:he,selectedKey:De}=cs({machine:s,currentWorkspaceId:ge&&ge!=="__custom__"?ge:null,currentWorkspacePath:Ve});Ae({title:V?eo(R):ns("start-fresh",R),description:V?to():as("start-fresh"),confirmLabel:ht,busyLabel:bt,workspaceOptions:he,selectedWorkspaceKey:De,details:[{label:"Mode",value:M.label},{label:"Provider",value:R},...!w&&e==="cli"&&D?[{label:"Resume",value:((Me=Q.find(Ke=>Ke.providerSessionId===D))==null?void 0:Me.title)||D}]:[],...!w&&B.trim()?[{label:"Arguments",value:B.trim()}]:[],...v&&K.trim()?[{label:"Model",value:K.trim()}]:[]]},async()=>{const Ke=he.find(at=>at.key===Ye.current);Ke!=null&&Ke.workspaceId?(oe(Ke.workspaceId),ie("")):Ke!=null&&Ke.workspacePath?(oe("__custom__"),ie(Ke.workspacePath)):(oe(""),ie("")),await lt({workspaceId:(Ke==null?void 0:Ke.workspaceId)??null,workspacePath:(Ke==null?void 0:Ke.workspacePath)??"",useHome:!(Ke!=null&&Ke.workspaceId)&&!(Ke!=null&&Ke.workspacePath)})})},ye=R=>{w?h(R):S(R.type,R.workspace,R.id)},U=o.useCallback(async(R,V,he=!1)=>{if(R.mode===V){he&&R.sessionId&&I(R.sessionId);return}if(!l||!R.sessionId){he&&R.sessionId&&I(R.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:R.sessionId,cliType:R.type,mode:V}),he&&I(R.sessionId)}catch(De){const Me=cl(De);il(De)?console.warn(Me?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",De instanceof Error?De.message:String(De)):console.error("Failed to switch CLI view mode:",De)}},[r,I,l]);return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${M.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 ",M.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:w?it.length>0?it.map(R=>{const V=a.find(at=>(at.type||"").toLowerCase()===(R.type||"").toLowerCase()&&jt(at.status)!=="stopped"),he=R.running||!!V,De=!!V&&V.cdpConnected,Me=Y.includes(R.type||R.id||""),Ke=T===(R.type||"");return t.jsxs("button",{onClick:()=>{if(De&&V){const at=V.sessionId;at?f(Yt(at),{state:{openRemoteForTabKey:at}}):f("/dashboard",{state:{openRemoteForTabKey:V.id}});return}Me||F(at=>at===(R.type||"")?"":R.type||"")},disabled:!!p||Me,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${De?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ke?"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!==R.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(R.type)}),he&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${De?"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:R.name||ot(R.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${De?"text-green-400":Me?"text-orange-400":Ke?"text-accent-primary":"text-text-muted"}`,children:De?"Open Session":Me?"Starting...":Ke?"Configure":"Select"})]})]},R.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:k,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(Zd,{size:14})," Scan System"]})]}):$.length>0?$.map(R=>{const V=T===R.type,he=Y.includes(R.type),Me=!!a.find(Ke=>Ke.type===R.type&&jt(Ke.status)!=="stopped");return t.jsxs("button",{onClick:()=>F(Ke=>Ke===R.type?"":R.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${V?"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:R.icon}),Me&&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:R.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${he?"text-orange-400":V?"text-accent-primary":"text-text-muted"}`,children:he?"Starting...":V?"Configure":"Select"})]})]},R.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),T&&(w?it.find(R=>R.type===T):$.find(R=>R.type===T))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:w?ot(T):_.get(T)||T})]}),t.jsx(Qg,{machine:s,selectedWorkspace:ge,resolvedWorkspacePath:Ve,customPath:le,canBrowse:!!l,onWorkspaceChange:oe,onCustomPathChange:ie,onOpenBrowseDialog:q}),!w&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&t.jsx(Bl,{busy:!!x||!!p||Y.includes(T),savedSessionsLoading:de,savedSessionsError:fe,savedSessionsLoaded:Z,savedSessionsCount:Q.length,selectedSession:we,onRefresh:()=>void X(T),onOpenHistory:()=>{T&&(ve(!0),$l({hasLoadedInitialResults:Z,isLoading:de})&&X(T))},onClearSelection:()=>H("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:K,onChange:R=>P(R.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:B,onChange:R=>L(R.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"}),C.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:C.map(R=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>L(R),title:R,children:R},R))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:ze,disabled:!!x||!!p||Y.includes(T),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:x===T||p===T?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+Y.filter(R=>!a.some(V=>V.type===R&&jt(V.status)!=="stopped")).length,")"]}),a.length===0&&Ue.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 ",M.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ue.map(R=>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(R)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:w?ot(R):_.get(R)||R}),t.jsx("div",{className:"text-[11px] text-text-muted",children:x===R?"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:${R}`)),a.map(R=>{const V=w?R:null,he=!w&&!v?R:null,De=jt(R.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(R.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ze(R),(V==null?void 0:V.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",V.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[t.jsx("span",{className:"truncate",children:R.workspace||"—"}),u&&R.git&&R.workspace?t.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Me=>{Me.stopPropagation(),u(R.daemonId??r,R.workspace)},children:t.jsx(Ls,{git:R.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):t.jsx(Ls,{git:R.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(he==null?void 0:he.mode)&&t.jsx("span",{className:he.mode==="chat"?"text-violet-400":"text-text-secondary",children:he.mode==="chat"?"Chat view":"Terminal view"})]}),he&&(he.runtimeKey||he.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[he.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 ",he.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 Me;(Me=navigator.clipboard)==null||Me.writeText(`adhdev attach ${he.runtimeKey}`),j(he.runtimeKey||null),window.setTimeout(()=>{j(Ke=>Ke===he.runtimeKey?null:Ke)},1200)},children:N===he.runtimeKey?"Copied":"Copy"})]}),he.runtimeWriteOwner&&t.jsx("span",{style:{color:he.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:he.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Jg(he.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 ${De==="stopped"?"bg-red-500/[0.08] text-red-500":De==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:De}),w&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Me=R.sessionId;if(Me){f(Yt(Me),{state:{openRemoteForTabKey:Me}});return}f("/dashboard",{state:{openRemoteForTabKey:R.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(Tt,{size:13})}),t.jsx("button",{onClick:()=>{const Me=R.workspace||"",{options:Ke,selectedKey:at}=cs({machine:s,currentWorkspacePath:Me});Ae({title:ns("restart-ide",ot(R.type)),description:as("restart-ide"),confirmLabel:_s("restart-ide"),busyLabel:Ps("restart-ide"),workspaceOptions:Ke,selectedWorkspaceKey:at,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ot(R.type)}]},async()=>{const St=Ke.find(zt=>zt.key===Ye.current),mt=(St==null?void 0:St.workspacePath)??"";if(mt&&mt!==Me){await lt({type:R.type,workspacePath:mt});return}await g(R)})},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(cr,{size:14})})]}),v&&t.jsx("button",{onClick:()=>{const Me=R.sessionId;Me&&I(Me)},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:!R.sessionId,children:t.jsx(Ht,{size:14})}),he&&De!=="stopped"&&t.jsxs(t.Fragment,{children:[he.mode&&t.jsx(Ja,{mode:he.mode,onChange:Me=>void U(he,Me,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Me=R.sessionId;Me&&I(Me)},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:!R.sessionId,children:he.mode==="chat"?t.jsx(Ht,{size:14}):t.jsx(Tt,{size:13})})]}),De==="stopped"?t.jsx("button",{onClick:()=>{const Me=R.workspace||"",Ke=w?ot(R.type):Ze(R),{options:at,selectedKey:St}=cs({machine:s,currentWorkspacePath:Me});Ae({title:ns("restart-stopped",Ke),description:as("restart-stopped"),confirmLabel:_s("restart-stopped"),busyLabel:Ps("restart-stopped"),workspaceOptions:at,selectedWorkspaceKey:St,details:[{label:"Mode",value:M.label},{label:"Provider",value:Ke}]},async()=>{const mt=at.find(zt=>zt.key===Ye.current);await lt({type:R.type,workspaceId:(mt==null?void 0:mt.workspaceId)??null,workspacePath:(mt==null?void 0:mt.workspacePath)??"",useHome:!(mt!=null&&mt.workspaceId)&&!(mt!=null&&mt.workspacePath)})})},disabled:Y.includes(R.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:Y.includes(R.type)?"⏳":t.jsx(cn,{size:14})}):t.jsx("button",{onClick:()=>ye(R),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(vt,{size:14})})]})]}),V&&V.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:V.aiAgents.map(Me=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${ac(Me.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Me.name," · ",jt(Me.status)]},Me.id))}),V&&(Pe[V.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:(Pe[V.type]||[]).map(Me=>t.jsxs("button",{disabled:Ie===`${V.type}.${Me.type}`,onClick:async()=>{const Ke=`${V.type}.${Me.type}`;Ge(Ke);try{await l(r,"set_ide_extension",{ideType:V.type,extensionType:Me.type,enabled:!Me.enabled}),Ee(at=>({...at,[V.type]:(at[V.type]||[]).map(St=>St.type===Me.type?{...St,enabled:!St.enabled}:St)}))}catch(at){console.error("Extension toggle failed:",at)}finally{Ge(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 ${Me.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 ${Me.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Me.name,t.jsx("span",{className:"text-[9px] font-normal",children:Me.enabled?"ON":"OFF"})]},Me.type))})]})]},R.id)})]}),ue&&l&&t.jsx(gn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:se,directories:$e,busy:He,error:Ce,confirmLabel:"Use this folder",onClose:()=>ke(!1),onNavigate:R=>{z(R)},onConfirm:R=>{ie(R),oe("__custom__"),ke(!1)}}),Be&&t.jsx(mo,{title:Be.title,description:Be.description,details:Be.details,workspaceOptions:Be.workspaceOptions,selectedWorkspaceKey:et,onWorkspaceChange:R=>{Ye.current=R,ut(R)},confirmLabel:Be.confirmLabel,busyLabel:Be.busyLabel,busy:ft,onConfirm:_e,onCancel:()=>{Le.current=null,Fe(null)}}),me&&ee&&t.jsx(so,{activeConv:ee,ides:[],isCreatingChat:!1,isRefreshingHistory:de,savedSessions:Q,isSavedSessionsLoading:de,isResumingSavedSessionId:je,savedHistoryFilters:ae,missingWorkspaceResumePath:Ve||null,onSavedHistoryFiltersChange:pe,onClose:()=>ve(!1),onNewChat:()=>{H(""),ve(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{X(T)},onResumeSavedSession:R=>{if(!R.canResume||je)return;const V=E(R);H(R.providerSessionId),re(R),xe(R.providerSessionId),ve(!1),lt({type:R.providerType,workspaceId:V.workspaceId,workspacePath:V.workspacePath,useHome:V.useHome,resumeSessionId:R.providerSessionId}).finally(()=>{xe(he=>he===R.providerSessionId?null:he)})}})]})}const Li=[{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 ey({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:f,onOpenGitDialog:b}){var k;const[S,g]=o.useState(d);o.useEffect(()=>{g(d)},[d]);const h=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:Li.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 ${S===p.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>g(p.id),children:[t.jsx("span",{children:p.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${S===p.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:h[p.id]})]},p.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(k=Li.find(p=>p.id===S))==null?void 0:k.helper})]}),S==="ide"&&t.jsx(aa,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b}),S==="cli"&&t.jsx(aa,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b}),S==="acp"&&t.jsx(aa,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b})]})}function ty({onNicknameSynced:e}={}){var ie,Y,G,ue,ke,se,Re,$e,Oe,He;const{id:s}=jd(),r=xs(),n=La(),{sendCommand:a}=xt(),i=mr(),c=rl(),l=Dc(),d=l.ides||[],m=l.initialLoaded??!0,u=d.find(W=>W.id===s&&W.type==="adhdev-daemon"),f=d.some(W=>W.type==="adhdev-daemon"),b=s?(ie=l.connectionRetryStatuses)==null?void 0:ie[s]:void 0,S=!!(b!=null&&b.blocked),[g,h]=o.useState("workspace"),[k,p]=o.useState(null),x=o.useCallback((W,Ce)=>{p({daemonId:W,workspace:Ce})},[]),[y,N]=o.useState("ide"),j=o.useRef(null),[I,M]=o.useState(null),w=o.useRef("__home__"),[v,$]=o.useState("__home__"),[_,T]=o.useState(!1),F=o.useRef(null);o.useEffect(()=>{!s||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,u,s]),o.useEffect(()=>{if(!s||!u||g!=="overview")return;const W=u.machine;(typeof(W==null?void 0:W.cpus)!="number"||typeof(W==null?void 0:W.totalMem)!="number"||typeof(W==null?void 0:W.arch)!="string"||typeof(W==null?void 0:W.release)!="string")&&c(s,{minFreshMs:3e4}).catch(()=>{})},[g,c,u,s]),ch(s&&g==="overview"?[s]:[],{enabled:g==="overview",intervalMs:cf});const B=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},L=Xb({machineId:s,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:F});o.useEffect(()=>nt.onToast(Ce=>{l.setToasts(Le=>{if(Le.some(Ye=>Ye.message===Ce.message&&Ce.timestamp-Ye.timestamp<3e3))return Le;const Fe={id:Ce.id,message:Ce.message,type:Ce.type,timestamp:Ce.timestamp,targetKey:Ce.targetKey,actions:Ce.actions};return[...Le.slice(-4),Fe]});const Te=Ce.duration||5e3;setTimeout(()=>l.setToasts(Le=>Le.filter(Be=>Be.id!==Ce.id)),Te)}),[l]);const C=(u==null?void 0:u.availableProviders)||[],A={};for(const W of C)A[W.type]=W.icon;const K=W=>A[W]||"",P=u?{id:u.id,hostname:oc(u,{fallbackId:u.id}),platform:((Y=u.machine)==null?void 0:Y.platform)||"unknown",arch:((G=u.machine)==null?void 0:G.arch)||"",cpus:((ue=u.machine)==null?void 0:ue.cpus)||0,totalMem:((ke=u.machine)==null?void 0:ke.totalMem)||0,freeMem:(se=u.machine)==null?void 0:se.freeMem,availableMem:(Re=u.machine)==null?void 0:Re.availableMem,loadavg:($e=u.machine)==null?void 0:$e.loadavg,uptime:(Oe=u.machine)==null?void 0:Oe.uptime,release:((He=u.machine)==null?void 0:He.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,D=d.filter(W=>W.daemonId===s&&W.type!=="adhdev-daemon").filter(W=>!or(W)&&!Ss(W)).map(W=>({id:W.id,sessionId:W.sessionId,type:W.type,version:W.version||"",instanceId:W.instanceId||"",status:W.status,workspace:W.workspace||null,terminals:W.terminals||0,aiAgents:tm(W.aiAgents||(W.agents||[]).map(Ce=>({id:Ce.name,name:Ce.name,status:Ce.status,version:Ce.version}))),activeChat:W.activeChat||null,chats:W.chats||[],childSessions:W.childSessions||[],cdpConnected:W.cdpConnected||!1,daemonId:s})),H=d.filter(W=>W.daemonId===s&&or(W)).map(W=>({id:W.id,sessionId:W.sessionId,type:W.type,cliName:W.cliName||W.type,status:W.status,workspace:W.workspace||"",activeChat:W.activeChat||null,providerSessionId:W.providerSessionId,mode:W.mode,runtimeKey:W.runtimeKey,runtimeDisplayName:W.runtimeDisplayName,runtimeWorkspaceLabel:W.runtimeWorkspaceLabel,runtimeWriteOwner:W.runtimeWriteOwner||null,runtimeAttachedClients:W.runtimeAttachedClients||[],daemonId:s})),Q=d.filter(W=>W.daemonId===s&&Ss(W)).map(W=>({id:W.id,sessionId:W.sessionId,type:W.type,acpName:W.cliName||W.type,status:W.status,workspace:W.workspace||"",activeChat:W.activeChat||null,providerSessionId:W.providerSessionId,daemonId:s})),be=u?Ct(u,{fallbackId:s}):"",de="workspace",te=n.state,Z=te==null?void 0:te.initialMachineTab,ce=te==null?void 0:te.initialWorkspaceCategory,fe=te==null?void 0:te.initialWorkspaceId,J=te==null?void 0:te.initialWorkspacePath,me=Z==="ides"||Z==="clis"||Z==="acps"?"workspace":Z||de,ve=Z==="ides"?"ide":Z==="clis"?"cli":Z==="acps"?"acp":ce,ae=[...D.map(W=>{var Ce,Te,Le,Be,Fe;return{id:`ide:${W.type}:${W.workspace||""}`,label:((Ce=W.activeChat)==null?void 0:Ce.title)||W.type,kind:"ide",providerType:W.type,subtitle:W.workspace||void 0,workspace:W.workspace||void 0,lastLaunchedAt:((Fe=(Be=(Le=(Te=W.activeChat)==null?void 0:Te.messages)==null?void 0:Le.at)==null?void 0:Be.call(Le,-1))==null?void 0:Fe.timestamp)||0}}),...H.map(W=>{var Ce,Te,Le,Be,Fe;return{id:`cli:${W.type}:${W.workspace||""}`,label:((Ce=W.activeChat)==null?void 0:Ce.title)||W.cliName,kind:"cli",providerType:W.type,providerSessionId:W.providerSessionId,subtitle:W.workspace||void 0,workspace:W.workspace||void 0,lastLaunchedAt:((Fe=(Be=(Le=(Te=W.activeChat)==null?void 0:Te.messages)==null?void 0:Le.at)==null?void 0:Be.call(Le,-1))==null?void 0:Fe.timestamp)||0}}),...Q.map(W=>{var Ce,Te,Le,Be,Fe;return{id:`acp:${W.type}:${W.workspace||""}`,label:((Ce=W.activeChat)==null?void 0:Ce.title)||W.acpName,kind:"acp",providerType:W.type,providerSessionId:W.providerSessionId,subtitle:ms(W.summaryMetadata)||W.workspace||void 0,workspace:W.workspace||void 0,lastLaunchedAt:((Fe=(Be=(Le=(Te=W.activeChat)==null?void 0:Te.messages)==null?void 0:Le.at)==null?void 0:Be.call(Le,-1))==null?void 0:Fe.timestamp)||0}})].sort((W,Ce)=>(Ce.lastLaunchedAt||0)-(W.lastLaunchedAt||0)),pe=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(W=>({id:W.id,label:W.title||W.providerName||W.providerType,kind:W.kind,providerType:W.providerType,providerSessionId:W.providerSessionId,subtitle:ms(W.summaryMetadata)||W.workspace||void 0,workspace:W.workspace,summaryMetadata:W.summaryMetadata,lastLaunchedAt:W.lastLaunchedAt})):ae,je=o.useMemo(()=>{var Ce;const W=((Ce=l.connectionStates)==null?void 0:Ce[s||""])||void 0;return d.filter(Te=>Te.daemonId===s&&Te.type!=="adhdev-daemon").flatMap(Te=>ro(Te,{connectionStates:s&&W?{[s]:W}:void 0,defaultConnectionState:W})).filter(Te=>!(Te.transport==="pty"&&Te.mode==="terminal")).sort((Te,Le)=>ya(Le)-ya(Te))},[d,l.connectionStates,s]),xe=o.useCallback(W=>{const Ce=Ya(W);Ce&&r(Yt(Ce))},[r]),ge=o.useCallback(()=>{j.current&&(T(!0),j.current().finally(()=>{j.current=null,T(!1),M(null)}))},[]),oe=o.useCallback(W=>{if(!P)return;const{options:Ce,selectedKey:Te}=cs({machine:P,currentWorkspacePath:W.workspace}),Le=async()=>{N(W.kind),h("workspace")};j.current=async()=>{const Be=Ce.find(et=>et.key===w.current),Fe=(Be==null?void 0:Be.workspacePath)??null,Ye=(Be==null?void 0:Be.workspaceId)??null;if(W.kind==="ide"&&W.providerType){await L.handleLaunchIde(W.providerType,Fe?{workspace:Fe}:void 0);return}if((W.kind==="cli"||W.kind==="acp")&&W.providerType){await L.runLaunchCliCore({cliType:W.providerType,dir:Ye?void 0:Fe||"",workspaceId:Ye||void 0,model:W.kind==="acp"&&cc(W.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:W.providerSessionId});return}await Le()},w.current=Te,$(Te),M({title:W.kind==="ide"?ns("restart-ide",W.label):W.providerSessionId?eo(W.label):ns("start-fresh",W.label),description:W.kind==="ide"?as("restart-ide"):W.providerSessionId?to():as("start-fresh"),confirmLabel:W.kind==="ide"?_s("restart-ide"):W.providerSessionId?en(!0):_s("start-fresh"),busyLabel:W.kind==="ide"?Ps("restart-ide"):W.providerSessionId?Qa(!0):Ps("start-fresh"),workspaceOptions:Ce,details:[{label:"Mode",value:W.kind.toUpperCase()},...W.providerType?[{label:"Provider",value:W.providerType}]:[]]})},[L,P]);if(o.useEffect(()=>{h(me)},[de,me,s]),o.useEffect(()=>{ve&&N(ve)},[ve,s]),!P)return m?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:B,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 le=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tt,{size:14})," Workspace"]}),count:D.length+H.length+Q.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ds,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(on,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(eu,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Jd,{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:B,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:[L.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:L.nicknameInput,onChange:W=>L.setNicknameInput(W.target.value),onKeyDown:W=>{W.key==="Enter"&&L.handleSaveNickname(),W.key==="Escape"&&L.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:L.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:()=>L.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:()=>{L.setEditingNickname(!0),L.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:be}),S?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),l.retryConnection&&s&&t.jsx("button",{onClick:()=>l.retryConnection(s),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):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:[P.platform," · ",P.arch]}),t.jsxs("span",{children:[P.cpus," cores"]}),(u==null?void 0:u.version)&&t.jsxs("span",{children:["v",u.version]}),P.p2p.available&&t.jsxs("span",{children:["P2P ",P.p2p.state==="connected"?"connected":P.p2p.state]}),P.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:P.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:le.map(W=>t.jsxs("button",{onClick:()=>h(W.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${g===W.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[W.label,W.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${g===W.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:W.count})]},W.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[g==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Xg,{machineEntry:u,providers:C,recentLaunches:pe,currentConversations:je,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:oe,onOpenConversation:xe}),t.jsx(ey,{machine:P,machineId:s,providers:C,ideSessions:D,cliSessions:H,acpSessions:Q,actions:L,getIcon:K,initialCategory:y,initialWorkspaceId:fe,initialWorkspacePath:J,sendDaemonCommand:a,onOpenGitDialog:x})]}),g==="providers"&&t.jsx(og,{machineId:s,providers:C,sendDaemonCommand:a}),g==="overview"&&t.jsx(Jb,{machineId:s,machine:P,ideSessions:D,cliSessions:H,acpSessions:Q,actions:L,sendDaemonCommand:a}),g==="session-host"&&t.jsx(qg,{machineId:s,cliSessions:H,sendDaemonCommand:a}),g==="logs"&&t.jsx(Og,{machineId:s,sendDaemonCommand:a})]})})}),L.launchPick&&P&&t.jsx(Yg,{machine:P,launchPick:L.launchPick,actions:L}),I&&t.jsx(mo,{title:I.title,description:I.description,details:I.details,workspaceOptions:I.workspaceOptions,selectedWorkspaceKey:v,onWorkspaceChange:W=>{w.current=W,$(W)},confirmLabel:I.confirmLabel,busyLabel:I.busyLabel,busy:_,onConfirm:ge,onCancel:()=>{j.current=null,M(null)}}),k&&t.jsx(Ol,{daemonId:k.daemonId,workspace:k.workspace,onClose:()=>p(null)}),t.jsx(zc,{toasts:l.toasts||[],onDismiss:W=>l.setToasts(Ce=>Ce.filter(Te=>Te.id!==W)),onClickToast:W=>{W.targetKey&&r(Yt(W.targetKey))}}),t.jsx("style",{children:`
|
|
90
|
-
@keyframes toast-in {
|
|
91
|
-
from { opacity: 0; transform: translateX(40px); }
|
|
92
|
-
to { opacity: 1; transform: translateX(0); }
|
|
93
|
-
}
|
|
94
|
-
`})]})}function sy(){var de,te;const{sendCommand:e}=xt(),{ides:s}=Xt(),r=xs(),n=s.find(Z=>Z.daemonMode||Z.type==="adhdev-daemon"),a=(n==null?void 0:n.id)||"",i=[];if(n){const Z=n.availableProviders||[];for(const ce of Z)ce.category==="cli"&&i.push({id:ce.type||ce.id,name:ce.displayName||ce.name||ce.type,meshCoordinator:ce.meshCoordinator})}const[c,l]=o.useState([]),[d,m]=o.useState(null),[u,f]=o.useState(!0),[b,S]=o.useState(null),[g,h]=o.useState(null),[k,p]=o.useState(!1),[x,y]=o.useState(""),[N,j]=o.useState(""),[I,M]=o.useState(!1),[w,v]=o.useState(""),[$,_]=o.useState(""),[T,F]=o.useState(!1),B=c.find(Z=>Z.id===d)||null,L=i.find(Z=>Z.id===$)||null,C=xl(L==null?void 0:L.meshCoordinator,{meshId:(B==null?void 0:B.id)||"",workspace:((de=B==null?void 0:B.nodes[0])==null?void 0:de.workspace)||""}),A=g||C,K=o.useCallback(async()=>{if(a){f(!0);try{const Z=await e(a,"list_meshes");Z!=null&&Z.success?(l(Z.meshes||[]),S(null)):S((Z==null?void 0:Z.error)||"Failed to load meshes")}catch(Z){S((Z==null?void 0:Z.message)||"Failed to load meshes")}finally{f(!1)}}},[a,e]);o.useEffect(()=>{K()},[K]);async function P(){var Z;if(!(!a||!x.trim()))try{const ce=await e(a,"create_mesh",{name:x.trim(),repoIdentity:N.trim()||void 0});ce!=null&&ce.success?(p(!1),y(""),j(""),await K(),m(((Z=ce.mesh)==null?void 0:Z.id)||null)):S((ce==null?void 0:ce.error)||"Create failed")}catch(ce){S((ce==null?void 0:ce.message)||"Create failed")}}async function D(Z){if(!(!a||!confirm("Delete this mesh?")))try{await e(a,"delete_mesh",{meshId:Z}),m(null),await K()}catch(ce){S((ce==null?void 0:ce.message)||"Delete failed")}}async function H(){if(!(!a||!d||!w.trim()))try{const Z=await e(a,"add_mesh_node",{meshId:d,workspace:w.trim()});Z!=null&&Z.success?(M(!1),v(""),await K()):S((Z==null?void 0:Z.error)||"Add node failed")}catch(Z){S((Z==null?void 0:Z.message)||"Add node failed")}}async function Q(Z){if(!(!a||!d))try{await e(a,"remove_mesh_node",{meshId:d,nodeId:Z}),await K()}catch(ce){S((ce==null?void 0:ce.message)||"Remove node failed")}}async function be(){var ce;if(!a||!B||!$)return;if(!(((ce=B.nodes[0])==null?void 0:ce.workspace)||"")){S("Add at least one node (workspace) before launching a coordinator.");return}F(!0),S(null),h(null);try{const fe=await e(a,"launch_mesh_coordinator",{meshId:B.id,cliType:$}),J=bl((fe==null?void 0:fe.meshCoordinatorSetup)||(fe==null?void 0:fe.manualSetup));fe!=null&&fe.success?r("/dashboard"):(fe==null?void 0:fe.code)==="mesh_coordinator_manual_mcp_setup_required"&&J?h(J):S((fe==null?void 0:fe.error)||"Failed to launch coordinator session")}catch(fe){S((fe==null?void 0:fe.message)||"Failed to launch coordinator session")}finally{F(!1)}}return a?B?t.jsxs(Zs,{icon:t.jsx(vr,{}),title:B.name,subtitle:B.repoIdentity||"Repo Mesh",actions:t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(null),children:"← Back"}),t.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>D(B.id),children:"Delete"})]}),children:[b&&t.jsx(ks,{variant:"error",className:"mb-4",children:b}),t.jsxs(yt,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[t.jsx("div",{className:"flex justify-end mb-3",children:t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>M(!0),children:"+ Add Node"})}),I&&t.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[t.jsxs("div",{className:"flex justify-between items-center mb-3",children:[t.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),t.jsx("button",{onClick:()=>M(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:t.jsx(vt,{size:16})})]}),t.jsx(_n,{label:"Workspace Path",children:t.jsx(Pn,{value:w,onChange:Z=>v(Z.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:Z=>{Z.key==="Enter"&&H()},autoFocus:!0})}),t.jsxs("div",{className:"flex gap-2 mt-3",children:[t.jsx("button",{onClick:H,disabled:!w.trim(),className:"btn btn-primary btn-sm",children:"Add"}),t.jsx("button",{onClick:()=>M(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),B.nodes.length===0?t.jsx(tn,{icon:t.jsx(us,{}),title:"No nodes",description:"Add a workspace to this mesh."}):t.jsx("div",{className:"flex flex-col gap-2",children:B.nodes.map(Z=>t.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border border-border-subtle bg-bg-primary",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium",children:Z.workspace.split("/").pop()}),t.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:Z.workspace})]}),t.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:()=>Q(Z.id),children:t.jsx(vt,{size:14})})]},Z.id))})]}),t.jsxs(yt,{title:"Coordinator",description:"Launch a CLI agent session with mesh context — just like the + button on the dashboard.",children:[B.nodes.length===0?t.jsx("div",{className:"text-[11px] text-text-muted",children:"Add at least one node before launching a coordinator."}):t.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[t.jsxs("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2 text-sm focus:border-accent focus:outline-none transition-colors min-w-[180px]",value:$,onChange:Z=>{_(Z.target.value),h(null)},children:[t.jsx("option",{value:"",children:"Select CLI agent…"}),i.map(Z=>t.jsx("option",{value:Z.id,children:Z.name},Z.id)),i.length===0&&t.jsx("option",{value:"",disabled:!0,children:"No CLI agents detected"})]}),t.jsxs("button",{className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",disabled:!$||T,onClick:be,children:[t.jsx(cn,{size:14}),T?"Launching…":"Launch Coordinator"]})]}),A&&t.jsx(Kl,{setup:A,providerName:(L==null?void 0:L.name)||$,className:"mt-3"}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-3",children:["Launches a new CLI session on ",t.jsx("strong",{children:((te=B.nodes[0])==null?void 0:te.workspace.split("/").pop())||"…"})," workspace. The session opens in the dashboard like any other agent session."]})]}),t.jsx(yt,{title:"External MCP Config",description:"For connecting external AI agents (Claude Desktop, etc.) to this mesh.",children:t.jsx("pre",{className:"text-xs bg-bg-secondary rounded-lg p-3 overflow-x-auto border border-border-subtle font-mono select-all",children:`{
|
|
95
|
-
"mcpServers": {
|
|
96
|
-
"adhdev-mesh": {
|
|
97
|
-
"command": "adhdev-mcp",
|
|
98
|
-
"args": ["--repo-mesh", "${B.id}"]
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
}`})})]}):t.jsxs(Zs,{icon:t.jsx(vr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>p(!0),children:"+ Create Mesh"}),children:[b&&t.jsx(ks,{variant:"error",className:"mb-4",children:b}),k&&t.jsx(yt,{title:"New Mesh",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(_n,{label:"Name",children:t.jsx(Pn,{value:x,onChange:Z=>y(Z.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),t.jsx(_n,{label:"Repo Identity (optional)",children:t.jsx(Pn,{value:N,onChange:Z=>j(Z.target.value),placeholder:"github.com/user/repo"})}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:P,disabled:!x.trim(),children:"Create"}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>p(!1),children:"Cancel"})]})]})}),u?t.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):c.length===0?t.jsx(tn,{icon:t.jsx(vr,{}),title:"No meshes",description:"Create a mesh to get started."}):t.jsx("div",{className:"flex flex-col gap-2",children:c.map(Z=>t.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>m(Z.id),children:[t.jsx("div",{className:"font-semibold text-sm",children:Z.name}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:Z.repoIdentity||"No repo identity"}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[Z.nodes.length," node(s)"]})]},Z.id))})]}):t.jsx(Zs,{icon:t.jsx(vr,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:t.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function bo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function ry(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=bo();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 Dt(e,s){return await fetch(ry(e),{credentials:"same-origin",...s})}function Ul(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class ny{constructor(){Je(this,"adapters",new Map);Je(this,"states",new Map);Je(this,"runtimeListeners",new Map);Je(this,"screenshotCallbacks",new Map);Je(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,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const i=await Dt(`${a.pathname}${a.search}`);if(!i.ok){let l=`Runtime snapshot unavailable (${i.status})`;try{const d=await i.json();d!=null&&d.error&&(l=d.error)}catch{}return{success:!1,error:l}}const c=await i.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof c.seq=="number"?c.seq:0,text:typeof c.text=="string"?c.text:"",truncated:!!c.truncated,cols:typeof c.cols=="number"?c.cols:void 0,rows:typeof c.rows=="number"?c.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Kt=new ny;function ay(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=bo();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Dr=ay(),_i=3e3,oy=3e4;let Lt=null,iy=0;const an=new Map;let Qt=null,sr=null;function Pi(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Vs(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function cy(e){return e==="connected"?"connected":e}async function Ur(e,s,r){const n=qc(e,r||{}),a=Lt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++iy}_${Date.now()}`;return new Promise((c,l)=>{const d=setTimeout(()=>{an.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);an.set(i,{resolve:m=>{clearTimeout(d),c(m)},reject:m=>{clearTimeout(d),l(m)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function Aa(e,s){const r=Lt;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}function ly(e,s,r){const n=Lt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=qc(e,{sessionId:s,targetSessionId:s,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class dy{constructor(s){Je(this,"daemonId");Je(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Lt==null?void 0:Lt.readyState)===WebSocket.OPEN}get connectionState(){return(Lt==null?void 0:Lt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Ur(this.daemonId,s,r)}async sendInput(s,r){return Ur(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Qt&&(clearInterval(Qt),Qt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Ur(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());Kt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Qt=setInterval(r,2e3)}stopScreenshots(s){Qt&&(clearInterval(Qt),Qt=null)}}let At=null;function uy(e){return(!At||At.daemonId!==e)&&(At=new dy(e)),At}function my({children:e}){const s=o.useRef(nr()),r=nr();s.current=r;const{setUserName:n}=Xt(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),d=o.useCallback((h,k)=>{l(h),sr==null||sr(h,k)},[]),m=o.useRef(null),u=o.useRef(),f=o.useRef(_i),b=o.useRef(!0),S=o.useRef(!1),g=o.useRef("initial_connect");return o.useEffect(()=>{b.current=!0,S.current=!1;function h(){var x,y;if(!b.current||((x=m.current)==null?void 0:x.readyState)===WebSocket.OPEN||((y=m.current)==null?void 0:y.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Dr}...`),Vs("connect_attempt",{url:Dr,reason:g.current,delayMs:f.current});let p;try{p=new WebSocket(Dr)}catch(N){console.error("[Standalone WS] Failed to create WebSocket:",N),k();return}m.current=p,p.onopen=()=>{if(!b.current){p.close();return}d("connected"),f.current=_i,Vs("open",{url:Dr,reason:g.current}),Ft.resubscribeAll({sendData:Aa}),console.log("[Standalone WS] Connected")},Lt=p,p.onmessage=N=>{var j,I;try{const M=JSON.parse(N.data);if((M.type==="command_result"||M.type==="error")&&M.requestId){const w=an.get(M.requestId);w&&(an.delete(M.requestId),M.type==="error"?w.reject(new Error(((j=M.data)==null?void 0:j.message)||"Command failed")):w.resolve(M.data));return}if(M.type==="session_output"){const w=M.sessionId||M.cliId||M.cliType;w&&Kt.emitSessionOutput(w,typeof M.data=="string"?M.data:"",typeof M.seq=="number"?M.seq:void 0);return}if(M.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(M.sessionId,typeof M.text=="string"?M.text:"",typeof M.seq=="number"?M.seq:0,!!M.truncated,typeof M.cols=="number"?M.cols:void 0,typeof M.rows=="number"?M.rows:void 0);return}if(M.type==="topic_update"){const w=M.update;w&&Ft.publish(w);return}if(M.type==="status"||M.type==="initial_state"){const w=M.data;if(!w)return;const{injectEntries:v,markLoaded:$,getIdes:_}=s.current,T=w.instanceId||"standalone",F=_().find(C=>C.id===T),B=uy(T);Kt.register(T,B),Kt.setState(T,"connected"),d("connected",T),Kt.emitStatus(T,w);const L=Zr(w,{daemonId:T,existingDaemon:F,existingEntries:_()});Pi("ws_status",{type:M.type,daemonId:T,sessions:(w.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(w.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Pi("entries",{daemonId:T,entries:L.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),L.length>0&&v(L,{authoritativeDaemonIds:[T]}),$(),c.current!==T&&((I=i.current)==null||I.call(i),c.current=T,i.current=Ft.subscribe({sendData:Aa},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const A=s.current.getIdes(),K=A.find(D=>D.id===T),P=Zr(C.status,{daemonId:T,existingDaemon:K,existingEntries:A,timestamp:C.timestamp});P.length>0&&s.current.injectEntries(P,{authoritativeDaemonIds:[T]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(M){console.error("[Standalone WS] Parse error:",M)}},p.onclose=N=>{b.current&&(At==null||At.stopScreenshots(),At&&Kt.setState(At.daemonId,"disconnected"),d("disconnected"),m.current=null,g.current=`close:${N.code}${N.wasClean?":clean":":unclean"}`,Vs("close",{code:N.code,reason:N.reason||"",wasClean:N.wasClean}),k())},p.onerror=N=>{S.current||!b.current||(g.current="error",Vs("error",{message:N instanceof Event?"event":String(N),readyState:p.readyState}),console.warn("[Standalone WS] Error, will reconnect:",N))}}function k(){if(!b.current)return;clearTimeout(u.current);const p=f.current;console.log(`[Standalone WS] Reconnecting in ${p}ms...`),Vs("schedule_reconnect",{reason:g.current,delayMs:p}),u.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,oy),h()},p)}return h(),()=>{var p;b.current=!1,S.current=!0,(p=i.current)==null||p.call(i),i.current=null,c.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Lt=null),At&&(At.stopScreenshots(),Kt.unregister(At.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function fy({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(sr=(c,l)=>{r(c),l&&a(l)},()=>{sr=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=cy(s),d={};return n&&(d[n]=l),d.standalone=l,{wsStatus:s,isConnected:c,connectionStates:d}},[s,n]);return t.jsx(Wd,{connectionOverrides:i,children:t.jsx(my,{children:e})})}const zl="adhdev_standalone_font_preferences",ls={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},wn=[{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"}],ir=[{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"}],py=new Set(wn.map(e=>e.id)),hy=new Set(ir.map(e=>e.id));function $t(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=ls[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"?py:hy).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Vr(e,s){var a;const r=zr(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?wn:ir;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function xy(e){const s=$t(e),r=Vr("chat",s.chat),n=Vr("code",s.code),a=Vr("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function es(e,s=document.documentElement){const r=$t(e),n=xy(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))s.style.setProperty(a,i);return r}function Ia(e){const s=$t(e);try{localStorage.setItem(zl,JSON.stringify(s))}catch{}return s}function by(){try{const e=localStorage.getItem(zl);if(e)return $t(JSON.parse(e))}catch{}return ls}function gy(){return es(by())}function Gs(e,s){var n;const r=e==="chat"?wn:ir;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const yy=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Ui,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(ds,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:t.jsx(As,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:t.jsx(on,{}),label:"Settings"}];function vy({children:e}){const s=xs(),r=La(),n=o.useMemo(()=>yy.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>s(i.path)})),[r.pathname,s]),a=o.useMemo(()=>[{id:"docs",label:t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Docs"}),t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:t.jsx(Vi,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:t.jsx(Gi,{}),active:r.pathname==="/about",onSelect:()=>s("/about"),title:"About"}],[r.pathname,s]);return t.jsx(Pp,{brand:({collapsed:i})=>t.jsxs(t.Fragment,{children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.70"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const wy=[{icon:t.jsx(ds,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Ht,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(qi,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Tt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(As,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Vi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],jy=[{icon:t.jsx(su,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Ui,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(ln,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Xd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(zi,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Qd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],ky=[{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 Sy(){return t.jsxs(Zs,{icon:t.jsx(Gi,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.70"]}),children:[t.jsx(yt,{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(yt,{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:wy.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(yt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Yc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Jc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Xc.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:s},s))})]},e.label))})}),t.jsx(yt,{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:jy.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(yt,{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:ky.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(tn,{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(mu,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function oa(e,s,r){return{...e,[s]:r}}function ia({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:Vr(e,n)})]})]})]})}function Ny({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:d}){const m=JSON.stringify(e)!==JSON.stringify(s);return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&t.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),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(ia,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:wn,onChange:u=>i(oa(e,"chat",u))}),t.jsx(ia,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:ir,onChange:u=>i(oa(e,"code",u))}),t.jsx(ia,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:ir,onChange:u=>i(oa(e,"terminal",u))})]}),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: ",Gs("chat",e.chat.preset)," · Code: ",Gs("code",e.code.preset)," · Terminal: ",Gs("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",Gs("chat",ls.chat.preset)," / ",Gs("code",ls.code.preset)]})]}),t.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:t.jsxs("div",{className:"chat-container-content",children:[t.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:t.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[t.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[t.jsx("span",{className:"chat-sender",children:"Hermes"}),t.jsx("span",{className:"chat-time",children:"now"})]}),t.jsxs("div",{className:"chat-markdown",children:[t.jsxs("p",{children:["Readable prose, ",t.jsx("strong",{children:"bold text"}),", and ",t.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),t.jsx("pre",{children:t.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),t.jsxs("div",{className:"chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"▸"}),t.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),t.jsxs("div",{className:"chat-msg-terminal",children:[t.jsx("div",{className:"chat-msg-header",children:"Terminal"}),t.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:c,disabled:r||!m,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),t.jsx("button",{type:"button",onClick:l,disabled:r||!m,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),t.jsx("button",{type:"button",onClick:d,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 Cy(){const{ides:e}=Xt(),s=e.find(J=>J.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=xt(),{userName:a}=Xt(),[i,c]=o.useState(a||""),[l,d]=o.useState(null),[m,u]=o.useState(null),[f,b]=o.useState(ls),[S,g]=o.useState(!1),[h,k]=o.useState(""),[p,x]=o.useState(""),[y,N]=o.useState("127.0.0.1"),[j,I]=o.useState(""),[M,w]=o.useState(""),[v,$]=o.useState(""),[_,T]=o.useState(""),[F,B]=o.useState(""),[L,C]=o.useState(!1),A=async()=>{const me=await(await Dt("/auth/session")).json();d(me)},K=async()=>{const me=await(await Dt("/api/v1/standalone/preferences")).json();u(me),N(me.standaloneBindHost);const ve=$t(me.standaloneFontPreferences);b(ve),es(ve),Ia(ve)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([A(),K()]).catch(J=>{T(J instanceof Error?J.message:String(J))})},[]),o.useEffect(()=>{es(f)},[f]);const P=J=>{const me=J.target.value.trim();s!=null&&s.id&&me!==a&&n(s.id,"set_user_name",{userName:me}).catch(console.error)},[D,H]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Q=J=>{H(J);try{localStorage.setItem("adhdev_sound",J?"1":"0")}catch{}},be=async()=>{k(""),x(""),g(!0);try{const J=$t(f),me=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:J})}),ve=await me.json();if(!me.ok)throw new Error((ve==null?void 0:ve.error)||"Failed to save standalone font preferences");const ae=$t(ve.standaloneFontPreferences);u(ve),b(ae),es(ae),Ia(ae),x("Standalone chat fonts saved for this self-hosted dashboard.")}catch(J){k(J instanceof Error?J.message:String(J))}finally{g(!1)}},de=()=>{const J=$t(m==null?void 0:m.standaloneFontPreferences);k(""),x(""),b(J),es(J)},te=()=>{k(""),x(""),b(ls),es(ls)},Z=async()=>{T(""),B(""),C(!0);try{const J=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:y})}),me=await J.json();if(!J.ok)throw new Error((me==null?void 0:me.error)||"Failed to save standalone network preference");u(me),N(me.standaloneBindHost),B(me.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(J){T(J instanceof Error?J.message:String(J))}finally{C(!1)}},ce=async()=>{if(T(""),B(""),M.trim().length<4){T("Password must be at least 4 characters.");return}if(M!==v){T("New password and confirmation do not match.");return}C(!0);try{const J=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,newPassword:M})}),me=await J.json();if(!J.ok)throw new Error((me==null?void 0:me.error)||"Failed to save password");d(me),await K(),I(""),w(""),$(""),B(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Ul()}catch(J){T(J instanceof Error?J.message:String(J))}finally{C(!1)}},fe=async()=>{T(""),B(""),C(!0);try{const J=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,clear:!0})}),me=await J.json();if(!J.ok)throw new Error((me==null?void 0:me.error)||"Failed to clear password");d(me),await K(),I(""),w(""),$(""),B("Standalone password disabled.")}catch(J){T(J instanceof Error?J.message:String(J))}finally{C(!1)}};return t.jsxs(Zs,{icon:t.jsx(on,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(ks,{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(ks,{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(yt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.70"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(yt,{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:y==="127.0.0.1",onChange:()=>N("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:y==="0.0.0.0",onChange:()=>N("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:()=>{Z()},disabled:L,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:L?"Saving…":"Save default network mode"}),t.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(yt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),_&&t.jsx(ks,{variant:"error",children:_}),F&&t.jsx(ks,{variant:"success",children:F}),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:J=>I(J.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:M,onChange:J=>w(J.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:v,onChange:J=>$(J.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{ce()},disabled:L,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:L?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{fe()},disabled:L,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(yt,{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(J=>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 ${J.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:J.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:J.type})]},J.type))})}),t.jsx(yt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Hp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(yt,{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(Gp,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),t.jsx(th,{})]}),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(Ny,{value:f,savedValue:$t(m==null?void 0:m.standaloneFontPreferences),saving:S,error:h,notice:p,onChange:b,onSave:()=>{be()},onResetToSaved:de,onResetToDefaults:te})]}),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(nh,{})]})]})}),t.jsx(yt,{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(Wp,{}),t.jsx(Zt,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(uu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:D,onChange:Q})]})}),t.jsx(yt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(Yd,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:J=>c(J.target.value),onBlur:P,onKeyDown:J=>{J.key==="Enter"&&J.currentTarget.blur()}})]})})})]})}Lp();Zp();gy();const Ty=Fi({baseUrl:"",getToken:bo});function My({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,d]=o.useState(""),[m,u]=o.useState(!1),f=async()=>{a(!0),d("");try{const g=await(await Dt("/auth/session")).json();r(g)}catch(S){d(S instanceof Error?S.message:String(S))}finally{a(!1)}};o.useEffect(()=>{f()},[]),o.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let S=!1;return(async()=>{try{const g=await Dt("/api/v1/standalone/preferences");if(!g.ok)return;const h=await g.json();if(S)return;const k=$t(h.standaloneFontPreferences);es(k),Ia(k)}catch{}})(),()=>{S=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const b=async S=>{S.preventDefault(),u(!0),d("");try{const g=await Dt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),h=await g.json();if(!g.ok)throw new Error((h==null?void 0:h.error)||"Login failed");r(h),c(""),Ul()}catch(g){d(g instanceof Error?g.message:String(g))}finally{u(!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:b,children:[t.jsx("input",{type:"password",value:i,onChange:S=>c(S.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),t.jsx("button",{type:"submit",disabled:m||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):t.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&t.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):t.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function Di(){const{ides:e,initialLoaded:s}=Xt();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(da,{to:`/machines/${r.id}`,replace:!0}):t.jsx(da,{to:"/dashboard",replace:!0})}function Ay(){const e=o.useMemo(()=>({sendCommand:Ur,sendData:Aa,sendPtyInput:ly}),[]);return t.jsx(kd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Hd,{client:Ty,children:t.jsx(My,{children:t.jsx(fy,{children:t.jsx(zd,{value:e,children:t.jsx(vy,{children:t.jsxs(Sd,{children:[t.jsx(Vt,{path:"/dashboard",element:t.jsx(Yb,{})}),t.jsx(Vt,{path:"/machine",element:t.jsx(Di,{})}),t.jsx(Vt,{path:"/machines/:id",element:t.jsx(ty,{})}),t.jsx(Vt,{path:"/machines",element:t.jsx(Di,{})}),t.jsx(Vt,{path:"/about",element:t.jsx(Sy,{})}),t.jsx(Vt,{path:"/settings",element:t.jsx(Cy,{})}),t.jsx(Vt,{path:"/mesh",element:t.jsx(sy,{})}),t.jsx(Vt,{path:"*",element:t.jsx(da,{to:"/dashboard",replace:!0})})]})})})})})})})}Gf({connectionManager:Kt});Nd(document.getElementById("root")).render(t.jsx(Ay,{}));
|