@adhdev/daemon-standalone 0.9.63 → 0.9.65
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 +932 -1978
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-BvBGqot4.js +94 -0
- package/public/index.html +1 -1
- package/public/assets/index-DrpgLkHO.js +0 -94
|
@@ -0,0 +1,94 @@
|
|
|
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 nd=Object.defineProperty;var ad=(e,t,r)=>t in e?nd(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ye=(e,t,r)=>ad(e,typeof t!="symbol"?t+"":t,r);import{r as o,j as s,M as ka,a as od,b as id,c as cd,u as _s,R as kt,d as er,t as ld,e as dd,D as ud,f as ea,g as ta,h as Sa,i as md,k as fd,B as pd,l as hd,m as qt,N as sa,n as xd}from"./vendor-BRZ4K-AC.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.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 bd(e={}){const t=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>t&&r.splice(0,r.length-t),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 Ss=bd();function go(e){const t={};for(const r of e)r.transport&&(t[r.transport]=(t[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:t}}function gd(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function yd(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ai(e,t){if(!e)return t??null;if(!t)return e??null;const r=yd(e,"messages"),n=r?Array.isArray(e.messages)?e.messages:[]:t.messages,a={...t,...e,activeModal:e.activeModal??null,inputContent:e.inputContent??t.inputContent};return r?{...a,messages:n}:a}function Vs(e,t){const r=gd(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:Ai(e.activeChat,t==null?void 0:t.activeChat),controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel)}}function Ii(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const i=e.find(c=>c.id===a.id);return i?Vs(a,i):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(i=>i.id));for(const i of e)a.has(i.id)||n.push(i)}return n}function yo(e){return!!e&&typeof e=="object"&&"text"in e}function Na(e,t){const r=(t==null?void 0:t.joiner)??" ",n=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(i=>typeof i=="string"?i:yo(i)?String(i.text||""):"").join(r):yo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Ns(e){return Na(e,{normalizeWhitespace:!0})}const Mi=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}),Ri=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function vo(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),(r=e.childSessions)!=null&&r.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function Li(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,i=t.serverVersion??e.serverVersion??r.serverVersion,c=t.versionMismatch===!0||e.versionMismatch===!0,l=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,u=t.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),u&&(n.versionUpdateReason=u),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((t.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function vd(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function xn(e){if(!e||typeof e!="object")return"";const t=e,r=vd(Ns(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),r].join(":")}function wd(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=xn(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:xn(e[0]),last:xn(e[e.length-1])}}function ra(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function na(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(ra(e)&&ra(t)){const c=e.messages;Array.isArray(c)&&c===t.messages&&r.add(c)}if(Array.isArray(e)&&Array.isArray(t)){const c=Math.min(e.length,t.length);for(let l=0;l<c;l+=1)na(e[l],t[l],r);return}const n=e,a=t,i=new Set([...Object.keys(n),...Object.keys(a)]);for(const c of i)c!=="messages"&&na(n[c],a[c],r)}function qs(e,t){return Array.isArray(e)?e.map(r=>qs(r,t)):!e||typeof e!="object"?e:ra(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?wd(a,t):qs(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,qs(n,t)]))}function jd(e,t){try{const r=new WeakSet;return na(e,t,r),JSON.stringify(qs(e,r))===JSON.stringify(qs(t,r))}catch{return!1}}function aa(e,t,r){return jd(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function _i(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function kd(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function wo(e,t,r,n){var l;const a=(l=t.chats)!=null&&l.length?t.chats:e.chats,i=Ii(e.childSessions,t.childSessions,{preserveMissing:n}),c=Ai(t.activeChat,e.activeChat);return Li(e,t,{...e,...t,chats:a,childSessions:i,activeChat:c,_lastUpdate:r})}function Sd(e,t,r){var a,i;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=Ii(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((i=e.chats)!=null&&i.length)&&(n.chats=t.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"])kd(n,t,c);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Nd(e,t,r,n){const a=Sd(e,t,n),i=Object.keys(a).length>0?Li(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return aa(e,i,r)}function Cd(e){const t=new Set(e.map(i=>i.id)),r=new Set,n=new Set,a=new Set;for(const i of e){const c=_i(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:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function Td(e,t,r,n,a,i){return!a.has(t)||!i.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function Ad(e,t,r,n){return!!(r.has(t)&&e.transport&&!n.has(t))}function Id(e,t,r){var d,h;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(f=>({...f,_lastUpdate:n}));const i=new Map;for(const f of t)i.set(f.id,f);const{incomingIds:c,incomingDaemonIds:l,daemonIdsWithSessionEntries:u,daemonIdsWithAuthoritativeSessionList:m}=Cd(e);for(const f of e){const w=i.get(f.id);if(!w){i.set(f.id,{...f,_lastUpdate:n});continue}const k=vo(f),p=vo(w),S=_i(f),x=!a.has(S);if(k>p){const I=wo(w,f,n,x);i.set(f.id,aa(w,I,n));continue}if(k<p){i.set(f.id,Nd(w,f,n,x));continue}const b=f.timestamp||n,y=w._lastUpdate||w.timestamp||0;if(b>=y){const I=wo(w,f,n,x);i.set(f.id,aa(w,I,n));continue}(d=f.chats)!=null&&d.length&&!((h=w.chats)!=null&&h.length)&&i.set(f.id,{...w,chats:f.chats})}for(const[f,w]of i){const k=w.daemonId||f.split(":")[0];if(!l.has(k))continue;if(a.has(k)&&m.has(k)&&!c.has(f)){i.delete(f);continue}const p=n-(w._lastUpdate||w.timestamp||0);Td(w,k,p,c,a,u)&&i.delete(f)}for(const[f,w]of i){const k=w.daemonId||f.split(":")[0];if(Ad(w,k,l,u))continue;n-(w._lastUpdate||w.timestamp||0)>3e5&&w.status!=="online"&&i.delete(f)}return Array.from(i.values())}function Md(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Rd({children:e,connectionOverrides:t}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,m]=o.useState(void 0),d=o.useRef(r);o.useEffect(()=>{d.current=r},[r]);const h=o.useCallback((x,b)=>{n(y=>{let I=!1;const g=y.map(T=>T.id!==x||T.chats===b?T:(I=!0,{...T,chats:b}));return I?g:y})},[]),f=o.useCallback((x,b)=>{n(y=>{const I=y.length===0?x:Id(x,y,b),g=!Md(y,I);return g&&Ss.record({kind:"dashboard.entries_applied",payload:{incoming:go(x),next:go(I)}}),g?I:y})},[]),w=o.useCallback(()=>i(!0),[]),k=o.useMemo(()=>({injectEntries:f,markLoaded:w,getIdes:()=>d.current}),[f,w]),p=t,S=o.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,connectionRetryStatuses:p==null?void 0:p.connectionRetryStatuses,userName:u,setUserName:m}),[r,h,a,c,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,p==null?void 0:p.connectionRetryStatuses,u]);return s.jsx(Ri.Provider,{value:k,children:s.jsx(Mi.Provider,{value:S,children:e})})}function cs(){return o.useContext(Mi)}function tr(){return o.useContext(Ri)}function Pi(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${t}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),m=a(l),d=l.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!l.startsWith("http")&&!t?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function c(l,u={}){const m={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(m.Authorization=`Bearer ${d}`);const h=a(l),f=new AbortController,w=setTimeout(()=>f.abort(),15e3);try{const k=await fetch(h,{...u,headers:m,signal:f.signal});if(k.status===401)throw n==null||n(),new Error("Unauthorized");if(!k.ok){const p=await k.json().catch(()=>({error:k.statusText}));throw new Error(p.error||`API Error: ${k.status}`)}return k.json()}finally{clearTimeout(w)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,m={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),execTerminal:(l,u,m)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:m})}),sendAgentMessage:(l,u,m)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:m})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,m)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,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,u,m={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:m})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Ld=Pi({baseUrl:"http://localhost:3847"}),_d=o.createContext(Ld);function Pd({client:e,children:t}){return s.jsx(_d.Provider,{value:e,children:t})}const Dd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Di=o.createContext(Dd);function Ed({value:e,children:t}){return s.jsx(Di.Provider,{value:e,children:t})}function ft(){return o.useContext(Di)}function $d(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function Bd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Kd(e){return e?$d([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Bd(e.content)]):""}const Oe={size:18};function Ei({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Ca({size:e=Oe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function ls({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function $i({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Od({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Wd({size:e=Oe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.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 Bi({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.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"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Hd({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function tn({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.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 Ki({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Fd({size:e=Oe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Ft({size:e=Oe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.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=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Ta({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Ud({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Cs({size:e=Oe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.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 or({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function sr({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function rr({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Oi({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Aa({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.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"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Wi({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function zd({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Ia({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Vd({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Ma({size:e=Oe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Hi({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function St({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Gd({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.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"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function qd({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Yd({size:e=Oe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.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 Xd({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.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 sn({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Jd({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Qd({size:e=Oe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Zd({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function eu({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function tu({size:e=Oe.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function su({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.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 ru({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.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"}),s.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 nu({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function au({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function ou({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function iu({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.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 cu({size:e=Oe.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Fi=[od,{singleTilde:!1}],Ui=[Fi,id,cd],lu=[Fi],Ra=200,du=80,jo=650,$s=new Map;function Fr(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function uu(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(t||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${Kd(n)}`}function mu(e,t,r,n){return e||!t?!1:Fr(r,n)}function fu({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=du,bottomThresholdPx:a=Ra}){const i=Math.max(0,Number(e)||0),c=Math.max(0,Number(t)||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 pu(e){return fu({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Gs(e,t=Ra){return!!e&&e.fromBottom>=t}function hu(e,t){return Fr(e,t)?!Gs(e):!0}function xu({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function bu({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function bn(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function zi(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function gu(e,t,r){return Number(e.receivedAt||r[Ur(e,t)]||0)||0}function Vi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function yu(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function xr(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function gn(e){if(typeof e.uri=="string"&&e.uri)return e.uri;if(typeof e.data=="string"&&e.data&&typeof e.mimeType=="string"&&e.mimeType)return`data:${e.mimeType};base64,${e.data}`}function ko(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Vi(e)?s.jsx(ka,{remarkPlugins:Ui,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function br({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return s.jsx("div",{children:ko(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=gn(r);return a?s.jsx("img",{src:a,alt:xr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=gn(r);return a?s.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=gn(r);return a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:xr(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||xr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=xr(r.resource.uri,"resource");if(r.resource.text)return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),ko(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return s.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function Ur(e,t){const r=e,n=Na(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:${t}`].filter(Boolean).join("|")}const vu=o.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(ka,{remarkPlugins:lu,children:t.text}),s.jsx("span",{className:"action-time",children:zi(t.timestamp)})]})},(e,t)=>e.log===t.log),wu=o.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var T,A,j;const u=(t.role||"").toLowerCase(),m=u==="user"||u==="human",d=t.kind||(u==="tool"?"tool":"standard"),h=yu(t.content)?t.content:null,f=!!(h!=null&&h.some(v=>v.type!=="text")),w=Na(t.content,{joiner:`
|
|
4
|
+
`});if(d==="thought"){const v=typeof((T=t.meta)==null?void 0:T.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Yd,{size:13}),s.jsx("span",{children:v})]}),s.jsx("div",{className:"chat-msg-body",children:w})]})}if(d==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),f&&h?s.jsx("div",{className:"tool-text w-full",children:s.jsx(br,{parts:h,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(d==="terminal"){const v=(A=t.meta)!=null&&A.isRunning?"⏳":"✅",K=typeof((j=t.meta)==null?void 0:j.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal",children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:v}),s.jsx("span",{children:K})]}),f&&h?s.jsx("div",{className:"chat-msg-body",children:s.jsx(br,{parts:h,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:w})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:f&&h?s.jsx(br,{parts:h,renderAsPreformatted:!1}):w.slice(0,100)});const k=t.meta,S=(typeof(k==null?void 0:k.renderMode)=="string"?k.renderMode.trim():"")==="preformatted",x=w,b=!1,y=x,I=S,g=!I&&Vi(y);return s.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${m?"self-end":"self-start"}`,children:(x||f||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${x||f?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:m?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:zi(r)})]}),(x||f)&&s.jsx("div",{className:"chat-markdown",children:f&&h?s.jsx(br,{parts:h,renderAsPreformatted:I}):I?s.jsx("pre",{className:"chat-preformatted",children:y}):g?s.jsx(ka,{remarkPlugins:Ui,children:y}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:y})}),b]})})},(e,t)=>e.message===t.message&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),ju=o.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},lastMessageHash:m,emptyState:d,onLoadMore:h,isLoadingMore:f,hasMoreHistory:w,hiddenLiveCount:k=0,loadError:p,scrollToBottomRequestNonce:S,isVisible:x=!0},b){const y=o.useRef(null),I=o.useRef(null),g=o.useRef(null),T=o.useRef(0),A=o.useRef(""),j=o.useRef(""),v=o.useRef(!1),K=o.useRef(null),_=o.useRef(!1),C=o.useRef(null),H=o.useRef(!1),[F,P]=o.useState(new Set),[N,M]=o.useState({showTop:!1,showBottom:!1}),O=o.useRef(!1),$=o.useRef(!1),E=o.useRef(x),U=o.useRef(x),X=o.useRef(null);U.current=x;const he=()=>{const G=y.current;return G?G.scrollHeight-G.scrollTop-G.clientHeight<Ra:!0},ce=o.useCallback(()=>{const G=y.current,Y=G?pu(G):{showTop:!1,showBottom:!1};M(le=>le.showTop===Y.showTop&&le.showBottom===Y.showBottom?le:Y)},[]),te=o.useCallback((G="auto")=>{var le;const Y=y.current;Y&&(Y.scrollTo({top:Y.scrollHeight,behavior:G}),(le=Y.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>ce()))},[ce]),ye=o.useCallback((G="auto")=>{var le;const Y=y.current;Y&&(Y.scrollTo({top:0,behavior:G}),(le=Y.ownerDocument.defaultView)==null||le.requestAnimationFrame(()=>ce()))},[ce]),fe=o.useCallback(()=>{var Z;const G=y.current,Y=(Z=window.getSelection)==null?void 0:Z.call(window);if(!G||!Y||Y.rangeCount===0||Y.isCollapsed){H.current=!1;return}const le=Y.anchorNode,ke=Y.focusNode;H.current=!!(le&&ke&&G.contains(le)&&G.contains(ke))},[]),be=uu(t,m),J=o.useCallback(()=>{const G=y.current;if(!G||!l||!U.current)return;const Y={top:G.scrollTop,fromBottom:Math.max(0,G.scrollHeight-G.scrollTop-G.clientHeight),messageFingerprint:be};X.current={contextKey:l,snapshot:Y},$s.set(l,Y)},[l,be]),ae=o.useCallback((G="auto")=>{K.current!=null&&cancelAnimationFrame(K.current),K.current=requestAnimationFrame(()=>{K.current=null,te(G)})},[te]),ge=o.useCallback(()=>{O.current=!1,_.current=!0,$.current=!0,C.current!=null&&window.clearTimeout(C.current),C.current=window.setTimeout(()=>{_.current=!1,C.current=null},jo)},[]);o.useEffect(()=>{const G=!v.current,Y=j.current!==l;if(j.current=l,G||Y){v.current=!0;const ke=l?$s.get(l):null,Z=!!ke&&Fr(ke,be);O.current=Z?Gs(ke):!1,_.current=hu(ke,be),H.current||(Z?requestAnimationFrame(()=>{const Ce=y.current;Ce&&(bn(Ce,ke),O.current=Gs(ke),ce(),$.current=!0)}):ae("auto")),T.current=t.length,A.current=be;return}t.length>T.current;const le=be!==A.current;xu({hasSelection:H.current,userScrolledUp:O.current,hasChatContentChanged:le})&&ae("auto"),T.current=t.length,A.current=be},[be,l,t.length,ae,ce]),o.useEffect(()=>{S&&(ge(),H.current||ae("auto"))},[ge,ae,S]),o.useEffect(()=>{const G=E.current;G&&!x&&J(),U.current=x,E.current=x;const Y=l?$s.get(l):null;if(mu(G,x,Y,be)){if(!Y)return;O.current=Gs(Y),_.current=!1,H.current||requestAnimationFrame(()=>{const le=y.current;le&&(bn(le,Y),ce())});return}},[x,l,be,ge,J,ae,ce]),o.useEffect(()=>()=>{const G=X.current;G&&$s.set(G.contextKey,G.snapshot),K.current!=null&&cancelAnimationFrame(K.current),C.current!=null&&window.clearTimeout(C.current)},[]),o.useEffect(()=>{const G=I.current,Y=y.current;if(!G||!Y)return;const le=()=>{C.current!=null&&window.clearTimeout(C.current),C.current=window.setTimeout(()=>{_.current=!1,C.current=null},jo)},ke=new ResizeObserver(()=>{ce();const Z=_.current;bu({hasSelection:H.current,userScrolledUp:O.current,contextAutoScrollActive:Z})&&(ae("auto"),Z&&le())});return ke.observe(G),Y!==G&&ke.observe(Y),()=>{ke.disconnect(),C.current!=null&&(window.clearTimeout(C.current),C.current=null)}},[ae,l,ce]),o.useImperativeHandle(b,()=>({scrollToBottom:(G="smooth")=>{te(G)}}),[te]),o.useEffect(()=>{const G=y.current;if(!G)return;let Y;const le=()=>{J(),clearTimeout(Y),Y=setTimeout(()=>{O.current=!he(),ce()},50)};return G.addEventListener("scroll",le,{passive:!0}),()=>{G.removeEventListener("scroll",le),clearTimeout(Y)}},[J,ce]),o.useEffect(()=>(document.addEventListener("selectionchange",fe),()=>document.removeEventListener("selectionchange",fe)),[fe]);const ee=o.useRef(0),de=o.useRef(!1);o.useEffect(()=>{const G=y.current;if(!G||!de.current||ee.current===0)return;const Y=G.scrollHeight-ee.current;Y>0&&(G.scrollTop=Y),ce(),J(),ee.current=0,de.current=!1},[t.length,J,ce]),o.useEffect(()=>{if($.current||!l)return;const G=$s.get(l),Y=y.current;if(!(!G||!Y)){if(!Fr(G,be)){te("auto"),$.current=!0;return}bn(Y,G),O.current=Gs(G),ce(),$.current=!0}},[l,be,t.length,te,ce]);const we=()=>{const G=y.current;G&&(ee.current=G.scrollHeight),de.current=!0,h==null||h()},ue=()=>{O.current=!0,ye("smooth"),J()},xe=()=>{ge(),te("smooth"),J()},se=o.useMemo(()=>{const G=t.map((Z,Ce)=>({type:"message",data:Z,index:Ce,ts:gu(Z,Ce,u)}));if(!r||r.length===0)return G;const Y=[...r].sort((Z,Ce)=>Z.timestamp-Ce.timestamp).map((Z,Ce)=>({type:"action",data:Z,index:Ce,ts:Z.timestamp})),le=[];let ke=0;for(const Z of G){for(;ke<Y.length&&Z.ts>0&&Y[ke].ts<Z.ts;)le.push(Y[ke++]);le.push(Z)}for(;ke<Y.length;)le.push(Y[ke++]);return le},[t,r,u]),ie=k>0||!!w,re=k>0?`↑ Show ${Math.min(k,80)} earlier messages${k>80?` (${k} hidden)`:""}`:p?`↻ ${p}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:y,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:I,className:"chat-container-content",children:[f&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ie&&!f&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:we,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${p&&k===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:re})}),se.length===0&&!ie&&(d||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),se.map(G=>{if(G.type==="action"){const We=G.data;return s.jsx(vu,{log:We},`action-${G.index}`)}const Y=G.data,le=G.index,ke=Ur(Y,le),Z=Y.receivedAt||u[ke],Ce=`${l}-${ke}`,Pe=F.has(Ce);return s.jsx(wu,{message:Y,receivedAt:Z,agentName:n,userName:a,isCliMode:i,isTextExpanded:Pe,onToggleTextExpanded:()=>P(We=>{const He=new Set(We);return Pe?He.delete(Ce):He.add(Ce),He})},`msg-${ke}`)}),c&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:g})]})}),(N.showTop||N.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[N.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ue,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),N.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:xe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),ku=o.memo(ju,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),Su="modulepreload",Nu=function(e){return"/"+e},So={},Cu=function(t,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(u=>{if(u=Nu(u),u in So)return;So[u]=!0;const m=u.endsWith(".css"),d=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":Su,m||(h.as="script"),h.crossOrigin="",h.href=u,l&&h.setAttribute("nonce",l),document.head.appendChild(h),m)return new Promise((f,w)=>{h.addEventListener("load",f),h.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return t().catch(i)})};let No=!1;const Gi=o.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:i="measured"},c)=>{const l=o.useRef(null),[u,m]=o.useState(null),d=o.useRef([]),h=o.useRef(!1),f=o.useRef(!1),w=o.useRef(!1),k=o.useRef(!1),p=()=>{const S=l.current;if(S){h.current&&(S.clear(),h.current=!1);for(const x of d.current)S.write(x.data,x.onProcessed);d.current=[],f.current&&(S.fit(),f.current=!1),w.current&&(S.bumpResize(),w.current=!1),k.current&&(S.scrollToTop(),k.current=!1)}};return o.useImperativeHandle(c,()=>({write:(S,x)=>{l.current?l.current.write(S,x):d.current.push({data:S,onProcessed:x})},clear:()=>{l.current?l.current.clear():(d.current=[],h.current=!0)},reset:()=>{l.current&&typeof l.current.reset=="function"?l.current.reset():(d.current=[],h.current=!0)},resize:(S,x)=>{l.current&&typeof l.current.resize=="function"&&l.current.resize(S,x)},fit:()=>{l.current?l.current.fit():f.current=!0},bumpResize:()=>{l.current?l.current.bumpResize():w.current=!0},scrollToTop:()=>{l.current?l.current.scrollToTop():k.current=!0},getSelection:()=>{var S,x;return((x=(S=l.current)==null?void 0:S.getSelection)==null?void 0:x.call(S))||""},getVisibleText:()=>{var S,x;return((x=(S=l.current)==null?void 0:S.getVisibleText)==null?void 0:x.call(S))||""}}),[]),o.useEffect(()=>{u&&p()},[u]),o.useEffect(()=>{let S=!1;return Cu(()=>import("./terminal-DbJP_JGY.js"),__vite__mapDeps([0,1,2])).then(x=>{No||(No=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),S||m(()=>x.GhosttyTerminalView)}).catch(x=>{console.error("[CliTerminal] failed to load terminal renderer",x)}),()=>{S=!0}},[]),u?s.jsx(u,{ref:l,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:i,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Gi.displayName="CliTerminal";function gr({label:e,value:t,sub:r,icon:n}){return s.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:n}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),r&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function Co({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:i=!1}){const c=t>0?Math.min(Math.round(e/t*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Tu({cursorPos:e,viewportRef:t,imgRef:r}){var b;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(b=t.current)==null?void 0:b.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,u=c/l,m=a.width/a.height;let d,h,f,w;u>m?(d=a.width,h=a.width/u,f=0,w=(a.height-h)/2):(h=a.height,d=a.height*u,f=(a.width-d)/2,w=0);const k=a.left-i.left+f+d*e.nx,p=a.top-i.top+w+h*e.ny,S=Math.max(8,Math.min(i.width-8,k)),x=Math.max(8,Math.min(i.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:S-8,top:x-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.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 Au({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:m,zoom:d,isMobile:h,mobileFillZoom:f,onZoomOut:w,onZoomReset:k,onZoomIn:p,transportType:S,screenshotUsage:x,lastActionStatus:b}){return s.jsxs(s.Fragment,{children:[s.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:[s.jsxs("div",{onClick:t,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:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.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:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.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:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:y=>y.stopPropagation(),onChange:y=>l(y.target.value),onKeyDown:y=>{u(y)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.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:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.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:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),S==="direct"&&s.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"}),S==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),x&&x.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:x.budgetExhausted?"#ef4444":"#c4b5fd",background:x.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:x.budgetExhausted?"TURN blocked":`TURN ${x.dailyUsedMinutes}/${x.dailyBudgetMinutes}m`}),b&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),a&&s.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:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",d<=(h?f:1)+.01?h?"FILL":"FIT":`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:y=>{y.stopPropagation(),w()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:y=>{y.stopPropagation(),k()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),s.jsx("button",{onClick:y=>{y.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Iu({waitingLabel:e,waitingHint:t,transportType:r}){return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.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:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),r==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function Mu(){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 To(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 ir(e,t){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!Mu())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([c,l])=>[c,To(l)]))}),r.current=t;return}const i=Object.keys({...a,...t}).filter(c=>!Object.is(a[c],t[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,To(t[c])]))}),r.current=t})}function Ru({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:m,setPanY:d,setZoom:h,lastWheelTimeRef:f,onAction:w,setLastActionStatus:k,spawnRippleFromNormalized:p,clampPan:S,isMobile:x,mobileFillZoom:b}){const[y,I]=o.useState(null),g=o.useRef(null),T=o.useRef(null),A=o.useRef(null),j=o.useRef(!1),v=o.useRef(null),K=o.useRef(0),_=o.useRef(null),C=o.useRef(1),H=o.useRef({x:0,y:0}),F=o.useRef(!1),P=o.useRef(n),N=o.useRef(w),M=30,O=550,$=18,E=60,U=400,X=12,he=()=>{if(g.current)return;const ye={nx:.5,ny:.5};g.current=ye,I(ye)};return o.useEffect(()=>{P.current=n,n==="mouse"&&he()},[n]),o.useEffect(()=>{N.current=w},[w]),o.useEffect(()=>{const ye=e.current;if(!ye)return;const fe=de=>{if(!r.current)return null;const we=r.current.getBoundingClientRect();return!we.width||!we.height?null:{nx:Math.max(0,Math.min(1,(de.clientX-we.left)/we.width)),ny:Math.max(0,Math.min(1,(de.clientY-we.top)/we.height))}},be=(de,we)=>{if(!r.current)return{dnx:0,dny:0};const ue=r.current,xe=ue.getBoundingClientRect(),se=ue.naturalWidth||xe.width,ie=ue.naturalHeight||xe.height,re=se/ie,G=xe.width/xe.height;let Y,le;return re>G?(Y=xe.width,le=xe.width/re):(le=xe.height,Y=xe.height*re),{dnx:de/Y,dny:we/le}},J=(de,we,ue)=>{if(ue<=1.05)return;const xe=-(de-.5)*100,se=-(we-.5)*100,ie=S(xe,se,ue);(Math.abs(ie.x-l.current)>.1||Math.abs(ie.y-u.current)>.1)&&(m(ie.x),d(ie.y),l.current=ie.x,u.current=ie.y)},ae=de=>{const we=t.current;if(we&&de.target instanceof Node&&we.contains(de.target))de.preventDefault();else return;if(de.touches.length===1){const ue=de.touches[0];T.current={x:ue.clientX,y:ue.clientY,time:Date.now()},A.current={x:ue.clientX,y:ue.clientY},F.current||(j.current=!1),v.current=setTimeout(()=>{if(!j.current&&!F.current)if(j.current=!0,P.current==="mouse"){const xe=g.current||{nx:.5,ny:.5};k("Right Click"),p(xe.nx,xe.ny,"right"),N.current("input_click",{...xe,button:"right"}).catch(()=>{})}else{const xe=fe(ue);xe&&(k("Right Click"),p(xe.nx,xe.ny,"right"),N.current("input_click",{...xe,button:"right"}).catch(()=>{}))}},500);return}if(de.touches.length===2){v.current&&clearTimeout(v.current),j.current=!0,F.current=!0;const ue=de.touches[1].clientX-de.touches[0].clientX,xe=de.touches[1].clientY-de.touches[0].clientY;_.current=Math.sqrt(ue*ue+xe*xe),C.current=c.current,H.current={x:(de.touches[0].clientX+de.touches[1].clientX)/2,y:(de.touches[0].clientY+de.touches[1].clientY)/2}}},ge=de=>{const we=t.current;if(we&&de.target instanceof Node&&we.contains(de.target)&&de.preventDefault(),de.touches.length===1&&A.current){const ue=de.touches[0],xe=ue.clientX-A.current.x,se=ue.clientY-A.current.y;if(!j.current&&T.current){const ie=ue.clientX-T.current.x,re=ue.clientY-T.current.y;Math.sqrt(ie*ie+re*re)>8&&(j.current=!0,v.current&&clearTimeout(v.current))}if(j.current)if(P.current==="mouse"){const ie=be(xe,se),re=g.current||{nx:.5,ny:.5},G=Math.max(0,Math.min(1,re.nx+ie.dnx)),Y=Math.max(0,Math.min(1,re.ny+ie.dny));g.current={nx:G,ny:Y},I({nx:G,ny:Y}),k(`Cursor: ${Math.round(G*100)}%, ${Math.round(Y*100)}%`),J(G,Y,c.current);const le=Date.now();le-f.current>=30&&(f.current=le,N.current("input_mouseMoved",{nx:G,ny:Y}).catch(()=>{}))}else if(c.current>1){const ie=t.current;if(ie){const re=ie.clientWidth,G=ie.clientHeight,Y=l.current+xe/re*100,le=u.current+se/G*100,ke=S(Y,le,c.current);m(ke.x),d(ke.y),l.current=ke.x,u.current=ke.y}}else{const ie=fe(ue);if(ie){const re=Date.now();re-f.current>=40&&(f.current=re,k("Scroll"),N.current("input_wheel",{nx:ie.nx,ny:ie.ny,deltaX:Math.round(-xe*2.5),deltaY:Math.round(-se*2.5)}).catch(()=>{}))}}A.current={x:ue.clientX,y:ue.clientY};return}if(de.touches.length===2&&_.current!==null){const ue=de.touches[1].clientX-de.touches[0].clientX,xe=de.touches[1].clientY-de.touches[0].clientY,ie=Math.sqrt(ue*ue+xe*xe)/_.current,re=(de.touches[0].clientX+de.touches[1].clientX)/2,G=(de.touches[0].clientY+de.touches[1].clientY)/2,Y=re-H.current.x,le=G-H.current.y,ke=Math.abs(ie-1)>.03;if(P.current==="mouse"){if(ke){const Z=Math.max(i,Math.min(5,C.current*ie));h(Z),c.current=Z}else if(Math.abs(Y)>2||Math.abs(le)>2){const Z=g.current||{nx:.5,ny:.5},Ce=Date.now();Ce-f.current>=30&&(f.current=Ce,k("Scroll"),N.current("input_wheel",{nx:Z.nx,ny:Z.ny,deltaX:Math.round(-Y*3),deltaY:Math.round(-le*3)}).catch(()=>{}))}}else{const Z=Math.max(i,Math.min(5,C.current*ie));h(Z),c.current=Z;const Ce=t.current;if(Ce&&Z>1){const Pe=Ce.clientWidth,We=Ce.clientHeight,He=l.current+Y/Pe*100,D=u.current+le/We*100,Se=S(He,D,Z);m(Se.x),d(Se.y),l.current=Se.x,u.current=Se.y}}H.current={x:re,y:G}}},ee=de=>{var we;if(v.current&&clearTimeout(v.current),_.current=null,de.touches.length===1&&F.current){const ue=de.touches[0];T.current={x:ue.clientX,y:ue.clientY,time:Date.now()},A.current={x:ue.clientX,y:ue.clientY},j.current=!0;return}if(de.touches.length===0){if(F.current){F.current=!1,j.current=!1;return}if(de.changedTouches.length===1){const ue=de.changedTouches[0],xe=Date.now(),se=xe-(((we=T.current)==null?void 0:we.time)||0),ie=T.current?ue.clientX-T.current.x:0,re=T.current?ue.clientY-T.current.y:0,G=Math.sqrt(ie*ie+re*re);if(P.current==="mouse"){if(se<M||se>O||G>$){j.current=!1;return}const Y=g.current||fe(ue);Y&&(k(`Click: ${Math.round(Y.nx*100)}%, ${Math.round(Y.ny*100)}%`),p(Y.nx,Y.ny,"left"),N.current("input_click",{...Y}).catch(()=>{}))}else{if(j.current){j.current=!1;return}if(se<E||se>U||G>X){j.current=!1;return}const Y=fe(ue);if(!Y)return;xe-K.current<300?(k("Double tap"),p(Y.nx,Y.ny,"double"),N.current("input_click",{...Y,clickCount:2}).catch(()=>{}),K.current=0):(k(`Tap: ${Math.round(Y.nx*100)}%, ${Math.round(Y.ny*100)}%`),p(Y.nx,Y.ny,"left"),N.current("input_click",{...Y}).catch(()=>{}),K.current=xe)}}j.current=!1}};return ye.addEventListener("touchstart",ae,{passive:!1}),ye.addEventListener("touchmove",ge,{passive:!1}),ye.addEventListener("touchend",ee,{passive:!1}),()=>{ye.removeEventListener("touchstart",ae),ye.removeEventListener("touchmove",ge),ye.removeEventListener("touchend",ee),v.current&&clearTimeout(v.current)}},[e,t,r,i,c,l,u,m,d,h,f,k,p,S]),{cursorPos:y,cursorPosRef:g,handleToggleInputMode:()=>{a(ye=>{const fe=ye==="touch"?"mouse":"touch";return fe==="mouse"&&he(),fe})},handleZoomReset:()=>{const ye=x?b:1;h(ye),c.current=ye,m(0),d(0),l.current=0,u.current=0}}}function qi({onAction:e,addLog:t,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[m,d]=o.useState(null),[h,f]=o.useState(""),[,w]=o.useState(!1),[k,p]=o.useState([]),S=o.useRef(0),[x,b]=o.useState(!1),[y,I]=o.useState(!1),g=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[T,A]=o.useState(g?"mouse":"touch"),[j,v]=o.useState(1),K=o.useRef(!1),[_,C]=o.useState(1),[H,F]=o.useState(0),[P,N]=o.useState(0);ir("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:T,zoom:_,panX:H,panY:P,isMenuOpen:x,isImeOpen:y});const M=o.useRef(0),O=o.useRef(_),$=o.useRef(H),E=o.useRef(P);o.useEffect(()=>{O.current=_},[_]),o.useEffect(()=>{$.current=H},[H]),o.useEffect(()=>{E.current=P},[P]),o.useEffect(()=>{var se;(se=c.current)==null||se.focus()},[]);const U=r==="connected",X=n,he=U?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ce=U?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!g||K.current||!X)return;const se=u.current,ie=l.current;if(!se||!ie)return;const re=()=>{const G=ie.clientWidth,Y=ie.clientHeight,le=se.naturalWidth,ke=se.naturalHeight;if(!le||!ke||!G||!Y)return;const Z=Math.min(G/le,Y/ke),Pe=Math.max(G/le,Y/ke)/Z;Pe>1.01&&(v(Pe),C(Pe),O.current=Pe),K.current=!0};se.complete&&se.naturalWidth?re():se.addEventListener("load",re,{once:!0})},[X,g]);const te=.5;o.useEffect(()=>{_<=te&&(F(0),N(0))},[_,te]);const ye=(se,ie,re)=>{if(re<=te)return{x:0,y:0};const G=(re-1)/(2*re)*100,Y=(re-1)/(2*re)*100;return{x:Math.max(-G,Math.min(G,se)),y:Math.max(-Y,Math.min(Y,ie))}},fe=(se,ie)=>{if(!u.current)return null;const re=u.current.getBoundingClientRect();return!re.width||!re.height?null:{nx:Math.max(0,Math.min(1,(se-re.left)/re.width)),ny:Math.max(0,Math.min(1,(ie-re.top)/re.height))}},be=(se,ie,re)=>{const G=l.current;if(!G)return;const Y=G.getBoundingClientRect(),le=++S.current;p(ke=>[...ke,{id:le,x:se-Y.left,y:ie-Y.top,type:re}]),setTimeout(()=>p(ke=>ke.filter(Z=>Z.id!==le)),600)},J=(se,ie,re)=>{const G=u.current,Y=l.current;if(!G||!Y)return;const le=G.getBoundingClientRect(),ke=Y.getBoundingClientRect(),Z=G.naturalWidth||le.width,Ce=G.naturalHeight||le.height,Pe=Z/Ce,We=le.width/le.height;let He,D,Se,Ie;Pe>We?(He=le.width,D=le.width/Pe,Se=0,Ie=(le.height-D)/2):(D=le.height,He=le.height*Pe,Se=(le.width-He)/2,Ie=0);const Re=le.left-ke.left+Se+He*se,Ee=le.top-ke.top+Ie+D*ie,Fe=++S.current;p(Ue=>[...Ue,{id:Fe,x:Re,y:Ee,type:re}]),setTimeout(()=>p(Ue=>Ue.filter(Je=>Je.id!==Fe)),600)},ae=async se=>{var re;const ie=fe(se.clientX,se.clientY);if(ie){d(`Click: ${Math.round(ie.nx*100)}%, ${Math.round(ie.ny*100)}%`),be(se.clientX,se.clientY,"left"),(re=c.current)==null||re.focus();try{const G=await e("input_click",{nx:ie.nx,ny:ie.ny});G!=null&&G.success||t(`❌ Click failed: ${G==null?void 0:G.error}`)}catch(G){t(`❌ Click error: ${G.message||G}`)}}},ge=async(se,ie,re,G=0)=>{try{await e("input_key",{type:re?"char":"keyDown",key:se,code:ie,text:re?se:void 0,unmodifiedText:re?se:void 0,modifiers:G})}catch(Y){t(`❌ Key error: ${Y.message||Y}`)}},ee=async se=>{if(se.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(se.key)&&se.preventDefault();let re=0;se.altKey&&(re|=1),se.ctrlKey&&(re|=2),se.metaKey&&(re|=4),se.shiftKey&&(re|=8),d(`Key: ${se.key}`),await ge(se.key,se.code,se.key.length===1,re)},de=async se=>{if(se.key==="Enter"){if(se.nativeEvent.isComposing)return;if(h){const ie=h;f(""),d(`IME Sent: ${ie}`);try{const re=await e("input_type",{text:ie});re!=null&&re.success||t(`❌ IME error: ${re==null?void 0:re.error}`)}catch(re){t(`❌ IME error: ${re.message}`)}}else d("Key: Enter"),await ge("Enter","Enter",!1)}};o.useEffect(()=>{const se=c.current;if(!se)return;const ie=re=>{var G;if((G=u.current)!=null&&G.contains(re.target)){re.preventDefault();const Y=Date.now();if(Y-M.current<40)return;M.current=Y;const le=fe(re.clientX,re.clientY);if(!le)return;d(`Scroll: ${Math.round(re.deltaY)}`),e("input_wheel",{nx:le.nx,ny:le.ny,deltaX:Math.round(re.deltaX),deltaY:Math.round(re.deltaY)}).catch(()=>{})}};return se.addEventListener("wheel",ie,{passive:!1}),()=>se.removeEventListener("wheel",ie)},[e]);const{cursorPos:we,handleToggleInputMode:ue,handleZoomReset:xe}=Ru({containerRef:c,viewportRef:l,imgRef:u,inputMode:T,setInputMode:A,minZoom:te,zoomRef:O,panXRef:$,panYRef:E,setPanX:F,setPanY:N,setZoom:C,lastWheelTimeRef:M,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:J,clampPan:ye,isMobile:g,mobileFillZoom:j});return s.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ee,onContextMenu:se=>se.preventDefault(),onFocus:()=>w(!0),onBlur:()=>w(!1),tabIndex:0,children:[s.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[X?s.jsx("img",{ref:u,src:X,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${_}) translate(${H}%, ${P}%)`,transformOrigin:"center center",cursor:T==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ae,onContextMenu:se=>se.preventDefault(),onDragStart:se=>se.preventDefault()}):s.jsx(Iu,{waitingLabel:he,waitingHint:ce,transportType:i}),T==="mouse"&&X&&s.jsx(Tu,{cursorPos:we,viewportRef:l,imgRef:u}),k.map(se=>{const re={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[se.type];return s.jsxs("div",{style:{position:"absolute",left:se.x,top:se.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${re}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${re}, 0.9)`,boxShadow:`0 0 12px rgba(${re}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},se.id)})]}),s.jsx(Au,{inputMode:T,onToggleInputMode:ue,isImeOpen:y,setIsImeOpen:I,isMenuOpen:x,setIsMenuOpen:b,imeText:h,setImeText:f,handleImeSubmit:de,isConnActive:U,zoom:_,isMobile:g,mobileFillZoom:j,onZoomOut:()=>C(se=>Math.max(.5,se-.25)),onZoomReset:xe,onZoomIn:()=>C(se=>Math.min(5,se+.25)),transportType:i,screenshotUsage:a,lastActionStatus:m}),s.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 rn(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const m=Math.floor(u/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const Yi=e=>rn(e);function Lu(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 Ps(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function _u(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Lu(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 t}function zr(e,t){if(e.sessionId){const r=t.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 nn(e,t,r){const n=zr(e,t),a=Ps(e),i=a.isReconnecting,c=a.isConnecting,l=a.isGenerating,u=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=n.inboxBucket==="working"||l,f=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:f,requiresAction:m,isWorking:d,isReconnecting:i,isConnecting:c,isGenerating:l,isWaiting:u,inboxBucket:m?"needs_attention":d?"working":f?"task_complete":"idle"}}function Pu(e,t,r){return nn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Xi({activeConv:e,onModalButton:t}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ps(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),t(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.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&&s.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)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(sr,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const m=c(l).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(m),h=/^(reject|deny|delete|remove|abort)/.test(m),f=r===l,w=r!==null;return s.jsx("button",{onClick:()=>i(l),disabled:w,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!f?"opacity-40":"opacity-100"} ${w?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:f?"⏳ ...":c(l)},u)})})]})]})}const La="adhdev_controls_bar_visible",oa="adhdev:controlsbarvisibilitychange";function yn(e){if(!e)return!1;try{return e.getItem(La)==="1"}catch{return!1}}function Du(e,t){if(t)try{t.setItem(La,e?"1":"0")}catch{}}function Eu(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(oa,{detail:{visible:e}}))}function _a(){const[e,t]=o.useState(()=>typeof window>"u"?!1:yn(window.localStorage)),r=o.useRef(e),n=o.useCallback((c,l=!0)=>{r.current=c,t(c),typeof window<"u"&&Du(c,window.localStorage),l&&Eu(c)},[]);o.useEffect(()=>{const c=u=>{const m=u.detail,d=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:yn(window.localStorage);r.current=d,t(d)},l=u=>{if(u.key!==La)return;const m=yn(window.localStorage);r.current=m,t(m)};return window.addEventListener(oa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(oa,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 $u=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Bu(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function yt(e,t){if(Bu(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":$u.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 Ji(e){return yt(e)==="generating"}function at(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Ku(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%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 vn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function an(e,t){const r=typeof t=="string"?t.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 Ou(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),r=t[t.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function Wu(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Hu(e){return Ou(e.trim().replace(/\.local$/i,""))}function Fu(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Qi(e,t={}){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&&!Wu(c));if(r&&r!=="Unknown")return Hu(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Ct(e,t={}){return Fu(e)||Qi(e,t)}function Zi(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function ec(e,t,r={}){const n=String(t).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function ds(e,t){return Zi(e).join(" · ")}function nr(e){return e.transport==="pty"}function ws(e){return e.transport==="acp"}function Uu(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:at(e)}function Ao(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=at(r||"").trim().toLowerCase();return n===a||n===i||n===c}function zu(e){return yt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Vu(e){if(!Array.isArray(e)||e.length<=1)return e;const t=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=t.get(a),c=yt(n.status);if(!i){t.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&t.set(a,{...n,status:c})}return Array.from(t.values())}function Gu(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function qu(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&Gu(t.receivedAt)||0}function Yu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ia(e){return Math.max(Yu(e),qu(e.activeChat))}function Xu(e,t,r,n,a,i){const c=t-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function Pa(e,t){return Xu(ia(e),ia(t),Ct(e,{fallbackId:e.id}),Ct(t,{fallbackId:t.id}),e.id,t.id)}const tc="adhdev_notification_prefs",Io={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Ju(){try{const e=localStorage.getItem(tc);if(e){const t=JSON.parse(e);return{...Io,...t}}}catch{}return{...Io}}function Qu(e){try{localStorage.setItem(tc,JSON.stringify(e))}catch{}}let Ot=Ju(),Lr=[];function Zu(){Lr.forEach(e=>e())}function em(e){Ot={...Ot,...e},Qu(Ot),Zu()}function tm(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Lr.push(r),()=>{Lr=Lr.filter(n=>n!==r)}},[]);const t=o.useCallback(r=>{em(r)},[]);return[{...Ot},t]}function Ys(e){if(!Ot.globalEnabled)return!1;switch(e){case"disconnect":return Ot.disconnectAlert;case"completion":return Ot.completionAlert;case"approval":return Ot.approvalAlert;case"browser":return Ot.browserNotifications;default:return!0}}const sm={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function sc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function rc(){return"Notification"in window&&Notification.permission==="granted"}let Yt=null;function rm(e){return e!==!1}async function nm(){if(Yt!==null)return Yt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Yt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Yt=!!await e.pushManager.getSubscription(),Yt):(Yt=!1,!1)}catch{return Yt=!1,!1}}function ca(e,t,r){if(rc())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function am(e,t={}){const r={...sm,...t},n=o.useRef(new Map),a=o.useRef(0),[i,c]=o.useState(null);o.useEffect(()=>{let u=!1;return nm().then(m=>{u||c(m)}),()=>{u=!0}},[]);const l=o.useCallback((u,m,d)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,ca(u,m,d))},[r.throttleMs]);o.useEffect(()=>{var u;if(!(!r.enabled||!rc())&&Ys("browser")&&!rm(i)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,yt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const d=n.current.get(m.id),h=yt(m.status,{activeModal:m.activeModal}),f=m.name||m.id;if(r.onApproval&&Ys("approval")&&h==="waiting_approval"&&d!=="waiting_approval"){const w=((u=m.activeModal)==null?void 0:u.message)||"Action requires your approval";l(`🔔 ${f} — Approval needed`,w.slice(0,120),`approval-${m.id}`)}r.onComplete&&Ys("completion")&&Ji(d)&&h==="idle"&&l(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&h==="error"&&d!=="error"&&l(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,h)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,i,l])}const om=/^(run|approve|accept|yes|allow|always)/,im=/^(run|approve|accept|yes|allow|always|proceed|save)/,cm=/^(reject|deny|delete|remove|abort|cancel|no)/;function Da(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function lm(e){const t=Da(e).toLowerCase();return om.test(t)?"primary":cm.test(t)?"danger":"default"}function dm(e){return im.test(Da(e).toLowerCase())?"approve":"reject"}function um(e){return e.map((t,r)=>({label:Da(t),variant:lm(t),action:dm(t),button:t,buttonIndex:r}))}function mm(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function fm(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class pm{constructor(){Ye(this,"dedupMap",new Map);Ye(this,"DEDUP_WINDOW_MS",5e3);Ye(this,"DEDUP_MAX_SIZE",50);Ye(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ye(this,"toastCallbacks",[]);Ye(this,"resolveActionFn",null);Ye(this,"viewRequestRespondFn",null);Ye(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,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(t){if(t.daemonId){const a=this.ides.find(i=>i.id===t.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.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(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var k;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),i=n||t.daemonId||"",c=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),l=`${i}:${t.event}:${c}`;if(this.isDuplicate(l))return;const u=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(u==null?void 0:u.type)||"";let d=at(m);const h=this.resolveOwningDaemon(t);if(h){const p=Ct(h,{fallbackId:h.id});p&&(d=!m||m==="adhdev-daemon"?p:`${p}/${d}`)}let f="",w="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";f=`✅ ${d} agent task completed${p}`,w="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(f=`⚡ ${d} approval needed`,w="warning",(k=t.modalButtons)!=null&&k.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const S=this.resolveActionFn,x=um(t.modalButtons).map(I=>({label:I.label,variant:I.variant,onClick:()=>{S(p,"resolve_action",{action:I.action,button:I.button,buttonIndex:I.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),b=mm(d,t.modalMessage,f),y=Date.now();this.emitToast({id:y,message:b,type:w,timestamp:y,targetKey:n||p,actions:x,duration:15e3}),f=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";f=`⚠️ ${d} agent is taking a long time${p}`,w="warning",Ys("browser")&&!document.hasFocus()&&ca(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",S=t.requestId,x=t.orgId;if(f=`👁️ ${p} wants to view your session`,w="warning",S&&x&&this.viewRequestRespondFn){const b=Date.now(),y=fm(x,S,this.viewRequestRespondFn,(I,g)=>console.error(`[EventManager] ${I} view request failed:`,g));this.emitToast({id:b,message:f,type:w,timestamp:b,actions:y,duration:3e4}),f=""}Ys("browser")&&!document.hasFocus()&&ca("👁️ View Request",`${p} wants to view your session`,`view-request-${S}`)}else t.event==="team:view_request_approved"?(f="✅ View request approved",w="success"):t.event==="team:view_request_rejected"&&(f=`❌ ${t.targetName||"Team member"} declined your view request`,w="warning");if(f){const p=Date.now();this.emitToast({id:p,message:f,type:w,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const rt=new pm,Mo=new Map;function Vr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function js(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function on(e){return Vr(e)?Vr(e.result)?e.result:e:null}function hm(e){const t=on(e);return!t||!Vr(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function yr(e){const t=on(e);return!t||!Vr(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function Bs(e){const t=on(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function vr(e){const t=on(e);return!!t&&t.success===!1}function xm(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";rt.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";rt.showToast(n.notification.body,a)}}}function bm(e,t){return e&&js(e.currentValue)?e.currentValue:t}function gm(e,t){return js(t)?js(e)?typeof e=="string"&&e.trim()==="":!0:!1}function ym(e,t){var i,c;if((t.now??Date.now())<t.localOverrideUntil){const l=t.localValues[e];if(js(l))return l}const n=(i=t.controlValues)==null?void 0:i[e];if(js(n))return n;const a=(c=t.defaultValues)==null?void 0:c[e];return js(a)?a:void 0}function _r(e,t){return e.options||t[e.id]||[]}const vm={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 wm(e,t,r){var n;return((n=vm[t])==null?void 0:n.has(r.id))===!0}function Ea(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!wm(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function wn(e,t){return{value:t}}function jm(e,t,r){var a;return r?((a=_r(e,t).find(i=>i.value===r))==null?void 0:a.label)||r:""}const km={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Sm({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=ft(),u=`${e}:${t||n}`,m=km[n]||"#94a3b8",[d,h]=o.useState({}),f=o.useRef({}),w=o.useRef(c);f.current=d,w.current=c;const k=o.useRef(0),p={};for(const M of i||[])M.defaultValue!==void 0&&(p[M.id]=M.defaultValue);const S={...p,...c||{},...Date.now()<k.current?d:{}};o.useEffect(()=>{c&&Date.now()>k.current&&h({})},[c]);const[x,b]=o.useState(Mo.get(u)||{}),[y,I]=o.useState(null),[g,T]=o.useState(null),A=o.useCallback(async(M,O={})=>{const $={...O,...t&&{targetSessionId:t}};return await l(e,M,$)},[e,t,l]),j=o.useCallback(async(M,O={})=>{const $=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await A("invoke_provider_script",{...$,scriptName:M,...O})},[A,n,r,t]),v=o.useCallback((M,O,$)=>{const E=bm($,O);h(U=>({...U,[M.id]:E})),xm($==null?void 0:$.effects)},[]),K=o.useCallback((M,O)=>{h($=>{const E={...$};return O===void 0?delete E[M.id]:E[M.id]=O,E}),k.current=0},[]);if(!i||i.length===0)return null;const _=Ea(i,{hostIdeType:r,providerType:n});if(_.length===0)return null;const C=async M=>{if(y===M.id){I(null);return}if(_r(M,x).length>0){I(M.id);return}if(M.dynamic&&M.listScript){T(M.id);try{const $=await j(M.listScript,{}),E=hm($);if(!E){const he=Bs($);he&&rt.showToast(he,"warning");return}const U=E.options;b(he=>{const ce={...he,[M.id]:U};return Mo.set(u,ce),ce});const X=ym(M.id,{localOverrideUntil:k.current,localValues:f.current,controlValues:w.current,defaultValues:p});if(gm(X,E.currentValue)){const he=E.currentValue;h(ce=>({...ce,[M.id]:he}))}I(M.id)}catch($){const E=$ instanceof Error?$.message:`Could not load ${M.label}`;rt.showToast(E,"warning")}finally{T(null)}}},H=async(M,O)=>{I(null);const $=(c==null?void 0:c[M.id])??p[M.id];h(E=>({...E,[M.id]:O})),k.current=Date.now()+5e3;try{if(!M.setScript)return;const E=await j(M.setScript,wn(M,O)),U=yr(E);if(U&&!U.ok||vr(E))throw new Error((U==null?void 0:U.error)||Bs(E)||`Could not update ${M.label}`);v(M,O,U)}catch(E){K(M,$);const U=E instanceof Error?E.message:`Could not update ${M.label}`;rt.showToast(U,"warning")}},F=async M=>{const O=_r(M,x).map(ce=>ce.value);if(O.length===0)return;const $=String(S[M.id]||""),U=(O.indexOf($)+1)%O.length,X=O[U];if(typeof X!="string")return;const he=(c==null?void 0:c[M.id])??p[M.id];h(ce=>({...ce,[M.id]:X})),k.current=Date.now()+5e3;try{if(!M.setScript)return;const ce=await j(M.setScript,wn(M,X)),te=yr(ce);if(te&&!te.ok||vr(ce))throw new Error((te==null?void 0:te.error)||Bs(ce)||`Could not update ${M.label}`);v(M,X,te)}catch(ce){K(M,he);const te=ce instanceof Error?ce.message:`Could not update ${M.label}`;rt.showToast(te,"warning")}},P=async M=>{const $=!S[M.id],E=(c==null?void 0:c[M.id])??p[M.id];h(U=>({...U,[M.id]:$})),k.current=Date.now()+5e3;try{if(!M.setScript)return;const U=await j(M.setScript,wn(M,$)),X=yr(U);if(X&&!X.ok||vr(U))throw new Error((X==null?void 0:X.error)||Bs(U)||`Could not update ${M.label}`);v(M,$,X)}catch(U){K(M,E);const X=U instanceof Error?U.message:`Could not update ${M.label}`;rt.showToast(X,"warning")}},N=async M=>{if(!M.invokeScript)return;if(M.confirmMessage){const $=[M.confirmTitle,M.confirmMessage,M.confirmLabel].filter(U=>typeof U=="string"&&U.trim().length>0);if(!window.confirm($.join(`
|
|
28
|
+
|
|
29
|
+
`)))return}const O=(c==null?void 0:c[M.id])??p[M.id];try{const $=await j(M.invokeScript),E=yr($);if(E&&!E.ok||vr($))throw new Error((E==null?void 0:E.error)||Bs($)||`Could not run ${M.label}`);E&&v(M,O??!0,E)}catch($){K(M,O);const E=$ instanceof Error?$.message:`Could not run ${M.label}`;rt.showToast(E,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.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(M=>{const O=String(S[M.id]||""),$=jm(M,x,O),E=y===M.id,U=g===M.id,X=_r(M,x),he="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(M.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${m}55`:"var(--border-default)",background:E?`${m}10`:"var(--surface-tertiary)",color:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void C(M),title:M.label,children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:U?"Loading…":$||M.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),E&&X.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>I(null)}),s.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:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:M.label}),X.map(ce=>s.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:ce.value===O?`${m}14`:"transparent",color:ce.value===O?"var(--text-primary)":"var(--text-secondary)",borderLeft:ce.value===O?`2px solid ${m}`:"2px solid transparent"},title:ce.description||ce.label,onMouseEnter:te=>{te.currentTarget.style.background=`${m}10`},onMouseLeave:te=>{te.currentTarget.style.background=ce.value===O?`${m}14`:"transparent"},onClick:()=>void H(M,ce.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ce.label}),ce.value===O&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},ce.value))]})]})]},M.id);case"cycle":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:O?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void F(M),title:`Click to cycle: ${X.map(ce=>ce.label).join(" → ")}`,children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$||M.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},M.id);case"toggle":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:O?`${m}44`:"var(--border-default)",background:O?`${m}14`:"var(--surface-tertiary)",color:O?m:"var(--text-muted)"},onClick:()=>void P(M),"aria-pressed":!!O,children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),M.label]},M.id);case"action":return s.jsxs("button",{type:"button",className:`${he} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void N(M),children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:M.resultDisplay==="inline"&&O?`${M.label}: ${O}`:M.label})]},M.id);case"display":return s.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:O?"var(--text-primary)":"var(--text-muted)"},children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:O?`${M.label}: ${O}`:M.label})]},M.id);default:return null}})]})})}function Nm({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:m}=_a(),d=Ea(l,{hostIdeType:a,providerType:i});return!e||t||d.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(Sm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function Cm({hasDraft:e,isBusy:t=!1}){return!e||t}const nc=o.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1,animateVisibility:m=!0,onControlsToggle:d}){const h=o.useRef(null),[f,w]=o.useState(""),{isVisible:k,toggleVisibility:p}=_a();o.useEffect(()=>{w("")},[t]),o.useEffect(()=>{var x;l&&((x=h.current)==null||x.focus({preventScroll:!0}))},[t,l]);const S=async()=>{const x=f.trim();if(!x||a)return;await c(x)!==!1&&w("")};return s.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:[s.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&s.jsx("button",{type:"button",onClick:()=>{p(),d==null||d()},"aria-label":k?"Hide controls":"Show controls","aria-pressed":k,title:k?"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:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:h,type:"text",placeholder:i||`Send message to ${r}...`,value:f,onChange:x=>w(x.target.value),onPaste:x=>{const b=x.clipboardData.getData("text");b&&w(y=>y+b),x.preventDefault()},onKeyDown:x=>{if(x.key==="Enter"){if(x.nativeEvent.isComposing){x.preventDefault();return}x.preventDefault(),S()}},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))"}})}),s.jsx("button",{onClick:()=>{S()},disabled:Cm({hasDraft:!!f.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${f.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:f.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:f.trim()?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),et=e=>e.transport==="pty",Ds=(e,t)=>et(e)?e.mode||"terminal":"chat",ac=(e,t)=>et(e)&&Ds(e)==="terminal",Xe=e=>e.transport==="acp",Tm=180;function Vt(e){return e.streamSource!=="agent-stream"}function hs(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function oc(e){return e.machineName||""}function cr(e){return hs(e)}function Bt(e){return e.agentType||""}function Gr(e){return e.hostIdeType||""}function $a(e){return e.displayPrimary||e.agentName||"Agent"}function ic(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Am(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function cc(e){const t=Am(e),r=Ns(t==null?void 0:t.content),n=Ns(e.lastMessagePreview);return r||n||""}function Im(e,t=Tm){const r=Ns(e);if(!r||t<=0)return"";const n=Array.from(r);return n.length<=t?r:`${n.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function Mm(e){return Im(cc(e)||e.displaySecondary||"")}function lc(e){return[e.displaySecondary,oc(e)].filter(Boolean)}function Ts(e){return e.agentName||at(Bt(e))}function Rm(e){var t,r;if(!Vt(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return at(Gr(e)||Bt(e))}function dc(e){return Vt(e)?e.sessionId:e.nativeSessionId}function Ro(e){return Vt(e)?"native":e.tabKey}function Lm(e){return e.sessionId}function _m(e,t){if(t)return Vt(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Pm(e,t){const r=Bt(e),n=Vt(e),a=et(e)||Xe(e),i=n?a?Ts(e)||(t==null?void 0:t.cliName)||at(Gr(e)||r):t!=null&&t.type?at(t.type):at(Gr(e)||r):Ts(e);return{isNativeConversation:n,isCli:et(e),isAcp:Xe(e),isCliTerminal:ac(e),providerType:r,displayLabel:i,targetEntry:_m(e,t)}}function Zt(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:et(e)||Xe(e)?{agentType:Bt(e)}:e.streamSource==="agent-stream"?{agentType:Bt(e)}:t}function As(e){return e?cr(e):""}function Ks(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Ba(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Dm(e){const t=e instanceof Error?e.message:String(e||""),r=t.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.":t||"Unable to send message right now."}function uc(){return"select_session"}function Em(){return"open_panel"}function $m({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Bm(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Lo(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function qr(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ka(e){return e instanceof Error?e.message:String(e||"")}function _o(e){const t=Ka(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Po(e,t){const r=Ka(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function cn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,i]=o.useState(!1),[c,l]=o.useState(!1),[u,m]=o.useState(null),d=o.useRef(!1),h=o.useRef(null);o.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const f=o.useCallback(async S=>{if(!t)return!1;const x=S.trim(),b=Ba(t);if($m({hasMessage:!!x,blockedMessage:b,sendInFlight:d.current}))return b&&m(b),!1;const y=Date.now(),I={tabKey:t.tabKey,message:x,timestamp:y};if(Bm(h.current,I))return m(null),!0;d.current=!0,l(!0),m(null),h.current=I;try{const g=As(t);if(!g)return h.current=Lo(h.current,I),m("Unable to send message right now."),!1;const T=await e(g,"send_chat",{message:x,...Zt(t)}),A=qr(T);if(A!=null&&A.deduplicated)return m(null),!0;if((A==null?void 0:A.sent)===!1)throw new Error((A==null?void 0:A.error)||"Send failed");if((A==null?void 0:A.success)===!1)throw new Error((A==null?void 0:A.error)||"Send failed");return m(null),!0}catch(g){const T=Ka(g);return T.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",T):console.warn("Send blocked/failed",g),h.current=Lo(h.current,I),m(Dm(g)),!1}finally{d.current=!1,l(!1)}},[t,e]),w=o.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(S){console.error("Relaunch failed",S)}},[t,e]),k=o.useCallback(async S=>{if(t)try{const b=(t.modalButtons||[]).indexOf(S),y=S.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),I=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(y),g=As(t);if(!g)return;const T=await e(g,"resolve_action",{button:S,action:I?"approve":"reject",...b>=0&&{buttonIndex:b},...Zt(t)}),A=qr(T);A.success||r(j=>[...j,{routeId:t.tabKey,text:Po(S,A==null?void 0:A.error),timestamp:Date.now()}])}catch(x){_o(x)||console.error("[ModalButton] Error:",x),r(b=>[...b,{routeId:t.tabKey,text:_o(x)?Po(S,x):`❌ **${S}** error`,timestamp:Date.now()}])}},[t,e,r]),p=o.useCallback(async()=>{if(!(!t||a)){i(!0);try{await e(t.routeId,Em(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(S){console.error("Focus agent failed",S)}finally{i(!1)}}},[t,a,e]);return{isSendingChat:c,sendFeedbackMessage:u,isFocusingAgent:a,handleSendChat:f,handleRelaunch:w,handleModalButton:k,handleFocusAgent:p}}const Km=10,Om=8e3,Wm=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function Hm(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 la(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Wm.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=Hm(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=>la(a,t,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,la(a,n,r+1)]))}function wr(e,t){return Array.isArray(e)?e.slice(-t):[]}function Fm(e,t=Date.now()){const r=e&&t-e.firstAt<=Om,n=r?e.count+1:1;return n>=Km?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function mc(e){var n;const{activeConv:t}=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:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:t.messages.length,visible:e.visibleMessages.length,history:((n=e.chatTailState.historyMessages)==null?void 0:n.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:wr(t.messages,10),visibleMessagesTail:wr(e.visibleMessages,5),historyMessagesTail:wr(e.chatTailState.historyMessages,5),actionLogsTail:wr(e.actionLogs.filter(a=>a.routeId===t.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 la(r)}function fc(e,t={}){const r=e&&typeof e=="object"?e:{},n=t.locatorCopyStatus??(t.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 pc(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.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 hc(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&r.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&r.push("","warnings:",...t.warnings.map(n=>`- ${String(n)}`)),r.join(`
|
|
30
|
+
`)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
|
|
31
|
+
|
|
32
|
+
\`\`\`json
|
|
33
|
+
${JSON.stringify(t.bundle,null,2)}
|
|
34
|
+
\`\`\``:`# ADHDev Chat Debug Bundle
|
|
35
|
+
|
|
36
|
+
\`\`\`json
|
|
37
|
+
${JSON.stringify(t,null,2)}
|
|
38
|
+
\`\`\``}function vt(e){return(typeof e=="string"?e.trim():"")||void 0}function Wt(e,t){const r=vt(t);return r?`${e}:${r}`:void 0}function zt(e,t,r){const n=Wt(t,r),a=vt(r);n&&e.push(n),a&&e.push(a)}function vs(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function xc(e){return vt(e.providerSessionId)||vt(e.sessionId)||vt(e.tabKey)||vt(e.routeId)}function Oa(e){return vs([vt(e.providerSessionId),vt(e.sessionId)])}function ks(e){const t=[];return zt(t,"provider",e.providerSessionId),zt(t,"session",e.sessionId),zt(t,"tab",e.tabKey),zt(t,"route",e.routeId),vs(t)}function Um(e){const t=[];return vt(e.providerSessionId)?(zt(t,"provider",e.providerSessionId),vs(t)):vt(e.sessionId)?(zt(t,"session",e.sessionId),vs(t)):vt(e.tabKey)?(zt(t,"tab",e.tabKey),vs(t)):vt(e.routeId)?(zt(t,"route",e.routeId),vs(t)):[]}function Wa(e){return Wt("provider",e.providerSessionId)||Wt("session",e.sessionId)||Wt("tab",e.tabKey)||Wt("route",e.routeId)||"unknown:"}function lr(e){return Oa(e)[0]}function zm(e){const t=vt(e.providerSessionId),r=vt(e.sessionId),n=vt(e.tabKey),a=vt(e.routeId),i=[Wt("provider",t),Wt("session",r),Wt("tab",n),Wt("route",a)].filter(u=>typeof u=="string"),c=ks({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),l=Wa({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:xc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:lr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function da(e,t){const r=zm(e);return Um(t).some(n=>r.lookupKeys.includes(n))}function Do(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function es(e){const t=[...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=Do(t==null?void 0:t.receivedAt)||Do(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function ua(e,t=0){return es(e)||e.lastUpdated||t||0}function bc(e){return es(e)||e.lastUpdated||0}function gc(e,t,r=bc){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(t.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(t.displaySecondary);return c!==0?c:e.tabKey.localeCompare(t.tabKey)}function ma(e){var r;const t=yt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Vm(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!ma(e)&&!e.title.trim()}function Gm(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(ma(r))-Number(ma(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:gc(t,r)})[0]||null}function Pt(e,t){const r=e.filter(c=>c.routeId===t);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),i=Gm(a);return n?i&&Vm(n)?i:n:i||r[0]||null}function Gt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ha(e){return lr(e)||e.tabKey||e.routeId||null}function yc(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(t)return t;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?Ha(a):null}function vc({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=_s(),c=hs(e),l=oc(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",m=e.streamSource==="agent-stream"&&!!e.agentName,d=!m&&(e.transport==="pty"||e.transport==="acp"),h=Ts(e),f=Rm(e),w=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),k=o.useCallback(()=>{if(r){r();return}const p=Ha(e);p&&i(Gt(p))},[e,i,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:f,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:f})]}):s.jsxs("span",{className:"conversation-meta-chip",title:f,children:[s.jsx(Tt,{size:12}),s.jsx("span",{children:f})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(rr,{size:12}),s.jsx("span",{children:h})]}),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:h,children:[s.jsx(rr,{size:12}),s.jsx("span",{children:h})]}),l&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:l,children:[s.jsx(ls,{size:12}),s.jsx("span",{children:l})]}):s.jsxs("span",{className:"conversation-meta-chip",title:l,children:[s.jsx(ls,{size:12}),s.jsx("span",{children:l})]}))]})}function jn(e,t){return`${e}:${t}`}function qm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Os(e,t){qm()&&console.debug(`[subscription-manager] ${e}`,t)}class Ym{constructor(){Ye(this,"active",new Map);Ye(this,"retryTimers",new Map)}subscribe(t,r,n,a,i){var d;const c=jn(n.topic,n.key),l=this.active.get(c);let u=!0;if(l)l.handlers.add(a),l.lastUpdate&&a(l.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(c,h),Os("subscribe",{daemonId:r,topic:n.topic,key:n.key}),u=((d=t.sendData)==null?void 0:d.call(t,r,n))??!1,!u&&(i!=null&&i.retryIntervalMs)&&this.scheduleRetry(c,t,i.retryIntervalMs)}const m=()=>{var w;this.clearRetry(c);const h=this.active.get(c);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(c);const f={type:"unsubscribe",topic:n.topic,key:n.key};Os("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(w=t.sendData)==null||w.call(t,r,f)};return m.initialSendAccepted=u,m}publish(t){const r=jn(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Ss.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),Ss.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=jn(t,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(t){var r;Os("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=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===t);Os("resubscribe_daemon",{daemonId:t,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(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var l;this.retryTimers.delete(t);const i=this.active.get(t);if(!i)return;const c=((l=r.sendData)==null?void 0:l.call(r,i.daemonId,i.request))??!1;Os("subscribe_retry",{id:t,accepted:c,topic:i.request.topic,key:i.request.key}),c||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const Ht=new Ym;function Xm(e,t){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&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 Jm(e){const t=[],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 t.push(n);return{topLevel:t,childrenByParent:r}}function Yr(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=t,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:m,childrenByParent:d}=Jm(u),h=Xm(i,n),f=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=m.filter(S=>S.kind==="workspace"&&S.transport==="cdp-page"),k=m.filter(S=>S.kind==="agent"&&S.transport==="pty"),p=m.filter(S=>S.kind==="agent"&&S.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...f&&{machine:f,platform:f.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:w.some(S=>!!S.cdpConnected)});for(const S of w){const x=h.get(S.id),b=Vs(S,x),y=(d.get(S.id)||[]).map(I=>Vs(I,h.get(I.id)));r.push({id:`${n}:ide:${S.id}`,sessionId:S.id,providerSessionId:S.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:n,instanceId:S.id,workspace:b.workspace,terminals:0,childSessions:y,agents:y.map(I=>({id:I.id,name:I.providerName||I.providerType,type:I.providerType,status:I.status})),activeChat:b.activeChat,chats:[],cdpConnected:b.cdpConnected,...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l})}for(const S of k){const x=h.get(S.id),b=Vs(S,x);r.push({id:`${n}:cli:${S.id}`,sessionId:S.id,providerSessionId:S.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:S.id,cliName:b.providerName||b.providerType,mode:b.mode||(x==null?void 0:x.mode)||"terminal",workspace:b.workspace||"",activeChat:b.activeChat,...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isCli:!0})}for(const S of p){const x=h.get(S.id),b=Vs(S,x);r.push({id:`${n}:acp:${S.id}`,sessionId:S.id,providerSessionId:S.providerSessionId??(x==null?void 0:x.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:n,instanceId:S.id,cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",activeChat:b.activeChat,...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const Qm=15e3,Zm=15e3,ef=6e4,tf=1200,Eo=12,sf=8e3,rf=4e3,kn=new Map,Sn=new Map,jr=new Set,Xs=new Map;function nf(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function $o(e,t){const r=Xs.get(e);!r||r.size===0||(Xs.delete(e),r.forEach(n=>n(t)))}function af(e,t){return new Promise(r=>{const n=Xs.get(e)||new Set;Xs.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Xs.delete(e),r(c)},i=setTimeout(()=>a(!1),t);n.add(a)})}function dr(){const{sendCommand:e,sendData:t}=ft(),{injectEntries:r,getIdes:n}=tr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??ef,l=Sn.get(a)||0;if(!(i!=null&&i.force)&&jr.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=kn.get(a);if(u)return u;const m=(async()=>{if(t&&!jr.has(a)){const p=Ht.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},S=>{const x=n(),b=x.find(I=>I.id===a),y=Yr(S.status,{daemonId:a,existingDaemon:b,existingEntries:x,timestamp:S.timestamp});y.length>0&&r(y),Sn.set(a,Date.now()),$o(a,!0)});if(p.initialSendAccepted?jr.add(a):jr.delete(a),!(i!=null&&i.force)&&p.initialSendAccepted&&await af(a,tf))return}const d=await e(a,"get_status_metadata"),h=nf(d);if(!h)return;const f=n(),w=f.find(p=>p.id===a),k=Yr(h,{daemonId:a,existingDaemon:w,existingEntries:f,timestamp:h.timestamp||Date.now()});k.length>0&&r(k,{authoritativeDaemonIds:[a]}),Sn.set(a,Date.now()),$o(a,!0)})().finally(()=>{kn.delete(a)});return kn.set(a,m),m},[n,r,e,t])}function of(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const cf=60,lf=50;function wc(e={}){return e.isCliLike?lf:cf}function df(e={}){return wc(e)}const ur=60,uf=1e3,Fa=12e4,mf=new Set(["generating","waiting_approval","starting","streaming","working"]),Bo=new Map;function jc(e,t){return`${e}::${t}`}function fa(e=ur){return{liveMessages:[],cursor:ff([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function ff(e,t=ur){return{tailLimit:t}}function Ko(e,t){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 pf{constructor(t){Ye(this,"manager");Ye(this,"sendData");Ye(this,"daemonId");Ye(this,"sessionId");Ye(this,"historySessionId");Ye(this,"subscriptionKey");Ye(this,"snapshot");Ye(this,"transportSubscription",null);Ye(this,"listeners",new Set);Ye(this,"retainCount",0);Ye(this,"loadHistoryPromise",null);Ye(this,"pendingDisconnectTimer",null);this.manager=t.manager||Ht,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.snapshot=fa(Math.max(0,t.tailLimit??ur))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}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(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await t({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(),t=>{this.handleUpdate(t)},{retryIntervalMs:uf}))}disconnect(){var t;(t=this.transportSubscription)==null||t.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(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const r=Array.isArray(t.messages)?t.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};Ko(this.snapshot.liveMessages)===Ko(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.emit())}}function kc(e){const t=jc(e.daemonId,e.sessionId),r=Bo.get(t);if(r)return r.updateOptions(e),r;const n=new pf(e);return Bo.set(t,n),n}function hf(e,t){return{...e,loadHistoryPage:t}}function xf(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function bf(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(mf.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??Fa)),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 gf(e=Fa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function yf(e,t={}){const r=new Set,n=[];for(const a of e){if(!bf(a,t))continue;const i=cr(a),c=a.sessionId||"";if(!i||!c)continue;const l=jc(i,c);if(r.has(l))continue;r.add(l);const u=lr(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(xf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function vf(e,t){const{sendData:r,sendCommand:n}=ft(),a=(t==null?void 0:t.enabled)!==!1,i=cr(e),c=e.sessionId||"",l=lr(e)||c,u=`daemon:${i}:session:${c}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??ur),d=o.useMemo(()=>!a||!i||!c?null:kc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:m}),[i,a,l,r,c,u,m]),[h,f]=o.useState(()=>(d==null?void 0:d.getSnapshot())||fa(m));o.useEffect(()=>{if(!d){f(fa(m));return}d.retain(),f(d.getSnapshot());const k=d.subscribe(p=>{f(p)});return()=>{k(),d.release()}},[d,m]);const w=o.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async({offset:k,excludeRecentCount:p})=>{const S=e.agentType,x=await n(i,"chat_history",{agentType:S,offset:k,limit:30,targetSessionId:c,historySessionId:l,excludeRecentCount:p}),b=x&&typeof x=="object"&&"result"in x?x.result||{}:x||{};return{messages:Array.isArray(b.messages)?b.messages:[],hasMore:b.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return o.useMemo(()=>hf(h,w),[w,h])}function wf(e,t){const{sendData:r}=ft(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??ur),i=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Fa)),c=gf(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const d=setInterval(()=>{u(h=>h+1)},c);return()=>{clearInterval(d)}},[e.length,n,c]);const m=o.useMemo(()=>yf(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const d=m.descriptors.map(h=>kc({...h,sendData:r,tailLimit:a}));return d.forEach(h=>{h.retain()}),()=>{d.forEach(h=>h.release())}},[m.signature,n,r,a])}function jf(e,t){return t?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Oo(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function kf(e,t){if(e.length===0)return[];if(t.some(Oo))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||!Oo(i))continue;const c=String(i.role||"").toLowerCase();n.has(c)||(n.add(c),r.unshift(i))}return r}function Sf(e){const{historyMessages:t,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=kf(i,c),u=l.length>0?[...l,...c]:c;return t.length===0?u:[...t,...u]}function Nf(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Cf(e){return Nf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Tf(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Af(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function If(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Sc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Nc(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function Mf(e){return Sc(e)?!1:e.inboxBucket==="task_complete"&&Nc(e).length>0}function Wo(e){return e.branch||"detached HEAD"}function Rf(e){if(e.error)return`${Wo(e)} · Git error: ${e.error}`;const t=[Wo(e)];return e.changedFiles>0?t.push(Tf(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function Lf(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Rf(t)}`}function _f(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Pf(e,t={}){if(t.enabled===!1)return[];if(!If(e))return[];const r=Sc(e)?"working":Mf(e)?"complete":null;if(!r)return[];const n=r==="complete"?Nc(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Af(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Lf(r,e.git),timestamp:_f(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 Df=60;function pa({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:m=!1,scrollToBottomRequestNonce:d,isInputActive:h=!0,isVisible:f=!0}){var ge,ee,de,we,ue,xe,se;const w=o.useRef(new Map),k=o.useRef(void 0),p=dr(),{sendCommand:S}=ft(),{isVisible:x}=_a();ir("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const b=kt.useMemo(()=>Ps(e),[e.status,e.connectionState]),y=o.useMemo(()=>Pm(e,t),[e,t]),I=o.useMemo(()=>{var ie;return Ea((ie=y.targetEntry)==null?void 0:ie.providerControls,{hostIdeType:e.hostIdeType,providerType:y.providerType})},[e.hostIdeType,y.providerType,(ge=y.targetEntry)==null?void 0:ge.providerControls]),g=wc({isCliLike:y.isCli||y.isAcp}),T=df({isCliLike:y.isCli||y.isAcp}),A=vf(e,{enabled:f&&!!e.sessionId,tailLimit:T}),[j,v]=o.useState(g),K=e.tabKey,_=A.historyMessages,C=A.hasMoreHistory,H=A.historyError,F=jf(e,A);o.useEffect(()=>{v(g)},[g,K]);const P=Math.max(0,F.length-j),N=$a(e),M=cr(e),O=Cf(e),$=Ba(e),E=a||$,U=!!$,[X,he]=o.useState(!1);o.useEffect(()=>{const ie=y.targetEntry;M&&(!ie||ie.providerControls===void 0||ie.controlValues===void 0)&&p(M,{minFreshMs:3e4}).catch(()=>{})},[M,y.isAcp,(ee=y.targetEntry)==null?void 0:ee.providerControls,(de=y.targetEntry)==null?void 0:de.controlValues,p]);const ce=o.useCallback(async()=>{if(!X){if(F.length>j){v(ie=>Math.min(F.length,ie+Df));return}he(!0);try{await A.loadHistoryPage()}finally{he(!1)}}},[A,X,F.length,j]),{allMessages:te,receivedAtMap:ye}=o.useMemo(()=>{const ie=Sf({historyMessages:_,liveMessages:F,visibleLiveCount:j}),re=Pf(e),G=re.length>0?[...ie,...re]:ie,Y={};return G.forEach((le,ke)=>{const Z=`${e.tabKey}:${Ur(le,ke)}`;let Ce=of(le)||w.current.get(Z)||0;Ce||(Ce=Date.now(),w.current.set(Z,Ce)),Y[Ur(le,ke)]=Ce}),{allMessages:G,receivedAtMap:Y}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,P,_,F,j]),fe=o.useMemo(()=>l.filter(ie=>ie.routeId===e.tabKey).sort((ie,re)=>ie.timestamp-re.timestamp),[l,e.tabKey]),be=o.useCallback(async()=>{var ke,Z;if(!M)return;const ie=mc({activeConv:e,visibleMessages:te,actionLogs:l,controls:(ke=y.targetEntry)==null?void 0:ke.providerControls,controlValues:(Z=y.targetEntry)==null?void 0:Z.controlValues,visibleBarControlCount:I.length,chatTailState:{hasMoreHistory:C,historyError:H,historyMessages:_},ui:{controlsVisible:x,visibleLiveCount:j,hiddenLiveCount:P,isInputActive:h,isVisible:f}}),re=await S(M,"get_chat_debug_bundle",{agentType:y.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:ie}),G=qr(re),Y=hc(G),le=await pc(Y);le==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),rt.showToast(fc(G,{locatorCopyStatus:le}),le==="failed"?"warning":"success")},[e,l,te,x,y.providerType,(we=y.targetEntry)==null?void 0:we.controlValues,(ue=y.targetEntry)==null?void 0:ue.providerControls,M,C,P,_,h,f,H,S,I.length,j]),J=o.useCallback(()=>{const ie=Fm(k.current);k.current=ie.state,ie.shouldCollect&&be().catch(re=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",re),rt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[be]),ae=o.useMemo(()=>{if(F.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.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:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((b.isGenerating||e.status==="streaming")&&he(!1),e.status==="not_monitored"&&O)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(rr,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cs,{size:14})," Open ",N," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&O)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Oi,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Cs,{size:14})," Open ",N," Panel"]})}),s.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"&&!X)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,O,i,c,X,F.length,N,b.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&s.jsx(vc,{conversation:e,className:"chat-pane-meta-row"}),s.jsx(ku,{messages:te,actionLogs:fe,agentName:Ts(e)||N||"Agent",userName:u,isCliMode:y.isCli||y.isAcp,isWorking:b.isGenerating,contextKey:e.tabKey,receivedAtMap:ye,lastMessageHash:e.lastMessageHash,onLoadMore:ce,isLoadingMore:X,hasMoreHistory:C,hiddenLiveCount:P,loadError:H??void 0,emptyState:ae,scrollToBottomRequestNonce:d,isVisible:f}),s.jsx(Nm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:y.providerType,displayLabel:y.displayLabel,controls:(xe=y.targetEntry)==null?void 0:xe.providerControls,controlValues:(se=y.targetEntry)==null?void 0:se.controlValues,isActive:h,isCliTerminal:y.isCliTerminal}),!y.isCliTerminal&&s.jsx(nc,{contextKey:e.tabKey,panelLabel:N,isSending:n,isBusy:U,statusMessage:E,onSend:r,isActive:h,showControlsToggle:I.length>0,onControlsToggle:J})]})}let Cc=cs;function Tc(){return Cc()}class Ef{constructor(){Ye(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let Ac=new Ef;class $f{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let it=new $f;function Bf(e){e.dashboardWS&&(Ac=e.dashboardWS),e.connectionManager&&(it=e.connectionManager),e.useDaemonsHook&&(Cc=e.useDaemonsHook)}const Kf=.5,Of=1.25;function ot(e){return $a(e)}function us(e){return lc(e).join(" · ")}function Ic(e){const t=cc(e);return t||(e.title?e.title:us(e)||"No messages yet")}function Mc(e,t){const{isReconnecting:r,isConnecting:n}=Ps(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function Wf(e,t){const r=["Chat",...lc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function ts(e){return Mc(e)||us(e)}function Hf(e){return`${ot(e)} · ${Ic(e)}`}function Ff(e){const t=Gr(e),r=t?at(t):Ts(e);return`${ot(e)} — ${r||"Agent"}`}function Uf(e){return Ts(e)||"CLI"}function Rc(e){return ic(e)}function Lc(e){return e?`Remote · ${ot(e)||e.workspaceName||"Session"}`:"Remote"}function zf({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0,isInputActive:l=!0}){var V;cs();const{sendPtyInput:u}=ft(),[m,d]=o.useState(!1),h=o.useRef(!1);h.current=m;const[f,w]=o.useState("Runtime terminal unavailable"),[k,p]=o.useState(!1),[S,x]=o.useState(null),[b,y]=o.useState(!1),[I,g]=o.useState(!1),[T,A]=o.useState(1),[j,v]=o.useState(!1),[K,_]=o.useState({width:0,height:0}),[C,H]=o.useState({width:0,height:0}),[F,P]=o.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[N,M]=o.useState(null),O=o.useRef(null),$=o.useRef(null),E=o.useRef(!1),U=o.useRef(!1),X=o.useRef(c),he=o.useRef(0),ce=o.useRef(!1),te=o.useRef(""),ye=o.useRef(null),fe=o.useRef(!1),be=o.useRef(!1),J=o.useRef(null),ae=o.useRef(null),ge=o.useRef(null),ee=32*1024,de=()=>{var L,q,Q,ne;return((q=(L=O.current)==null?void 0:L.ownerDocument)==null?void 0:q.defaultView)||((ne=(Q=$.current)==null?void 0:Q.ownerDocument)==null?void 0:ne.defaultView)||window},we=L=>{const q=de();return{ownerWindow:q,frameId:q.requestAnimationFrame(L)}},ue=()=>{const L=J.current;if(L){try{L.ownerWindow.cancelAnimationFrame(L.frameId)}catch{}J.current=null}},xe=()=>{const L=ae.current;if(L){try{L.ownerWindow.clearTimeout(L.timeoutId)}catch{}ae.current=null}},se=()=>{const L=ge.current;if(L){try{L.ownerWindow.clearTimeout(L.timeoutId)}catch{}ge.current=null}},ie=()=>{c&&J.current===null&&(J.current=we(()=>{Je()}))},re=e.tabKey,G=e.sessionId||"",Y=e.daemonId||((V=e.routeId)==null?void 0:V.split(":")[0])||e.routeId||"",le=Ba(e),ke=m?i||le:f,Z=Kf,Ce=Of,Pe=.05,We=()=>{const L=C.width,q=C.height;if(!Number.isFinite(K.width)||K.width<=0||!Number.isFinite(K.height)||K.height<=0||!Number.isFinite(L)||L<=0||!Number.isFinite(q)||q<=0)return 1;const Q=K.width/L,ne=K.height/q;return Number(Math.min(Ce,Math.max(Z,Math.min(Q,ne))).toFixed(2))},He=We(),D=E.current&&T>He,Se=Number.isFinite(C.width)&&C.width>0?Math.max(K.width,Math.round(C.width*T)):K.width,Ie=Number.isFinite(C.height)&&C.height>0?Math.max(K.height,Math.round(C.height*T)):K.height,Re=()=>{we(()=>{const L=$.current;L&&(L.scrollLeft=0,L.scrollTop=L.scrollHeight-L.clientHeight)})},Ee=()=>{var L,q;he.current=0,ce.current=!1,te.current="",ye.current=null,fe.current=!1,be.current=!1,E.current||(U.current=!1,A(1)),J.current!==null&&ue(),d(!1),w("Runtime terminal unavailable"),se(),xe(),x(null),M(null),v(!1),p(!1),y(!1),g(!1),(q=(L=r.current)==null?void 0:L.reset)==null||q.call(L)},Fe=()=>{var L,q;he.current=0,ce.current=!1,te.current="",ye.current=null,fe.current=!1,be.current=!1,J.current!==null&&ue(),d(!0),w(""),se(),xe(),x(null),M(null),v(!1),p(!1),y(!1),g(!1),(q=(L=r.current)==null?void 0:L.reset)==null||q.call(L)},Ue=()=>{be.current&&(be.current=!1,we(()=>{var L,q;(q=(L=r.current)==null?void 0:L.scrollToTop)==null||q.call(L)}))},Je=()=>{if(J.current=null,!c)return;const L=te.current;if(!L)return;const q=L.slice(0,ee);te.current=L.slice(q.length);const Q=r.current;if(!Q){te.current=q+te.current,ie();return}Q.write(q,()=>{if(te.current.length>0){ie();return}Ue()})},dt=L=>{L&&(te.current+=L,ie())},ut=(L,q=0,Q,ne,ve={})=>{var _e,Ne,De,Be;const Ae=!!ve.force;!Ae&&q>0&&he.current>=q||!Ae&&q===0&&ce.current||(he.current=q,q>0&&y(!0),d(!0),w(""),typeof Q=="number"&&typeof ne=="number"&&Q>0&&ne>0&&((Ne=(_e=r.current)==null?void 0:_e.resize)==null||Ne.call(_e,Q,ne)),te.current="",(Be=(De=r.current)==null?void 0:De.reset)==null||Be.call(De),L?dt(L):Ue())};o.useEffect(()=>{Ee()},[G]),o.useEffect(()=>{var q;if(!G)return;const L=((q=it.onRuntimeEvent)==null?void 0:q.call(it,G,Q=>{if(!(!Q||Q.sessionId!==G)){if(Q.type==="runtime_snapshot"){if(!c){ye.current={text:Q.text||"",seq:Q.seq||0,cols:Q.cols,rows:Q.rows,force:!!Q.force};return}ut(Q.text||"",Q.seq||0,Q.cols,Q.rows,{force:!!Q.force});return}if(Q.type==="session_output"){ce.current=!0,typeof Q.seq=="number"&&(he.current=Math.max(he.current,Q.seq),Q.seq>0&&y(!0)),h.current||d(!0),h.current||w(""),typeof Q.data=="string"&&dt(Q.data);return}if(Q.type==="session_cleared"){if(!c){fe.current=!0,te.current="",ye.current=null;return}Fe();return}if(Q.type==="session_io_error"){const ne=typeof Q.error=="string"&&Q.error?Q.error:typeof Q.reason=="string"&&Q.reason?Q.reason:"unknown error";d(!1),w(`Runtime input failed: ${ne}`);return}}},Y))||(()=>{});return()=>{L()}},[Y,G,r,c]);const lt=async(L={})=>{var q;if(!Y||!G)return{success:!1,error:"daemonId and sessionId are required"};L.preserveStatus||w(L.loadingMessage||"Loading runtime terminal...");try{const Q=await((q=it.requestRuntimeSnapshot)==null?void 0:q.call(it,Y,G,{sinceSeq:L.sinceSeq,force:L.force}));return Q&&Q.success===!1?(L.preserveStatus||(d(!1),w(`Runtime terminal unavailable: ${Q.error}`)),Q):Q||{success:!0}}catch(Q){const ne=(Q==null?void 0:Q.message)||String(Q);return L.preserveStatus||(d(!1),w(`Runtime terminal unavailable: ${ne}`)),{success:!1,error:ne}}},Te=async L=>{var Ae,_e;const q=((Ae=O.current)==null?void 0:Ae.ownerDocument)||document,Q=q.defaultView||window,ne=(_e=Q.navigator)==null?void 0:_e.clipboard;if(ne!=null&&ne.writeText&&Q.isSecureContext)try{return await ne.writeText(L),!0}catch{}let ve=null;try{return ve=q.createElement("textarea"),ve.value=L,ve.setAttribute("readonly","true"),ve.style.position="fixed",ve.style.left="-9999px",ve.style.top="0",q.body.appendChild(ve),ve.focus(),ve.select(),q.execCommand("copy")}catch{return!1}finally{ve==null||ve.remove()}},Ge=L=>{xe(),M(L);const q=de();ae.current={ownerWindow:q,timeoutId:q.setTimeout(()=>{ae.current=null,M(Q=>Q===L?null:Q)},2200)}},Qe=L=>{se(),x(L);const q=de();ge.current={ownerWindow:q,timeoutId:q.setTimeout(()=>{ge.current=null,x(Q=>Q===L?null:Q)},2200)}},qe=async()=>{var ve,Ae,_e,Ne;const L=((Ae=(ve=r.current)==null?void 0:ve.getSelection)==null?void 0:Ae.call(ve))||"",q=((Ne=(_e=r.current)==null?void 0:_e.getVisibleText)==null?void 0:Ne.call(_e))||"",Q=L.trimEnd()||q.trimEnd();if(!Q){Ge("Nothing to copy");return}if(!await Te(Q)){Ge("Copy failed");return}Ge(L.trimEnd()?"Copied selection":"Copied visible terminal")},tt=L=>{if(!m||!c)return;((u==null?void 0:u(Y,G,L))??!1)||Ge("Terminal input failed")},W=async()=>{if(k)return;p(!0),x("Loading older terminal output..."),be.current=!0;const L=await lt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(L==null?void 0:L.success)===!1){be.current=!1,x(`Older terminal output unavailable: ${L.error}`);return}g(!0),Qe("Older terminal output loaded"),we(()=>{var q;(q=r.current)==null||q.bumpResize()})};o.useEffect(()=>{var q,Q;if(!G)return;Y&&((q=it.getState)==null?void 0:q.call(it,Y))==="connected"&<();const L=(Q=it.onStateChange)==null?void 0:Q.call(it,(ne,ve)=>{ne!==Y||ve!=="connected"||lt()});return()=>{L==null||L()}},[Y,G,r]),o.useEffect(()=>{t&&Ee()},[t,re,r]),o.useEffect(()=>{var ne,ve;const L=O.current,q=(ve=(ne=L==null?void 0:L.ownerDocument)==null?void 0:ne.defaultView)==null?void 0:ve.ResizeObserver;if(!L||!q)return;const Q=new q(Ae=>{const _e=Ae[0];if(!_e)return;const{width:Ne,height:De}=_e.contentRect;_(Be=>{const Le=Math.round(Ne),ze=Math.round(De);return Be.width===Le&&Be.height===ze?Be:{width:Le,height:ze}})});return Q.observe(L),()=>Q.disconnect()},[]),o.useEffect(()=>{if(E.current)return;const L=We();!Number.isFinite(L)||L<=0||A(q=>U.current?L<q-Pe?L:q:(U.current=!0,L))},[C.height,C.width,K.height,K.width]),o.useEffect(()=>{D&&Re()},[D,Ie,Se]),o.useEffect(()=>{var Q;const L=X.current;if(X.current=c,!c)return;L||g(!1),fe.current&&(fe.current=!1,Fe());const q=ye.current;q&&(ye.current=null,ut(q.text,q.seq,q.cols,q.rows,{force:!!q.force})),Y&&G&&((Q=it.getState)==null?void 0:Q.call(it,Y))==="connected"&<(),te.current&&J.current===null&&ie(),we(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[Y,c,G]),o.useEffect(()=>()=>{J.current!==null&&ue(),xe(),se()},[]),o.useEffect(()=>{const L=ne=>{var Ae;const ve=ne.detail;ve!=null&&ve.sessionId&&ve.sessionId!==G||m&&((Ae=r.current)==null||Ae.bumpResize())},q=de(),Q=q===window?[window]:[window,q];for(const ne of Q)ne.addEventListener("adhdev:fit-cli-terminal",L);return()=>{for(const ne of Q)ne.removeEventListener("adhdev:fit-cli-terminal",L)}},[m,G,r]);const R=m&&b&&!I&&(F.atTop||!F.canScroll)||k||!!S;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:O,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[R&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.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:()=>{W()},disabled:!G||k,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:k?"Loading older...":"Load older terminal output"}),S&&s.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:S})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[N&&s.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:N}),s.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:()=>{qe()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.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(L=>!L),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":j,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),j&&s.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:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.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:"×"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.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"}),s.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"}),s.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"}),s.jsx("span",{"aria-hidden":"true"}),s.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:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.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:"←"}),s.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:"↓"}),s.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:"→"}),s.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"}),s.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"}),s.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"})]})]})]}),s.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:()=>{E.current=!0,A(L=>{const q=Math.max(He,Number((L-.1).toFixed(2)));return q>He&&Re(),q})},title:"Shrink terminal viewport",children:"-"}),s.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:()=>{E.current=!0,A(L=>{const q=Math.min(Ce,Number((L+.1).toFixed(2)));return q>He&&Re(),q})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:$,className:D?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Se>0?`${Se}px`:"100%",height:Ie>0?`${Ie}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:C.width>0?`${C.width}px`:"100%",height:C.height>0?`${C.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:T},children:s.jsx(Gi,{ref:r,readOnly:!m||!c,sizingMode:"measured",onViewportMetrics:H,onScrollMetrics:P,onInput:L=>{!m||(u==null||u(Y,G,L))}})})})}),!m&&s.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:f})]}),s.jsx(nc,{contextKey:e.tabKey,panelLabel:ot(e),isSending:a,isBusy:!!le,statusMessage:ke,onSend:async L=>le?!1:n(L),isActive:l&&c,showControlsToggle:!1,animateVisibility:!1})]})}const Vf=5e3,Gf=12e3;function qf(e){return e==="disconnected"||e==="reconnecting"}function Yf({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=Vf,reconnectActionDelayMs:i=Gf}){const c=qf(e),[l,u]=o.useState(()=>!c||a<=0),[m,d]=o.useState(()=>!c||i<=0),h=o.useRef(!1);o.useEffect(()=>{if(!c){u(!1);return}if(h.current=!1,a<=0){h.current=!0,u(!0);return}u(!1);const g=setTimeout(()=>{h.current=!0,u(!0)},a);return()=>clearTimeout(g)},[a,c]),o.useEffect(()=>{if(!c){d(!1);return}if(i<=0){d(!0);return}d(!1);const g=setTimeout(()=>{d(!0)},i);return()=>clearTimeout(g)},[i,c]);const f=c?l:e==="offline"||e==="auth_failed",w=!!(n&&e!=="auth_failed"&&(!c||m)),k=o.useMemo(()=>!t||e!=="connected"?!1:a<=0||h.current,[a,t,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",S={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))"},x={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)"},b={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",I={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[f&&s.jsx("div",{className:y,style:I,children:s.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:S[p],border:x[p],color:b[p]},children:[s.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}}),s.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?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),w&&s.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"})]})}),k&&s.jsx("div",{className:y,style:I,children:s.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:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Xf({terminalBackend:e,isStandalone:t=!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]),!t||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",u=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return s.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:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[l," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.jsx("button",{type:"button",onClick:u,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Ua({mode:e,onChange:t,compact:r=!1}){const n=r?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?s.jsx(Ia,{size:n}):s.jsx(Ft,{size:n})})}const Et="New session",_c="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 Jf(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 t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function Qf(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 Zf(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 Is({git:e,className:t="",compact:r=!1}){const n=Jf(e),a=Qf(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 s.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 ${Zf(a)} ${t}`.trim(),title:i.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function ep({wsStatus:e,isConnected:t,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..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function Ho({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Fo({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=rn(e.updatedAt),l=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function tp({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:l,onSetCliViewMode:u,onHideConversation:m,hiddenConversations:d=[],onShowConversation:h,onShowAllHidden:f,onResetPanelsToMain:w,inboxOpen:k,onInboxOpenChange:p,hiddenOpen:S,onHiddenOpenChange:x,onOpenNewSession:b,onOpenDashboardGuide:y,guideNudgeVisible:I=!1,actionShortcuts:g,notifications:T,notificationUnreadCount:A,onOpenNotification:j,onMarkNotificationRead:v,onMarkNotificationUnread:K,onDeleteNotification:_,onOpenGitDialog:C}){const{ides:H,p2pStates:F={}}=cs(),P=!!e&&et(e)&&!Xe(e),N=!!e&&Xe(e),M=l||(e?ac(e)?"terminal":"chat":null),[O,$]=o.useState(!1),E=o.useRef(null),U=o.useRef(null),X=H.filter(ee=>ee.type==="adhdev-daemon"),he=ep({wsStatus:t,isConnected:r,daemonCount:X.length,p2pStates:F}),ce=he.subtitle,te=he.tone==="connected"?"#22c55e":he.tone==="limited"?"#eab308":"#ef4444",ye=he.tone==="connected"?"0 0 4px #22c55e80":he.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",fe=o.useMemo(()=>T.filter(ee=>!ee.readAt),[T]),be=o.useMemo(()=>T.filter(ee=>!!ee.readAt),[T]),J=o.useMemo(()=>fe.slice(0,9),[fe]),ae=A;o.useEffect(()=>{if(!k)return;const ee=de=>{var we;(we=E.current)!=null&&we.contains(de.target)||p(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[k,p]),o.useEffect(()=>{if(!S)return;const ee=de=>{var we;(we=U.current)!=null&&we.contains(de.target)||x(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[S,x]),o.useEffect(()=>{if(!S&&!k)return;const ee=de=>{if(!de.altKey)return;const we=de.code.match(/^Digit([1-9])$/);if(!we)return;const ue=Number(we[1])-1,xe=S?d[ue]:void 0,se=k?J[ue]:void 0;if(!(!xe&&!se)){if(de.preventDefault(),de.stopPropagation(),xe){h==null||h(xe),x(!1);return}se&&(j(se),p(!1))}};return window.addEventListener("keydown",ee,!0),()=>window.removeEventListener("keydown",ee,!0)},[d,S,k,J,x,p,j,h]);const ge=ee=>{if(!ee)return;const de=n.find(we=>we.tabKey===ee);de&&(m==null||m(de))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Ft,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?ot(e):"Dashboard"}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:te,boxShadow:ye}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[s.jsx("span",{title:he.title,className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:te,boxShadow:ye}}),ce&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ce]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${Et}${g!=null&&g.openNewSession?` (${g.openNewSession})`:""}`,"aria-label":Et,children:s.jsx(Hi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[y&&s.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:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),I&&s.jsx("span",{children:"Guide"})]}),e&&(P||N||!Xe(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:us(e)||ot(e),children:ot(e)}),C&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>C(e.daemonId,e.workspacePath),children:s.jsx(Is,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Is,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(P||N)&&c&&s.jsxs(s.Fragment,{children:[P&&u&&M&&s.jsx(Ua,{mode:M,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>c(e),className:"btn btn-secondary btn-sm",title:N?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(St,{size:14})})]}),!Xe(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(Ta,{size:14})}),!P&&!Xe(e)&&s.jsx("button",{onClick:i,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Tt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:E,children:[s.jsxs("div",{className:`dashboard-header-hidden${O?" is-drop-target":""}`,ref:U,onDragEnter:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),$(!0))},onDragOver:ee=>{ee.dataTransfer.types.includes("text/tab-key")&&(ee.preventDefault(),ee.dataTransfer.dropEffect="move",$(!0))},onDragLeave:ee=>{ee.currentTarget.contains(ee.relatedTarget)||$(!1)},onDrop:ee=>{const de=ee.dataTransfer.getData("text/tab-key");ee.preventDefault(),$(!1),ge(de)},children:[s.jsxs("button",{type:"button",onClick:()=>x(!S),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${g!=null&&g.toggleHiddenTabs?` (${g.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Aa,{size:16}),d.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:d.length})]}),S&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(Ho,{value:g==null?void 0:g.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[w&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:w,children:"Reset panels"}),d.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),x(!1)},children:"Restore all"})]})]}),e&&m&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(Ho,{value:g==null?void 0:g.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:ot(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(ee=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(ee),x(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:ot(ee)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(ee)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(ee)+1]}):null,us(ee)]})]},ee.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!k),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(sn,{size:16}),ae>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ae})]}),k&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[fe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),fe.map(ee=>s.jsx(Fo,{notification:ee,shortcutIndex:J.indexOf(ee)>=0?J.indexOf(ee)+1:void 0,onOpen:()=>j(ee),onMarkRead:()=>v(ee.id),onMarkUnread:()=>K(ee.id),onDelete:()=>_(ee.id)},ee.id))]}),be.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),be.map(ee=>s.jsx(Fo,{notification:ee,onOpen:()=>j(ee),onMarkRead:()=>v(ee.id),onMarkUnread:()=>K(ee.id),onDelete:()=>_(ee.id)},ee.id))]}),T.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function xt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function sp(e,t){return String(e||"")!==String(t||"")}function rp(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),i=!!t.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
|
|
39
|
+
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!Zi(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
40
|
+
`).includes(a)))}function np(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="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 Pc(e,t={}){return np(rp(e,t),t.sortMode||"recent")}function Xr(e){return e?"Resume saved history":"Start fresh"}function za(e){return e?"Resuming saved history…":"Starting fresh…"}function ap(){return"Start fresh"}function Dc(e,t=!1){return e==="cli"?Xr(t):e==="ide"?"Start IDE":"Start ACP session"}function Ec(e,t=!1){return e==="cli"?za(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function op(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function ip(){return"Open saved history"}function cp(){return"Saved History"}function Va(){return"Use saved history when you want continuity in the same provider conversation."}function lp(){return"No saved history found yet."}function dp(){return"Refresh saved history"}function up(){return"Refreshing saved history…"}function ss(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function rs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Ms(e){return e==="start-fresh"?"Start fresh":"Restart"}function Rs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Ga(e){return`Resume saved history with ${e}?`}function qa(){return"Review or change the target workspace before resuming saved history."}function mp(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 Ya({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:m,onClose:d,onNewChat:h,onSwitchSession:f,onRefreshHistory:w,onResumeSavedSession:k}){var _;const p=t.find(C=>C.id===e.routeId),S=(p==null?void 0:p.chats)||[],x=(_=p==null?void 0:p.activeChat)==null?void 0:_.id,b=et(e)&&!Xe(e),[y,I]=o.useState(()=>xt()),g=l||y,T=String(u||"").trim(),A=C=>{if(m){m(C);return}I(C)},j=o.useMemo(()=>a.map(C=>{const H=String(C.workspace||"").trim();return C.canResume||H||!T?C:{...C,workspace:T,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[T,a]),v=o.useMemo(()=>Pc(j,{textQuery:g.textQuery,workspaceQuery:g.workspaceQuery,modelQuery:g.modelQuery,resumableOnly:g.resumableOnly,sortMode:g.sortMode}),[j,g.modelQuery,g.resumableOnly,g.sortMode,g.textQuery,g.workspaceQuery]),K=s.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:[s.jsx("div",{onClick:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.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:[s.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:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:b?cp():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Ff(e)}),b&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Va()})]}),s.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(St,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!b&&s.jsx("button",{onClick:h,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),b?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:g.textQuery,onChange:C=>A({...g,textQuery:C.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"}),s.jsx("input",{type:"text",value:g.workspaceQuery,onChange:C=>A({...g,workspaceQuery:C.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"}),s.jsx("input",{type:"text",value:g.modelQuery,onChange:C=>A({...g,modelQuery:C.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"}),s.jsxs("select",{value:g.sortMode,onChange:C=>A({...g,sortMode:C.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:g.resumableOnly,onChange:C=>A({...g,resumableOnly:C.target.checked})}),"Resume-ready only"]})]}),v.map(C=>{const H=e.providerSessionId===C.providerSessionId,F=H||!C.canResume||!!c,P=C.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{F||!k||k(C)},disabled:F,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${H?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${F?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${H?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:C.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:C.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:mp(C.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:C.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[C.workspace||"Workspace unknown",P?" · selected workspace":"",ds(C.summaryMetadata)?` · ${ds(C.summaryMetadata)}`:"",C.messageCount>0?` · ${C.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:H?"ACTIVE":C.canResume?P?"RESUME IN SELECTED WORKSPACE":c===C.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},C.id)})]}):S.map(C=>s.jsxs("div",{onClick:()=>{f(e.routeId,C.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${x===C.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${x===C.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:C.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[C.id.substring(0,12),"..."]}),x===C.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},C.id)),(b&&!i&&v.length===0||!b&&S.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Xd,{size:32})}),s.jsx("div",{className:"text-[13px]",children:b?a.length>0?"No saved history matches these filters.":lp():"No recent chat sessions found."})]}),b&&i&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:up()})})]}),s.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:s.jsx("button",{onClick:w,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(or,{size:13})," ",b?dp():"Refresh History"]})})})]})]});return typeof document>"u"?K:er.createPortal(K,document.body)}const Uo={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 $c({toasts:e,onDismiss:t,onClickToast:r}){return s.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=Uo[n.type]||Uo.info;return s.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:[s.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))`}}),s.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(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(St,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.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})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>s.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(),t(n.id)},children:i.label},c))})]})]},n.id)})})}const fp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function pp(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function hp(e){return e.sessionId||e.instanceId||e.agentType}function Nn(e,t){return e||t}function Bc(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Ct(r,{fallbackId:r.id}));return t}function Kc(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Xa(e,t={}){return xp(e,Kc(e,t))}function xp(e,t={}){var h,f,w,k,p,S;const r=[],n=t.machineName,a=t.connectionState,i=pp(e),c=e.workspace||"",l=Uu(e.type,{agentName:e.cliName}),u=et(e)||Xe(e)?l:at(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(x=>{var b,y;return{sessionId:x.id,instanceId:x.id,providerSessionId:x.providerSessionId,transport:x.transport,sessionCapabilities:x.capabilities,agentType:x.providerType,agentName:x.providerName||at(x.providerType),status:x.status,title:x.title,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,messages:((b=x.activeChat)==null?void 0:b.messages)||[],activeModal:((y=x.activeChat)==null?void 0:y.activeModal)||void 0,unread:x.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,surfaceHidden:x.surfaceHidden,git:x.git}}):[],d=fp(e);if(d){const x=e.sessionId||e.instanceId,b=l,y=(h=e.activeChat)==null?void 0:h.activeModal,I=y&&Array.isArray(y.buttons)&&y.buttons.length>0,g=yt((f=e.activeChat)==null?void 0:f.status,{activeModal:(w=e.activeChat)==null?void 0:w.activeModal})||yt((p=(k=e.agents)==null?void 0:k[0])==null?void 0:p.status)||"idle",T=e.activeChat||{title:"",messages:[]};let A=T.title&&String(T.title).trim()?String(T.title).trim():"";const j=(S=e.activeChat)==null?void 0:S.id,v=e.chats;if(j&&Array.isArray(v)&&v.length>0){const H=v.find(F=>F.id===j||F.id&&String(F.id)===String(j));H!=null&&H.title&&String(H.title).trim()&&(A=String(H.title).trim())}const K=(et(e)||Xe(e),e.type),_=(et(e)||Xe(e))&&Ao(A,b,K)?"":A,C=T.messages||[];r.push({routeId:e.id,sessionId:x,providerSessionId:e.providerSessionId,nativeSessionId:x,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:et(e)?e.mode||"terminal":"chat",agentName:b,agentType:K,status:g,title:_,messages:C,resume:e.resume,hostIdeType:!et(e)&&!Xe(e)?e.type:void 0,workspaceName:i,workspacePath:c,git:e.git,displayPrimary:_||i||(et(e)?e.mode==="chat"?b:"Terminal":b),displaySecondary:u,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:I?y.buttons:void 0,modalMessage:I?y.message:void 0,streamSource:"native",tabKey:Nn(x,e.id),machineName:n,connectionState:a})}if(d&&(et(e)||Xe(e)))return r;for(const x of m){const b=x.activeModal&&Array.isArray(x.activeModal.buttons)&&x.activeModal.buttons.length>0,y=zu(x),I=hp(x),g=`${e.id}:${I}`,T=x.title&&String(x.title).trim()||"",A=Ao(T,x.agentName,x.agentType)?"":T,j=x.messages||[];(x.transport==="cdp-webview"||x.sessionId||x.providerSessionId||j.length>0||b||A||!["idle","panel_hidden","disconnected","not_monitored"].includes(y))&&r.push({routeId:e.id,sessionId:x.sessionId||x.instanceId,providerSessionId:x.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:x.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:x.sessionCapabilities,mode:"chat",agentName:x.agentName,agentType:x.agentType,status:y,title:A,messages:j,hostIdeType:e.type,workspaceName:i,workspacePath:c,git:x.git||e.git,displayPrimary:A||i||x.agentName||u,displaySecondary:`${u} · ${x.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:x.lastMessagePreview,lastMessageRole:x.lastMessageRole,lastMessageAt:x.lastMessageAt,lastMessageHash:x.lastMessageHash,lastUpdated:x.lastUpdated||e.lastUpdated,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,modalButtons:b?x.activeModal.buttons:void 0,modalMessage:b?x.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Nn(x.sessionId||x.instanceId,g),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||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Nn(e.sessionId||e.instanceId,e.id),connectionState:a}),r}function bp(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function Oc(e,t){const r=bp(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Wc=[{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:"🏄"}],Hc=[{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:"🧩"}],Fc=[{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:"🟠"}],gp=Wc,yp=Hc,vp=Fc;function ms(...e){return ld(dd(e))}function wp({icon:e,title:t,subtitle:r,badge:n,actions:a,className:i}){return s.jsxs("div",{className:ms("dashboard-header",i),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.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&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function Uc({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(wp,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:ms("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}const ha="adhdev:themechange";function jp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function gs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ys(e){return e==="system"?jp():e}function zc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Pr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(ha,{detail:{preference:e,theme:t}}))}function kp(){const e=gs(),t=ys(e);zc(t),Pr(e,t)}function Ja(){const[e,t]=o.useState(gs),[r,n]=o.useState(()=>ys(gs()));o.useEffect(()=>{zc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const m=u.matches?"light":"dark";n(m),Pr("system",m)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const m=u.detail||{},d=m.preference,h=m.theme;t(d==="dark"||d==="light"||d==="system"?d:gs()),n(h==="dark"||h==="light"?h:ys(gs()))},l=u=>{if(u.key!=="theme")return;const m=gs(),d=ys(m);t(m),n(d)};return window.addEventListener(ha,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ha,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=ys(c);t(c),n(l);try{localStorage.setItem("theme",c)}catch{}Pr(c,l)},[]),i=o.useCallback(()=>{t(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=ys(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Pr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const zo={dark:"Dark",light:"Light",system:"System"};function Sp({collapsed:e}){const{preference:t,cycleTheme:r}=Ja(),n=t==="dark"?s.jsx(Qd,{size:16}):t==="light"?s.jsx(Jd,{size:16}):s.jsx(Zd,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${zo[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:zo[t]})]})}function Cn(e,t){return e?typeof e=="function"?e(t):e:null}function Np({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:i,footerActions:c,preMainContent:l,collapsedStorageKey:u="sidebar-collapsed"}){const[m,d]=o.useState(!1),[h,f]=o.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),w=()=>d(!0),k=()=>d(!1),p=()=>{f(y=>{const I=!y;try{localStorage.setItem(u,I?"1":"0")}catch{}return I})},S=o.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:w,closeMobileMenu:k,toggleCollapsed:p}),[h,m]),x=y=>`nav-item${y.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${y.className?` ${y.className}`:""}`,b=y=>s.jsxs("div",{className:x(y),id:`nav-${y.id}`,onClick:()=>{y.onSelect(),k()},title:h?y.title??(typeof y.label=="string"?y.label:void 0):y.title,children:[s.jsx("span",{className:"nav-icon",children:y.icon}),!h&&y.label]},y.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:w,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:k,onKeyDown:y=>y.key==="Escape"&&k()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:Cn(t,S)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:k,children:s.jsx(St,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(b)}),n.map(y=>s.jsxs("div",{className:y.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&y.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:y.title}):null,y.items.map(b)]},y.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(b),Cn(i,S),s.jsx(Sp,{collapsed:h}),Cn(c,S)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[l,e]})})]})}function Nt({title:e,icon:t,description:r,accentColor:n,className:a,children:i}){return s.jsxs("div",{className:ms("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Vc({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:ms("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Cp={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"},Tp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function kr({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:ms("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Cp[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Tp[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const Ap={online:"bg-green-500/10 text-green-400 border-green-500/30",idle:"bg-yellow-500/10 text-yellow-400 border-yellow-500/30",busy:"bg-orange-500/10 text-orange-400 border-orange-500/30",error:"bg-red-500/10 text-red-400 border-red-500/30",offline:"bg-gray-500/10 text-text-secondary border-gray-500/30"},Ip={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Mp({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:ms("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Ap[e],r),children:[s.jsx("span",{className:ms("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Ip[e])}),n]})}function Jt({label:e,description:t,checked:r,disabled:n,onChange:a,extra:i}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,s.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:[s.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))"}}),s.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 Rp({onPrefChange:e}){const[t,r]=tm(),[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 s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(sn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:c=>i("globalEnabled",c)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:c=>i("browserNotifications",c)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.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"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{sc().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"&&s.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"&&s.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."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(eu,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(rr,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Jr(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function Lp(e,t){const r=Jr(e),n=Jr(t);if(!r||!n)return e.localeCompare(t);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 Gc(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function Js(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||Lp(r,t)>=0)return!1;const n=Jr(r),a=Jr(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function _p(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Tn(e,t){return e instanceof Error?e.message:t}function Pp({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Vc,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(Ep,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function Vo({title:e,message:t,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 er.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:s.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:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.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"}),s.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 Dp(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...gp,...yp,...vp].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Ep({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var F,P;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[m,d]=o.useState(null),[h,f]=o.useState("idle"),[w,k]=o.useState(""),p=e.version||null,S=((F=e.machine)==null?void 0:F.platform)||((P=e.system)==null?void 0:P.platform)||"",x=Ct(e,{fallbackId:e.id}),b=S==="win32"?"🪟":S==="darwin"?"🍎":"🐧",y=t.filter(N=>N.daemonId===e.id&&N.transport==="cdp-page"),I=t.filter(N=>N.daemonId===e.id&&N.transport==="pty"),g=t.filter(N=>N.daemonId===e.id&&N.transport==="acp"),T=e.p2p,A=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const N=_p(await r(e.id,"daemon_upgrade",{}));N.alreadyLatest?(c("done"),u(`Already on v${N.version||"latest"}.`)):N.upgraded||N.success?(c("done"),u(`Upgrade to v${N.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(N.error||"Upgrade failed"))}catch(N){c("error"),u(Tn(N,"Connection lost during upgrade"))}}},j=async()=>{if(d(null),!!n){f("loading");try{await n(e.id),f("done"),k("Machine disconnected.")}catch(N){f("error"),k(Tn(N,"Failed to disconnect"))}}},v=async()=>{if(d(null),!!a){f("loading");try{await a(e.id),f("done"),k("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(N){f("error"),k(Tn(N,"Failed to revoke token"))}}},K="0.9.65",_=Gc(e,K),C=Js(e,K),H=y.length+I.length+g.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:b}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:x}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&s.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",p,!_&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&_&&s.jsx("button",{onClick:A,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${K}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${C?"↑ Update now":`↑ Update${` to v${K}`}`}`}),n&&s.jsx("button",{onClick:()=>d("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>d("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Mp,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[T&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${T.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${T.state==="connecting"||T.state==="new"?"animate-pulse":""}`,style:T.state==="connecting"||T.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",T.state==="connected"?"connected":T.state==="connecting"||T.state==="new"?"connecting...":T.state||"off"]}),T.peers!==void 0&&T.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",T.peers," peer",T.peers!==1?"s":"",")"]})]}),T&&H>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),H>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[y.map(N=>{const M=Dp(N.type),O=N.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:M.icon}),s.jsx("span",{children:M.name}),O!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${O?"bg-green-400":"animate-pulse"}`,style:O?void 0:{background:"var(--status-warning)"},title:O?"CDP connected":"CDP connecting..."})]},N.id)}),I.map(N=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:N.cliName||"CLI"})]},N.id)),g.map(N=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:N.cliName||"ACP"})]},N.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||h==="error"?"text-red-400":i==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:w||l})]}),m==="disconnect"&&s.jsx(Vo,{title:"🔌 Disconnect Machine",message:`Disconnect "${x}" 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:j,onCancel:()=>d(null)}),m==="revoke"&&s.jsx(Vo,{title:"⚠️ Remove Machine",message:`Remove "${x}" 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:()=>d(null)})]})}const $p=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Bp(){const{preference:e,setPreference:t}=Ja();return s.jsx("div",{className:"flex gap-2",children:$p.map(r=>s.jsxs("button",{onClick:()=>t(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:[s.jsx("span",{children:r.icon}),r.label]},r.id))})}function Kp(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function Op(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function An(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Go(e){const{r:t,g:r,b:n}=Op(e);return .2126*An(t)+.7152*An(r)+.0722*An(n)}function qo(e,t){const r=Go(e),n=Go(t),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function qc(e){const t=Kp(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return qo(t,r)>=qo(t,n)?r:n}const xa={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},ba={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},Wp=[{id:"midnight",name:"Midnight",description:"Classic violet theme",preview:{dark:{userBubble:"#8b5cf6",assistantBubble:"#18181d",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0f0f13",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#7c3aed",assistantBubble:"#ffffff",assistantBorder:"1px solid rgba(0,0,0,0.08)",containerBg:"#f0f1f5",textColor:"#52525b"}}},{id:"ember",name:"Ember",description:"Default landing-inspired amber theme",preview:{dark:{userBubble:"#f59e0b",assistantBubble:"#111726",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0a0e1a",textColor:"#9ca3af"},light:{userBubble:"#f59e0b",assistantBubble:"#fffaf4",assistantBorder:"1px solid rgba(146,64,14,0.10)",containerBg:"#fff8ee",textColor:"#6f6255"}}},{id:"aurora",name:"Aurora",description:"Pink accent theme",preview:{dark:{userBubble:"#ec4899",assistantBubble:"#1e1b2e",assistantBorder:"1px solid rgba(236,72,153,0.12)",containerBg:"#0f0d17",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#ec4899",assistantBubble:"#fef2f8",assistantBorder:"1px solid rgba(236,72,153,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}},{id:"honey",name:"Honey",description:"Warm yellow accents",preview:{dark:{userBubble:"#fbbf24",assistantBubble:"#1c1c1e",assistantBorder:"1px solid rgba(255,255,255,0.06)",containerBg:"#111113",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#fbbf24",assistantBubble:"#fffbeb",assistantBorder:"1px solid rgba(251,191,36,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}}],Yc="adhdev-chat-theme",Xc="adhdev-chat-theme-custom";function Dr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Yc)||"ember"}catch{return"ember"}}function _t(e){try{const t=localStorage.getItem(Xc);if(t){const r=JSON.parse(t);return{...e==="dark"?xa:ba,...r[e]}}}catch{}return e==="dark"?xa:ba}function Sr(e,t){try{localStorage.setItem(Xc,JSON.stringify({dark:e,light:t}))}catch{}}function At(e,t){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}, ${t})`}function Qr(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const Hp={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Qs(e,t){var a;const r=(a=Hp[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Qr(r,24)),n.style.setProperty("--accent-on-primary",qc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Qr(r,18)})`),n.style.setProperty("--border-accent",At(r,.35)),n.style.setProperty("--nav-active-bg",At(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${At(r,.06)}`)}function ns(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",At(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",At(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",At(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",At(e.borderSubtle,.5)),t.style.setProperty("--border-default",At(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Qr(e.accentColor,30)),t.style.setProperty("--accent-on-primary",qc(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Qr(e.accentColor,40)})`),t.style.setProperty("--border-accent",At(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",At(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${At(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${At(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function Qa(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(r=>e.style.removeProperty(r))}function Fp(e){try{localStorage.setItem(Yc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(_t(t))}else Qa(),Qs(e,as()?"dark":"light")}function Up(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Dr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=as()?"dark":"light";ns(_t(t))}else Qa(),Qs(e,as()?"dark":"light")}function as(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function gt({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,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 Ws({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.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}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function zp({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=o.useState(()=>_t(r));o.useEffect(()=>{a(_t(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const m={...u,[c]:l},h=_t(r==="dark"?"light":"dark");return r==="dark"?Sr(m,h):Sr(h,m),ns(m),t(m),m})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.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",s.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"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(Ws,{title:"App Background",children:[s.jsx(gt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(gt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(gt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Ws,{title:"App Text",children:[s.jsx(gt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(gt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(gt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Ws,{title:"Borders & Accent",children:[s.jsx(gt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(gt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(gt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Ws,{title:"Chat Bubbles",children:[s.jsx(gt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(gt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),s.jsx(gt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(gt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Ws,{title:"Chat Layout",children:[s.jsx(gt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(gt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(gt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.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)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?xa:ba,u=_t(e?"light":"dark");e?Sr(c,u):Sr(u,c),a(c),ns(c),t(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 Vp(){const[e,t]=o.useState(Dr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>_t("dark"));o.useEffect(()=>{n(as());const u=new MutationObserver(()=>{const h=as();n(h);const f=Dr();f==="custom"?ns(_t(h?"dark":"light")):Qs(f,h?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const h=as();n(h);const f=Dr();f==="custom"?ns(_t(h?"dark":"light")):Qs(f,h?"dark":"light")};return m.addEventListener("change",d),()=>{u.disconnect(),m.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ns(_t(r?"dark":"light")):(Qa(),Qs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(_t(r?"dark":"light"))},[r]);const c=u=>{t(u),Fp(u)},l=[...Wp,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const m=e===u.id,d=r?u.preview.dark:u.preview.light,h=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(u.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:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:h},children:"Fix the bug please"}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&s.jsx(zp,{dark:r,onColorsChange:u=>i(u)})]})}const Za="adhdev_mobileDashboardMode_v1",ga="adhdev:mobile-dashboard-mode-change";function eo(){try{return localStorage.getItem(Za)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Gp(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??eo())},r=a=>{const i=a.detail;t(i)},n=a=>{a.key&&a.key!==Za||t()};return window.addEventListener(ga,r),window.addEventListener("storage",n),()=>{window.removeEventListener(ga,r),window.removeEventListener("storage",n)}}function qp(e){try{localStorage.setItem(Za,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ga,{detail:e}))}function Yp(){const[e,t]=o.useState(!0);return o.useEffect(()=>{t(eo()==="chat")},[]),s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ft,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),qp(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const In=new Map,Yo=new Map;function Xp(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function Jp(e,t,r,n){return{...e||{},id:t,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 Jc(){const{sendCommand:e}=ft(),{injectEntries:t,getIdes:r}=tr();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Zm,c=Yo.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=In.get(n);if(l)return l;const u=(async()=>{const m=await e(n,"get_machine_runtime_stats"),d=Xp(m);if(!d)return;const h=r().find(w=>w.id===n),f=Jp(h,n,d.machine,d.timestamp||Date.now());t([f]),Yo.set(n,Date.now())})().finally(()=>{In.delete(n)});return In.set(n,u),u},[r,t,e])}function Qp(e,t,r){return{...e||{},id:t,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 Zp(e,t){const{sendData:r}=ft(),{injectEntries:n,getIdes:a}=tr(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>Ht.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const h=a().find(w=>w.id===u),f=Qp(h,u,d);n([f])}));return()=>{l.forEach(u=>u())}},[i,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function eh(e,t){const{sendData:r}=ft(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(t!=null&&t.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=Ht.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{l&&(clearTimeout(l),l=null),a(m.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},rf):c(!1),()=>{l&&clearTimeout(l),u()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function th(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Qc(e){const{sendData:t}=ft(),[r,n]=o.useState({});return o.useEffect(()=>{const a=th(e);if(!a||!e.sessionId||!t){n({});return}const i=Ht.subscribe({sendData:t},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}),Ss.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,t]),r}const Zc="adhdev_hiddenTabs";function sh(){try{const e=localStorage.getItem(Zc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function xs(e){try{localStorage.setItem(Zc,JSON.stringify([...e]))}catch{}}function Mn(e){return Wa(e)}function to(e,t){return ks(t).some(r=>e.has(r))}function rh(){const[e,t]=o.useState(sh),r=o.useCallback(m=>{const d=Mn(m);t(h=>{const f=new Set(h);return f.has(d)?f.delete(d):f.add(d),xs(f),f})},[]),n=o.useCallback(m=>{const d=Mn(m);t(h=>{if(h.has(d))return h;const f=new Set(h);return f.add(d),xs(f),f})},[]),a=o.useCallback(m=>{const d=Mn(m);t(h=>{if(!h.has(d))return h;const f=new Set(h);return f.delete(d),xs(f),f})},[]),i=o.useCallback(()=>{t(m=>{if(m.size===0)return m;const d=new Set;return xs(d),d})},[]),c=o.useCallback((m,d)=>{t(h=>{const f=new Set(h);for(const w of d)f.add(w);return xs(f),f})},[]),l=o.useCallback((m,d)=>{t(h=>{const f=new Set(h);for(const w of d)f.delete(w);return xs(f),f})},[]),u=o.useCallback(m=>to(e,m),[e]);return{hiddenTabs:e,toggleTarget:r,hideTarget:n,showTarget:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function el(e){return e instanceof Error?e.message:String(e||"")}function tl(e){const t=el(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function sl(e){const t=el(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function rl({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!et(e)||Xe(e))return;const i=Ds(e);if(i===t)return;const c=e.sessionId;c&&a(l=>({...l,[c]:t}));try{await n(hs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Bt(e),mode:t})}catch(l){const u=sl(l);c&&!u&&a(m=>{const d={...m};return i===nl(r,c)?delete d[c]:d[c]=i,d}),tl(l)?console.warn(u?"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 Xo(e,t){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=t[r];return!n||e.mode===n?e:{...e,mode:n}}function nh(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const i=Xo(a,t),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>Xo(u,t)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function nl(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function ah(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))nl(t,a)===i&&(delete n[a],r=!0);return r?n:e}function oh({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{sc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Rc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return am(a),o.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),m={};for(const[d,h]of Object.entries(l))u-h<5e3&&(m[d]=h);return Object.keys(m).length===Object.keys(l).length?l:m})},5500);return()=>clearTimeout(c)},[t,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(m=>m.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function ih(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){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 Rn(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function ch(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Jo(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?ch(Ns(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.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 lh(e){const t=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||""),Jo(e.activeChat),...t.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||""),Jo(r.activeChat)].join(":"))].join("|")}function dh(e,t){const r=Date.now();return e.map(n=>{const a=t[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function uh(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const i of ks({routeId:n.routeId}))r.set(i,a);for(const i of ks({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of ks({tabKey:n.tabKey}))r.set(i,n)}return r}function mh(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function fh(e){const t=mh(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=Ns(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function ph({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=o.useMemo(()=>ih(e),[e]),i=o.useMemo(()=>Bc(e),[e]),c=o.useRef([]),l=o.useRef([]),u=o.useRef([]),m=o.useRef(new Map),d=o.useRef(new Map),h=o.useMemo(()=>{const I=new Map,g=[];for(const v of a){const{connectionState:K="new",machineName:_}=Kc(v,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),C=lh(v),H=m.current.get(v.id);if(H&&H.ide===v&&H.sourceSignature===C&&H.connectionState===K&&H.machineName===_){I.set(v.id,H),g.push(...H.conversations);continue}const F=Xa(v,{machineNames:i,connectionStates:t,defaultConnectionState:"new"}),P={ide:v,sourceSignature:C,connectionState:K,machineName:_,conversations:F};I.set(v.id,P),g.push(...F)}m.current=I;const T=new Map,A=v=>{const K=fh(v),_=d.current.get(v.tabKey);if(_&&_.signature===K)return T.set(v.tabKey,_),_.timestamp;const C={signature:K,timestamp:bc(v)||(_==null?void 0:_.timestamp)||0};return T.set(v.tabKey,C),C.timestamp},j=[...g].sort((v,K)=>gc(v,K,A));return d.current=T,j},[a,t,i]),f=o.useMemo(()=>{const I=dh(h,r);return Rn(c.current,I)?c.current:(c.current=I,I)},[h,r]),w=o.useMemo(()=>{const I=new Map,g=Array.from(new Set(f.map(T=>T.routeId)));for(const T of g){const A=Pt(f,T);A&&I.set(T,A)}return I},[f]),k=o.useMemo(()=>{const I=new Map;for(const g of f){const T=w.get(g.routeId),A=g.streamSource==="native"&&T?T:g;for(const j of ks({providerSessionId:g.providerSessionId,sessionId:g.sessionId}))I.set(j,A)}return I},[f,w]),p=o.useMemo(()=>uh(f,w),[f,w]),S=o.useCallback(I=>{if(I)return k.get(I)},[k]),x=o.useCallback(I=>{if(I)return p.get(I)},[p]),b=o.useMemo(()=>{const I=f.filter(g=>!to(n,g));return Rn(l.current,I)?l.current:(l.current=I,I)},[f,n]),y=o.useMemo(()=>{const I=b.map(g=>g.tabKey);return Rn(u.current,I)?u.current:(u.current=I,I)},[b]);return{chatIdes:a,conversations:f,visibleConversations:b,visibleTabKeys:y,resolveConversationBySessionId:S,resolveConversationByTarget:x}}function hh({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),i=o.useMemo(()=>{var l;return!e||!t?null:((l=r(t))==null?void 0:l.tabKey)??null},[e,r,t]),c=o.useCallback(()=>{t&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function xh({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){o.useEffect(()=>{rt.setIdes(e)},[e]),o.useEffect(()=>{rt.setResolveAction((a,i,c)=>{t(a,i,c).catch(()=>{})})},[t]),o.useEffect(()=>{const a=rt.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(u=>u.id!==i.id)),c)});return()=>{a()}},[r]),o.useEffect(()=>{const a=Ac.on("status_event",i=>{rt.handleRawEvent(i,"ws")});return()=>{a()}},[]),o.useEffect(()=>{var i;const a=c=>{var p;const l=c.data;if((l==null?void 0:l.type)!=="notification_action"||typeof l.action!="string"||!l.action.startsWith("approval_")||!(l.daemonId||l.targetSessionId||l.targetKey))return;const u=l.targetSessionId||l.targetKey||l.daemonId,m=n(u),d=(m==null?void 0:m.routeId)||l.daemonId;if(!d)return;const h=Number(l.buttonIndex),f=l.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[h])||"Approve",w=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(w);t(d,"resolve_action",{action:k?"approve":"reject",button:f,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...l.targetSessionId&&{targetSessionId:l.targetSessionId}}).catch(S=>console.error("[SW Action] approval failed:",S))};return(i=navigator.serviceWorker)==null||i.addEventListener("message",a),()=>{var c;return(c=navigator.serviceWorker)==null?void 0:c.removeEventListener("message",a)}},[n,t])}const bh="adhdev_dashboardLayout_v1",gh="adhdev_dashboardDockview_v1",yh="adhdev_dashboardDockviewHiddenRestore_v1",Hs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function so(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function vh(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function al(e){return`${bh}:${e}`}function wh(e){const t=al(e);return so(t,null)}function jh(e,t){try{const r=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=al(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function ol(e){return`${gh}:${e}`}function kh(e){const t=ol(e);return so(t,null)}function Sh(e,t){try{const r=ol(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function il(e){return`${yh}:${e}`}function Nh(e){const t=il(e);return so(t,{})}function Ch(e,t){try{const r=il(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Th(){return{groupAssignments:[...Hs.groupAssignments],focusedGroup:Hs.focusedGroup,groupActiveTabIds:{...Hs.groupActiveTabIds},groupTabOrders:{...Hs.groupTabOrders},groupSizes:[...Hs.groupSizes]}}function Ah(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function Ih(){const[e]=o.useState(()=>vh(typeof window<"u"?window.innerWidth:1280)),[t,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[m,d]=o.useState([]),[h,f]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,k]=o.useState(!1),p=o.useCallback(()=>{if(w)return;const v=wh(e)??Th();r(new Map(v.groupAssignments)),a(v.focusedGroup),c(v.groupActiveTabIds),u(v.groupTabOrders),d(v.groupSizes),k(!0)},[w,e]);o.useEffect(()=>{w&&jh(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:m})},[w,e,t,n,i,l,m]),o.useEffect(()=>{const v=window.matchMedia("(max-width: 767px)"),K=_=>f(_.matches);return v.addEventListener("change",K),()=>v.removeEventListener("change",K)},[]);const S=o.useCallback(v=>{r(v)},[]),x=o.useCallback(v=>{a(v)},[]),b=o.useCallback(v=>{c(v)},[]),y=o.useCallback(v=>{u(v)},[]),I=o.useCallback(v=>{d(v)},[]),g=o.useCallback(v=>{x(v)},[x]),T=o.useCallback((v,K)=>{c(_=>(_[v]??null)===(K??null)?_:{..._,[v]:K})},[]),A=o.useCallback((v,K)=>{u(_=>{const C=_[v];return Ah(C,K)?_:{..._,[v]:K}})},[]),j=o.useCallback((v,K)=>{const _=K.get(v)??0;return T(_,v),g(_),_},[g,T]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:S,focusedGroup:n,updateFocusedGroup:x,focusGroup:g,groupActiveTabIds:i,updateGroupActiveTabIds:b,setGroupActiveTab:T,groupTabOrders:l,updateGroupTabOrders:y,setGroupTabOrder:A,groupSizes:m,updateGroupSizes:I,isMobile:h,hasHydratedStoredLayout:w,hydrateStoredLayout:p,focusConversationTab:j}}function Mh(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Oa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Rh({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,focusConversationTab:c,setSearchParams:l,historyModalOpen:u,activeConv:m,isRefreshingHistory:d,ides:h,handleRefreshHistory:f}){const w=o.useRef(!1),k=o.useRef(!1),p=o.useRef(null),S=o.useRef(!1);o.useEffect(()=>{if(!e||w.current||t.length===0)return;if(!a){i();return}const x=r(e);x&&(c(x.tabKey,n),w.current=!0,k.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),l(b=>{const y=new URLSearchParams(b);return y.delete("activeTab"),y},{replace:!0}))},[e,t,r,n,a,i,c,l]),o.useEffect(()=>{if(!(k.current||a)&&t.length!==0){if(!e){i(),k.current=!0;return}if(w.current){k.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(k.current||a)&&(i(),k.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,i]),o.useEffect(()=>{if(!u){S.current=!1;return}if(!m||S.current||d)return;const x=h.find(b=>b.id===m.routeId);x&&(!x.chats||x.chats.length===0||Mh(x.chats,m))&&(S.current=!0,f())},[u,m,d,h,f])}function Ln(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Oa(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function cl({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:i}){const[c,l]=o.useState(!1),[u,m]=o.useState(!1),d=o.useCallback(async k=>{try{await e("standalone","launch_ide",{ideType:k,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=o.useCallback(async(k,p)=>{try{const S=k||(t==null?void 0:t.daemonId)||"",x=await e(S,"switch_chat",{id:p,sessionId:p,...Zt(t)}),b=x==null?void 0:x.result;if((x==null?void 0:x.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Ks(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Ks(a,`⚠️ Switch error: ${b}`):Ks(a,"⚠️ Session switch failed")}catch(S){console.error("Switch failed",S),Ks(a,`❌ Switch failed: ${S.message||"connection error"}`)}},[t,e,a]),f=o.useCallback(async()=>{if(!(!t||c)){l(!0);try{const k=As(t);await e(k,"new_chat",{...Zt(t)}),i(p=>({...p,[t.tabKey]:Date.now()}))}catch(k){console.error("New chat failed",k)}finally{l(!1)}}},[t,c,e,i]),w=o.useCallback(async()=>{var k,p;if(!(!t||u)){m(!0);try{const S=As(t),x=async()=>e(S,"list_chats",{forceExpand:!0,...Zt(t)});let b=await x(),y=(b==null?void 0:b.chats)||((k=b==null?void 0:b.result)==null?void 0:k.chats);Ln(y,t)&&(await new Promise(I=>setTimeout(I,450)),b=await x(),y=(b==null?void 0:b.chats)||((p=b==null?void 0:b.result)==null?void 0:p.chats)),b!=null&&b.success&&Array.isArray(y)&&(n(t.routeId,y),Ln(y,t)&&!Ln(r,t)&&Ks(a,"⚠️ History dialog did not fully open — try once more"))}catch(S){console.error("Refresh history failed",S)}finally{m(!1)}}},[t,r,u,e,n,a]);return{isCreatingChat:c,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:h,handleNewChat:f,handleRefreshHistory:w}}function Lh(e,t){if(e.size!==t.size)return!1;for(const[r,n]of e)if(t.get(r)!==n)return!1;return!0}function _h(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function Qo(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function Nr(e,t){const r=new Set(t),n=t.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function Zo(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=t[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Ph(e,t,r){if(t.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...t].reverse().find(a=>a<e)??t[0];return r[n]??0}function Dh(e,t,r){if(t.length<=1)return[];const n=t.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===t.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 ei(e,t){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=t?i+1:i]=a}return r}function ti(e){return Array(e).fill(100/e)}function Eh({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:i,updateGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:m}){const d=o.useRef(null),h=o.useMemo(()=>Nr(e,m),[e,m]),f=h.assignments,w=o.useMemo(()=>l?1:h.groupCount,[h.groupCount,l]),k=w>1,p=o.useCallback((g,T)=>{t(A=>{const j=new Map(Nr(A,m).assignments);return T===0?j.delete(g):j.set(g,T),j}),n(A=>({...A,[T]:g})),r(T)},[t,m,n,r]),S=o.useCallback(g=>{t(T=>{const A=Nr(T,m).assignments,j=new Map;for(const[v,K]of A)K!==g&&(K>g?j.set(v,K-1):j.set(v,K));return j}),c(T=>{if(T.length<=1)return[];const A=[...T];A.splice(g,1);const j=A.reduce((v,K)=>v+K,0);return j>0?A.map(v=>v/j*100):[]}),r(0)},[t,m,c,r]),x=o.useCallback((g,T)=>{T.preventDefault();const A=d.current;if(!A)return;const j=T.clientX,v=A.offsetWidth,K=i.length===w?[...i]:ti(w),_=H=>{const P=(H.clientX-j)/v*100,N=[...K];N[g]=Math.max(15,K[g]+P),N[g+1]=Math.max(15,K[g+1]-P),c(N)},C=()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",C),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",C)},[i,w,c]),b=o.useCallback((g,T,A)=>{if(w>=4)return;const j=A==="left"?T:T+1;t(v=>{const K=Nr(v,m).assignments,_=new Map;for(const C of u){const H=K.get(C.tabKey)??0,F=H>=j?H+1:H;F>0&&_.set(C.tabKey,F)}return j>0&&_.set(g,j),_}),c(v=>{const K=v.length===w?[...v]:ti(w),_=K[T]??100/w,C=Math.max(15,_/2),H=Math.max(15,_/2),F=[...K];F[T]=C,F.splice(j,0,H);const P=F.reduce((N,M)=>N+M,0);return F.map(N=>N/P*100)}),n(v=>{const K=ei(v,j);return K[j]=g,K}),a(v=>{const K=ei(v,j);return K[j]=[g],K}),r(j)},[w,t,m,u,c,n,a,r]);o.useEffect(()=>{Lh(e,f)||t(f)},[e,f,t]),o.useEffect(()=>{const{mapping:g,usedGroups:T}=h;n(A=>{const j=Zo(A,g);return Qo(A,j)?A:j}),a(A=>{const j=Zo(A,g);return Qo(A,j)?A:j}),r(A=>{const j=l?0:Ph(A,T,g);return A===j?A:j}),c(A=>{const j=l?[]:Dh(A,T,h.groupCount);return _h(A,j)?A:j})},[h,l,n,a,r,c]);const y=o.useMemo(()=>{const g=Array.from({length:w},()=>[]);for(const T of u){const A=f.get(T.tabKey)??0,j=Math.min(A,w-1);g[j].push(T)}return g},[u,f,w]),I=o.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:w,isSplitMode:k,groupedConvs:y,moveTabToGroup:p,closeGroup:S,handleResizeStart:x,splitTabRelative:b,clearAllSplits:I}}function $h({ides:e,sendDaemonCommand:t}){const r="0.9.65",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Gc(d,r)).sort((d,h)=>Number(Js(h,r))-Number(Js(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>Js(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),m=o.useCallback(async d=>{var h,f;u(w=>({...w,[d]:"upgrading"}));try{const w=await t(d,"daemon_upgrade",{});(h=w==null?void 0:w.result)!=null&&h.upgraded||(f=w==null?void 0:w.result)!=null&&f.success?u(k=>({...k,[d]:"done"})):u(k=>({...k,[d]:"error"}))}catch{u(w=>({...w,[d]:"error"}))}},[t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:m}}const ll=80;function Er(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Bh(e){return{...e,createdAt:Er(e.createdAt),updatedAt:Er(e.updatedAt,e.createdAt),lastEventAt:Er(e.lastEventAt,e.updatedAt||e.createdAt)}}function Kh(e){const t=Wa(e);return t==="unknown:"?e.id:t}function Oh(e){return[e.type,xc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Wh(e,t=ll){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Kh(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,t))}function Hh(e,t){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?t.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=nn(a,t),l=c.inboxBucket==="needs_attention"?"needs_attention":c.inboxBucket==="task_complete"&&c.unread?"task_complete":null;if(!l)continue;const u=Er(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),m=Oh({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(Bh({id:m,dedupKey:m,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:ic(a),preview:Mm(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return Wh(n)}function Fh(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function Uh(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=ll}=e,a=o.useMemo(()=>Hh(t,r).slice(0,Math.max(0,n)),[t,r,n]),i=o.useMemo(()=>Fh(a),[a]);return{notifications:a,unreadCount:i}}function zh({notifications:e,sendDaemonCommand:t}){const r=o.useCallback(i=>{const c=e.find(u=>u.id===i),l=Math.max(Date.now(),(c==null?void 0:c.updatedAt)||0);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_session_seen",{sessionId:c.sessionId,seenAt:l}).catch(()=>{})},[e,t]),n=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"mark_notification_unread",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]),a=o.useCallback(i=>{const c=e.find(l=>l.id===i);c!=null&&c.sessionId&&t(c.machineId||c.routeId,"delete_notification",{sessionId:c.sessionId,notificationId:c.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}function ln(...e){const t=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();t.has(c)||(t.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 Vh(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function dn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=Vh(r);if(n)return n}return"C:\\"}for(const r of t){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function Gh(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const r=t.includes("\\")?"\\":"/",n=t.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 qh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function un(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=qh(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,d)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${d}`:m==="/"||m==="\\"?`${c}${d}`:`${m.replace(/[\\/]+$/,"")}${c}${d}`,u=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,d)=>m.name.localeCompare(d.name)):[];return{path:i,directories:u}}function Yh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function si(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Xh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Jh({ides:e,conversations:t,onOpenSession:r}){const[n,a]=o.useState(null),i=o.useCallback(c=>{a(c)},[]);return o.useEffect(()=>{if(!n)return;const c=si(n.workspacePath),l=e.find(m=>{var k,p,S,x;if(!m||m.type==="adhdev-daemon"||Yh(m.daemonId||m.id)!==n.machineId||(nr(m)?"cli":ws(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 b=si(m.workspace||m.runtimeWorkspaceLabel);return b?b===c:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((x=(S=(p=(k=m.activeChat)==null?void 0:k.messages)==null?void 0:p.at)==null?void 0:S.call(p,-1))==null?void 0:x.timestamp)||0)>=n.startedAt-5e3});if(!l)return;const u=yc({entrySessionId:l.sessionId,entryInstanceId:l.instanceId,entryRouteId:l.id,conversations:t});u&&(a(null),r(u))},[t,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 Qh({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:i}){const c=o.useCallback(async(f,w)=>un(e,f,w),[e]),l=o.useCallback(async(f,w)=>{if(!w.trim())return{ok:!1,error:"Choose a workspace path first."};try{const k=await e(f,"workspace_add",{path:w.trim()});return k!=null&&k.success?{ok:!0}:{ok:!1,error:(k==null?void 0:k.error)||"Could not save workspace"}}catch(k){return{ok:!1,error:k instanceof Error?k.message:"Could not save workspace"}}},[e]),u=o.useCallback(async(f,w,k)=>{var p;try{const S={ideType:w,enableCdp:!0};(p=k==null?void 0:k.workspacePath)!=null&&p.trim()&&(S.workspace=k.workspacePath.trim());const x=await e(f,"launch_ide",S);return!(x!=null&&x.success)&&(x==null?void 0:x.success)!==void 0?{ok:!1,error:(x==null?void 0:x.error)||"Could not launch IDE"}:(t({machineId:f,kind:"ide",providerType:w,workspacePath:(k==null?void 0:k.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not launch IDE"}}},[e,t]),m=o.useCallback(async(f,w,k,p)=>{var x,b,y;const S=Date.now();try{const I={cliType:k};(x=p==null?void 0:p.workspacePath)!=null&&x.trim()?I.dir=p.workspacePath.trim():p!=null&&p.workspaceId&&(I.workspaceId=p.workspaceId),(b=p==null?void 0:p.resumeSessionId)!=null&&b.trim()&&(I.resumeSessionId=p.resumeSessionId.trim()),Array.isArray(p==null?void 0:p.cliArgs)&&p.cliArgs.length>0&&(I.cliArgs=p.cliArgs),(y=p==null?void 0:p.initialModel)!=null&&y.trim()&&(I.initialModel=p.initialModel.trim());const g=await e(f,"launch_cli",I),T=(g==null?void 0:g.result)||g,A=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);return g!=null&&g.success&&A?(r(A),{ok:!0}):g!=null&&g.success?(t({machineId:f,kind:w,providerType:k,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:S}),{ok:!0}):{ok:!1,error:(g==null?void 0:g.error)||(T==null?void 0:T.error)||`Could not launch ${w.toUpperCase()} session`}}catch(I){return Xh(I)?(t({machineId:f,kind:w,providerType:k,workspacePath:(p==null?void 0:p.workspacePath)||null,resumeSessionId:(p==null?void 0:p.resumeSessionId)||null,startedAt:S}),{ok:!0}):{ok:!1,error:I instanceof Error?I.message:`Could not launch ${w.toUpperCase()} session`}}},[r,e,t]),d=o.useCallback(async(f,w)=>{if(!f||!w)return[];try{const k=await e(f,"list_saved_sessions",{providerType:w,kind:"cli",limit:30}),p=(k==null?void 0:k.result)??k;return Array.isArray(p==null?void 0:p.sessions)?p.sessions:[]}catch(k){return console.error("List saved sessions failed",k),[]}},[e]),h=o.useCallback(async f=>{await rl({conversation:n,mode:f,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:i})},[n,a,e,i]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:l,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineSavedSessions:d,setActiveCliViewMode:h}}function Zh(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 ex(e,t,r=Date.now()){return!e||!Zh(t)?null:{tabKey:e,nonce:r}}function tx({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:i,setSearchParams:c}){const[l,u]=o.useState(null),[m,d]=o.useState(null),h=o.useMemo(()=>{var S,x;if(!e){if(l){const b=t.find(y=>y.tabKey===l);if(b)return b}return r[0]}const p=n[a];if(p){const b=t.find(y=>y.tabKey===p);if(b)return b}return((S=i[a])==null?void 0:S[0])||((x=i[0])==null?void 0:x[0])},[t,l,a,n,i,e,r]),f=o.useCallback(p=>{u(p)},[]),w=o.useCallback(p=>{u(p.tabKey),c(S=>{const x=new URLSearchParams(S),b=Lm(p);return b?x.set("activeTab",b):x.delete("activeTab"),x},{replace:!0})},[c]),k=o.useCallback((p,S)=>{const x=ex(p,S);x&&d(x)},[]);return{activeConv:h,openDesktopConversation:w,requestScrollToBottom:k,scrollToBottomRequest:m,setDesktopActiveTab:f}}function sx(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===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 rx(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:i,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function nx({activeConv:e,isMobile:t,liveSessionInboxState:r,sendDaemonCommand:n}){const a=o.useRef(null),i=o.useRef(null),c=o.useRef(null),l=o.useRef(null),u=o.useRef(null);o.useEffect(()=>{const m=()=>{c.current&&(clearTimeout(c.current),c.current=null),l.current&&(clearTimeout(l.current),l.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),i.current=null};if(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const d=zr(e,r),h=rx({tabKey:e.tabKey,historySessionId:lr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:es(e),liveState:d}),f=h.autoReadKey,w=sx({autoReadKey:f,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:i.current});if(!h.shouldMarkSeen){w.shouldCancelPending&&m(),a.current=f;return}if(!w.shouldSchedule)return;w.shouldCancelPending&&m();const k=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,i.current=null,c.current=null,l.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const S=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:S,completionMarker:h.completionMarker}).catch(()=>{})};if(i.current=w.nextPendingKey,document.visibilityState==="visible"){c.current=setTimeout(k,1500);const S=()=>{document.visibilityState!=="visible"&&c.current&&(clearTimeout(c.current),c.current=null)};u.current=S,document.addEventListener("visibilitychange",S);return}const p=()=>{document.visibilityState==="visible"&&(l.current&&clearTimeout(l.current),l.current=setTimeout(k,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),o.useEffect(()=>()=>{c.current&&clearTimeout(c.current),l.current&&clearTimeout(l.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function _n(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function ax({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:i,setToasts:c,setClearedTabs:l,setSearchParams:u}){var M;const[m,d]=o.useState(!1),[h,f]=o.useState([]),[w,k]=o.useState(()=>xt()),[p,S]=o.useState(!1),[x,b]=o.useState(null),y=o.useRef(null),I=o.useMemo(()=>r||t||e,[e,r,t]),g=!!I&&et(I)&&!Xe(I),T=o.useMemo(()=>{if(!I||!g)return null;const O=I.daemonId||I.routeId||"",$=Bt(I),E=_n(I);return`${O}:${$}:${I.providerSessionId||""}:${E}`},[I,g]),A=o.useMemo(()=>!I||!g?"":_n(I),[I,g]),{isCreatingChat:j,isRefreshingHistory:v,handleSwitchSession:K,handleNewChat:_,handleRefreshHistory:C}=cl({sendDaemonCommand:a,activeConv:I,chats:(M=n.find(O=>O.id===(I==null?void 0:I.routeId)))==null?void 0:M.chats,updateRouteChats:i,setToasts:c,setClearedTabs:l}),H=o.useCallback(()=>{d(!0)},[]),F=o.useCallback(()=>{d(!1)},[]),P=o.useCallback(async()=>{if(!(!I||!g||p)){S(!0);try{const O=I.daemonId||I.routeId,$=Bt(I),E=_n(I),U=await a(O,"list_saved_sessions",{agentType:$,providerType:$,kind:"cli",limit:50,...I.providerSessionId?{providerSessionId:I.providerSessionId}:{},...E?{workspace:E}:{}}),X=(U==null?void 0:U.result)??U;f(Array.isArray(X==null?void 0:X.sessions)?X.sessions:[])}catch(O){console.error("Refresh saved sessions failed",O),f([])}finally{S(!1)}}},[I,p,g,a]);o.useEffect(()=>{if(!m){y.current=null;return}if(!g){y.current=null,f([]),S(!1);return}!T||p||y.current!==T&&(y.current=T,P())},[P,m,p,g,T]);const N=o.useCallback(async O=>{if(!I||!g||!O.providerSessionId||!O.workspace)return;const $=I.daemonId||I.routeId,E=Bt(I);try{b(O.providerSessionId);const U=await a($,"launch_cli",{cliType:E,dir:O.workspace,resumeSessionId:O.providerSessionId,initialModel:ec(O.summaryMetadata,"model",{preferShortValue:!0})||void 0}),X=(U==null?void 0:U.result)??U,he=typeof(X==null?void 0:X.sessionId)=="string"?X.sessionId:typeof(X==null?void 0:X.id)=="string"?X.id:"";he&&u(ce=>{const te=new URLSearchParams(ce);return te.set("activeTab",he),te},{replace:!0}),F()}catch(U){console.error("Resume saved session failed",U)}finally{b(null)}},[F,I,g,a,u]);return{historyModalOpen:m,openHistoryModal:H,closeHistoryModal:F,historyTargetConv:I,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:j,isHistoryRefreshingHistory:v,handleHistorySwitchSession:K,handleHistoryNewChat:_,handleHistoryRefresh:C,savedHistorySessions:h,savedHistoryFilters:w,setSavedHistoryFilters:k,missingWorkspaceResumePath:A,isSavedHistoryLoading:p,resumingSavedHistorySessionId:x,handleRefreshSavedHistory:P,handleResumeSavedHistorySession:N}}function ox({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,m]=o.useState(null),[d,h]=o.useState(null),f=o.useMemo(()=>{if(e||!n)return null;const x=l(n);return x&&!et(x)&&!Xe(x)?x:null},[e,n,l]),w=o.useMemo(()=>{const x=u==null?void 0:u.routeId;if(!x)return null;const b=u!=null&&u.tabKey?i.find(y=>y.tabKey===u.tabKey):a?i.find(y=>y.tabKey===a):null;return(b==null?void 0:b.routeId)===x?b:Pt(i,x)},[i,u,a]),k=o.useMemo(()=>{if(w)return c.find(x=>x.id===w.routeId)},[c,w]);o.useEffect(()=>{f&&(m({routeId:f.routeId,tabKey:Ro(f)}),h(f),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,f]);const p=o.useCallback(x=>{x&&(m({routeId:x.routeId,tabKey:Ro(x)}),h(x))},[]),S=o.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:k,remoteDialogActiveConv:d,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:S}}function ix({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l,activeConv:u,sendDaemonCommand:m}){const{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:w,openRemoteDialog:k,closeRemoteDialog:p}=ox({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}),[S,x]=o.useState(!1),[b,y]=o.useState(null),I=o.useCallback(async A=>{const j=A||u;!j||!et(j)&&!Xe(j)||(y(j),x(!0))},[u]),g=o.useCallback(()=>{x(!1),y(null)},[]),T=o.useCallback(async A=>{const j=b||u;if(!j||!et(j)&&!Xe(j)){g();return}x(!1);try{const v=Bt(j),K=j.routeId||j.daemonId||"";await m(K,"stop_cli",{cliType:v,targetSessionId:j.sessionId,mode:A})}catch(v){console.error("Stop CLI failed:",v)}finally{y(null)}},[u,g,b,m]);return{remoteDialogConv:d,remoteDialogIdeEntry:h,remoteDialogActiveConv:f,setRemoteDialogActiveConv:w,openRemoteDialog:k,closeRemoteDialog:p,cliStopDialogOpen:S,cliStopTargetConv:b,requestCliStop:I,cancelCliStop:g,confirmCliStop:T}}function Pn(e,t=!0){return(e??!0)&&t}const ro=o.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d=null,handleFocusAgent:h,isFocusingAgent:f,actionLogs:w,userName:k,scrollToBottomRequestNonce:p,isInputActive:S=!0,isVisible:x=!0}){const b=n,y=!n,I=Pn(x,b),g=Pn(x,y),T=Pn(x),A=Qc(t),j=A.status||A.modalMessage||A.modalButtons?{...t,...A.status?{status:A.status}:{},...A.modalMessage!==void 0?{modalMessage:A.modalMessage}:{},...A.modalButtons!==void 0?{modalButtons:A.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(Xi,{activeConv:j,onModalButton:c}),j.transport!=="pty"&&j.transport!=="acp"&&j.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.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:[s.jsx("span",{className:"text-sm",children:s.jsx(sr,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.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,j.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:b?"visible":"hidden",pointerEvents:b?"auto":"none"},children:s.jsx(zf,{activeConv:j,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,isVisible:I,isInputActive:S&&I})}),s.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:s.jsx(pa,{activeConv:j,ideEntry:a,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:w,userName:k,scrollToBottomRequestNonce:p,isInputActive:S&&g,isVisible:g})})]}):s.jsx(pa,{activeConv:j,ideEntry:a,handleSendChat:u,isSendingChat:m,sendFeedbackMessage:d,handleFocusAgent:h,isFocusingAgent:f,actionLogs:w,userName:k,scrollToBottomRequestNonce:p,isInputActive:S&&T,isVisible:T})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function cx({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:m,onOpenNativeConversation:d,onOpenMachine:h,onOpenHistory:f,onOpenRemote:w,onStopCli:k,cliViewMode:p,onSetCliViewMode:S,handleSendChat:x,handleFocusAgent:b,handleModalButton:y,handleRelaunch:I}){const g=o.useRef(null),T=et(e)&&!t,A=T&&p==="terminal",j=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${j} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.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:s.jsx(Ca,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ot(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(vc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>h(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[T&&p&&s.jsx(Ua,{mode:p,onChange:S,compact:!0}),T&&k&&s.jsx("button",{onClick:()=>{k(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:s.jsx(St,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Ta,{size:14})}),!t&&!T&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:s.jsx(Tt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(ro,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:n,terminalRef:g,handleModalButton:y,handleRelaunch:I,handleSendChat:x,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:b,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const Dn={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 lx(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function dl(){const[e,t]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{t(lx())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Dn[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return s.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:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.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:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.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:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.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"}),s.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"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Dn[c].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Dn[c].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function ul({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:Ft}];return s.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:s.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 s.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:()=>t(n),type:"button","aria-pressed":c,children:[s.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:s.jsx(i,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function Cr({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function bs({children:e,className:t=""}){return s.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)] ${t}`,children:e})}function Fs({icon:e,title:t,subtitle:r,children:n}){return s.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:[s.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}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function dx({conversation:e,onCancel:t,onConfirm:r}){const n=ot(e),a=us(e);return s.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:[s.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.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:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.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."})]}),s.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:t,"aria-label":"Cancel hide chat",children:s.jsx(St,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.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:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function Tr({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onCollectChatDebugBundle:i}){const c=t==="needs_attention"||t==="task_complete",l=t==="working",u=t==="earlier",m=t==="task_complete",{isReconnecting:d,isConnecting:h}=Ps(e.conversation),f=ot(e.conversation),w=us(e.conversation),k=Mc(e.conversation,{requiresAction:t==="needs_attention"}),p=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%)]":u?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",S=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":u?"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",x=u?"text-text-secondary":"text-text-primary",b=u?"text-text-muted":"text-text-secondary",y=u?"text-text-secondary opacity-80":"text-text-muted",I=u?"text-text-muted opacity-80":"text-text-muted",g=!l&&!m,T="text-[color:var(--status-warning)]",A=j=>{if(!i)return;j.preventDefault(),j.stopPropagation();const v=i==null?void 0:i(e.conversation);Promise.resolve(v).catch(K=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",K)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${p}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[c||l?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${S}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(f)}),a&&s.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:j=>{j.preventDefault(),j.stopPropagation(),a()},"aria-label":`Hide ${f}`,title:"Hide conversation",children:[s.jsx(Aa,{size:11}),s.jsx("span",{children:"Hide"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:A,type:"button",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${x}`,children:f}),g&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${I}`,children:Yi(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[s.jsx("span",{className:"truncate",children:w}),s.jsx(Is,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),d?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${T} animate-pulse`,children:"Reconnecting…"})]}):h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):k==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:T,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,children:e.preview})]}),c&&!m&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),m&&s.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&&s.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 ri({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.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 ux({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,actionLogs:u,sendDaemonCommand:m,onOpenConversation:d,onShowAllHidden:h,onHideConversation:f,onOpenNewSession:w,onOpenMachine:k,onOpenSettings:p,onSectionChange:S,wsStatus:x="connected",isStandalone:b=!1,onCollectChatDebugBundle:y}){const[I,g]=o.useState(null),T=x==="disconnected"||x==="reconnecting"||x==="offline"||x==="auth_failed",A=c.length>0,j=t.length>0||r.length>0||n.length>0||a.length>0,v=e==="machines"?"Machines":"Chats",K=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",_=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",C=o.useCallback(async P=>{const N=As(P);if(!N)return;const M=Array.isArray(P.messages)?P.messages:[],O=mc({activeConv:P,visibleMessages:M,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:M.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),$=await m(N,"get_chat_debug_bundle",{...Zt(P),delivery:"daemon_file",frontendSnapshot:O}),E=qr($),U=hc(E),X=await pc(U);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),rt.showToast(fc(E,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[u,m]),H=y||C,F=o.useCallback(()=>{I&&(f==null||f(I),g(null))},[I,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${K}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:v}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.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:[s.jsx(sn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:p,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:s.jsx(tn,{size:18})})]})]})}),s.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"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:T?s.jsx(Fs,{icon:s.jsx(ri,{}),title:x==="offline"?"Network offline":x==="auth_failed"?"Session expired":"Reconnecting",subtitle:x==="offline"?"Waiting for network…":x==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):c.length===0?s.jsx(Fs,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:b?"Waiting for your daemon":"Connect your machines",subtitle:b?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!b&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(dl,{})})}):s.jsx(bs,{children:c.map((P,N)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${N>0?"border-t border-border-subtle/70":""}`,onClick:()=>k(P.id),type:"button",children:[s.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(P.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:P.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:P.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[P.unread," new"]}):P.total>0?`${P.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:P.subtitle}),P.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[P.total," chat",P.total!==1?"s":"",P.unread>0?` · ${P.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},P.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Cr,{title:"Needs attention",className:"mb-0"}),s.jsx(bs,{children:t.map((P,N)=>s.jsx("div",{className:N>0?"border-t border-border-subtle/70":"",children:s.jsx(Tr,{item:P,type:"needs_attention",getAvatarText:l,onOpenConversation:d,onRequestHideConversation:f?()=>g(P.conversation):void 0,onCollectChatDebugBundle:H})},P.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Cr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(bs,{children:r.map((P,N)=>s.jsx("div",{className:N>0?"border-t border-border-subtle/70":"",children:s.jsx(Tr,{item:P,type:"task_complete",getAvatarText:l,onOpenConversation:d,onRequestHideConversation:f?()=>g(P.conversation):void 0,onCollectChatDebugBundle:H})},P.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Cr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(bs,{children:n.map((P,N)=>s.jsx("div",{className:N>0?"border-t border-border-subtle/70":"",children:s.jsx(Tr,{item:P,type:"working",getAvatarText:l,onOpenConversation:d,onRequestHideConversation:f?()=>g(P.conversation):void 0,onCollectChatDebugBundle:H})},P.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(Cr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(bs,{children:a.map((P,N)=>s.jsx("div",{className:N>0?"border-t border-border-subtle/70":"",children:s.jsx(Tr,{item:P,type:"earlier",getAvatarText:l,onOpenConversation:d,onRequestHideConversation:f?()=>g(P.conversation):void 0,onCollectChatDebugBundle:H})},P.conversation.tabKey))}):j?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):T?s.jsx(Fs,{icon:s.jsx(ri,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):A?s.jsx(Fs,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Ft,{size:20})}),title:"No conversations yet",subtitle:_c,children:w&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:w,"aria-label":Et,title:Et,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:Et})]})}):s.jsx(Fs,{icon:s.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&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(bs,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[i.length," collapsed ",i.length===1?"conversation":"conversations"]})]}),s.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:h,children:"Restore all"})]})})})]}),e==="chats"&&w&&j&&s.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:w,"aria-label":Et,title:Et,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),I&&s.jsx(dx,{conversation:I,onCancel:()=>g(null),onConfirm:F}),s.jsx(ul,{section:e,onSectionChange:S})]})}function mx(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 ml(e){const t=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=mx(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function mn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:m}){const[d,h]=o.useState(r);o.useEffect(()=>{h(r)},[r]);const f=Gh(r),w=d.trim();return s.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:s.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:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.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:s.jsx(St,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.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:()=>{!f||a||u(f)},disabled:!f||a,children:[s.jsx(Ca,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:k=>h(k.target.value),onKeyDown:k=>{k.key!=="Enter"||!w||a||(k.preventDefault(),u(w))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!w||a||u(w)},disabled:!w||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(k=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(k.path),children:[s.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:s.jsx(Cs,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:k.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:k.path})]})]},k.path))})}),s.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:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(w||r),disabled:!w&&!r||a,children:c})]})]})})}function no({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:m,argsValue:d,onArgsChange:h,showModelInput:f,modelValue:w,onModelChange:k,historyProviderNode:p,onConfirm:S,onCancel:x}){const b=n==null?void 0:n.find(y=>y.key===a);return s.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:s.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:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:x,"aria-label":"Close launch confirmation",children:s.jsx(St,{size:16})})]}),s.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&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.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:u,children:n.map(y=>s.jsx("option",{value:y.key,children:y.label},y.key))}),(b==null?void 0:b.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:b.description})]}),p,r.map(y=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:y.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:y.value})]},`${y.label}:${y.value}`)),f&&k&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:w||"",onChange:y=>k(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:u})]}),m&&h&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:d||"",onChange:y=>h(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:u})]})]}),s.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:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:x,disabled:u,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:S,disabled:u,children:[s.jsx(Ma,{size:14}),u?l:c]})]})]})})}function ni(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function os(e){const{machine:t,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${ni(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(t.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:ni(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(m=>m.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function fx(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function px(e){return[fx(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function hx(e){return e.lastLaunchedAt?rn(e.lastLaunchedAt):""}function fl(e){return{metaText:px(e),updatedLabel:hx(e)}}function En(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function xx({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var Je,dt,ut,lt;const c=dr(),[l,u]=o.useState(!1),m=(((Je=e.detectedIdes)==null?void 0:Je.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),h=e.defaultWorkspaceId||null,[f,w]=o.useState(h||((dt=d[0])==null?void 0:dt.id)||""),[k,p]=o.useState(""),[S,x]=o.useState(""),[b,y]=o.useState([]),[I,g]=o.useState(!1),[T,A]=o.useState(""),[j,v]=o.useState(!1),[K,_]=o.useState(En(m,t.length,r.length)),C=o.useRef(null),[H,F]=o.useState(null),P=o.useRef("__home__"),[N,M]=o.useState("__home__"),[O,$]=o.useState(""),[E,U]=o.useState(""),[X,he]=o.useState(""),[ce,te]=o.useState([]),[ye,fe]=o.useState(()=>xt().textQuery),[be,J]=o.useState(()=>xt().workspaceQuery),[ae,ge]=o.useState(()=>xt().modelQuery),[ee,de]=o.useState(()=>xt().resumableOnly),[we,ue]=o.useState(()=>xt().sortMode),[xe,se]=o.useState(!1),[ie,re]=o.useState(!1),G=o.useRef(null),Y=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const le=f==="__custom__"?k.trim():((ut=d.find(Te=>Te.id===f))==null?void 0:ut.path)||"",ke=f==="__custom__"&&!!le&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),Z=f!=="__custom__"&&((lt=d.find(Te=>Te.id===f))==null?void 0:lt.path)||"",Ce=o.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),Pe=o.useCallback(async Te=>{g(!0),A("");try{const Ge=await a(Te);x(Ge.path),p(Ge.path),y(Ge.directories)}catch(Ge){A(Ge instanceof Error?Ge.message:"Could not load folder")}finally{g(!1)}},[a]),We=o.useCallback(()=>{var Ge;w("__custom__"),v(!0);const Te=dn(e.platform,ln(k.trim(),Z,Ce,e.defaultWorkspacePath,(Ge=d.find(Qe=>Qe.id===h))==null?void 0:Ge.path,d.map(Qe=>Qe.path)));Pe(Te)},[k,h,Pe,Ce,Z,e.platform,d]),He=o.useCallback(Te=>{if(Te!=null&&Te.workspaceId){w(Te.workspaceId),p("");return}if(Te!=null&&Te.workspacePath){w("__custom__"),p(Te.workspacePath);return}w(""),p("")},[]),D=o.useCallback(Te=>{if(w(Te),Te==="__custom__"){We();return}p("")},[We]),Se=o.useCallback(Te=>{w("__custom__"),p(Te)},[]),Ie=o.useCallback((Te,Ge)=>{C.current=Ge,P.current=Te.selectedWorkspaceKey||"__home__",M(Te.selectedWorkspaceKey||"__home__"),$(Te.initialArgs||""),U(Te.initialModel||""),he(""),te([]);const Qe=Te.providerType?`${e.id}:${Te.providerType}`:null;if(sp(Y.current,Qe)){const qe=xt();fe(qe.textQuery),J(qe.workspaceQuery),ge(qe.modelQuery),de(qe.resumableOnly),ue(qe.sortMode)}Y.current=Qe,F(Te),Te.providerType&&i&&(se(!0),i(Te.providerType).then(qe=>te(qe||[])).catch(qe=>console.warn("Failed to load saved sessions",qe)).finally(()=>se(!1)))},[i,e.id]),Re=o.useMemo(()=>Pc(ce,{textQuery:ye,workspaceQuery:be,modelQuery:ae,resumableOnly:ee,sortMode:we}),[ae,ee,ce,we,ye,be]);o.useEffect(()=>{X&&(Re.some(Te=>Te.providerSessionId===X)||he(""))},[Re,X]);const Ee=o.useCallback(()=>{C.current&&(re(!0),C.current().finally(()=>{C.current=null,re(!1),F(null)}))},[]),Fe=o.useCallback(()=>{C.current=null,F(null)},[]),Ue=o.useCallback(Te=>{P.current=Te,M(Te)},[]);return o.useEffect(()=>{var Te;G.current!==e.id&&(G.current=e.id,w(h||((Te=d[0])==null?void 0:Te.id)||"__custom__"),p(""),x(""),y([]),A(""),v(!1),fe(xt().textQuery),J(xt().workspaceQuery),ge(xt().modelQuery),de(xt().resumableOnly),ue(xt().sortMode),Y.current=null,_(En(m,t.length,r.length)))},[r.length,t.length,h,m,e.id,d]),o.useEffect(()=>{var Te;f!=="__custom__"&&(f&&d.some(Ge=>Ge.id===f)||w(h||((Te=d[0])==null?void 0:Te.id)||"__custom__"))},[h,f,d]),o.useEffect(()=>{K==="ide"&&m||K==="cli"&&t.length>0||K==="acp"&&r.length>0||_(En(m,t.length,r.length))},[K,r.length,t.length,m]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:m,workspaceRows:d,defaultWorkspaceId:h,workspaceChoice:f,customWorkspacePath:k,browseCurrentPath:S,browseDirectories:b,browseBusy:I,browseError:T,browseDialogOpen:j,activeLauncherKind:K,launchConfirm:H,launchConfirmWorkspaceKeyRef:P,launchConfirmWorkspaceKey:N,launchConfirmArgs:O,launchConfirmModel:E,launchConfirmResumeId:X,launchConfirmSavedSessions:ce,launchConfirmTextFilter:ye,launchConfirmWorkspaceFilter:be,launchConfirmModelFilter:ae,launchConfirmResumableOnly:ee,launchConfirmSortMode:we,filteredLaunchConfirmSavedSessions:Re,launchConfirmSessionsLoading:xe,launchConfirmBusy:ie,resolvedWorkspacePath:le,canCreateMissingWorkspace:ke,openBrowseDialog:We,loadBrowsePath:Pe,handleWorkspaceChoiceChange:D,chooseCustomWorkspacePath:Se,setCustomWorkspacePath:p,setBrowseDialogOpen:v,setActiveLauncherKind:_,openLaunchConfirm:Ie,handleConfirmLaunch:Ee,closeLaunchConfirm:Fe,setWorkspaceSelectionFromOption:He,setLaunchConfirmWorkspaceKeyAndSync:Ue,setLaunchConfirmArgs:$,setLaunchConfirmModel:U,setLaunchConfirmResumeId:he,setLaunchConfirmTextFilter:fe,setLaunchConfirmWorkspaceFilter:J,setLaunchConfirmModelFilter:ge,setLaunchConfirmResumableOnly:de,setLaunchConfirmSortMode:ue}}function bx({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:m,showBottomNav:d,onBack:h,onSectionChange:f,onOpenConversation:w,onOpenRecent:k,onOpenMachineDetails:p,onMachineUpgrade:S,onLaunchDetectedIde:x,onAddWorkspace:b,onBrowseDirectory:y,onLaunchWorkspaceProvider:I,onListSavedSessions:g}){const T=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",A=r.slice(0,4),j=t.slice(0,3),v=xx({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:y,onListSavedSessions:g}),K=o.useMemo(()=>A.map(N=>{const{metaText:M,updatedLabel:O}=fl(N);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:M,updatedLabel:O,onClick:()=>{const{options:$,selectedKey:E}=os({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspacePath:N.workspace});v.openLaunchConfirm({title:N.kind==="ide"?ss("restart-ide",N.label):N.providerSessionId?Ga(N.label):ss("start-fresh",N.label),description:N.kind==="ide"?rs("restart-ide"):N.providerSessionId?qa():rs("start-fresh"),confirmLabel:N.kind==="ide"?Ms("restart-ide"):N.providerSessionId?Xr(!0):Ms("start-fresh"),busyLabel:N.kind==="ide"?Rs("restart-ide"):N.providerSessionId?za(!0):Rs("start-fresh"),workspaceOptions:$,selectedWorkspaceKey:E,details:[{label:"Mode",value:T(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const U=$.find(X=>X.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption(U),await k({...N,workspace:(U==null?void 0:U.workspacePath)??null})})}}}),[v,k,A]),_=o.useMemo(()=>j.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:ot(N.conversation),secondary:Wf(N.conversation,{timestampLabel:N.timestamp?Yi(N.timestamp):null}),unread:N.unread,onClick:()=>w(N.conversation)})),[w,j]),C=v.showAllRecent?K:K.slice(0,4),H=K.length>0,F=_.length>0,P=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${P} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:s.jsx(Ca,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Ct(e,{fallbackId:e.id})}),s.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}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[F&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:_.map(N=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${N.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:N.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:N.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))})]}),H&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:C.map(N=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:N.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:N.primary}),N.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:N.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))}),K.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.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(N=>!N),children:v.showAllRecent?"Show fewer":`Show ${K.length-4} more`})})]}),(v.hasIdeOptions||n.length>0||a.length>0)&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.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:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:v.workspaceChoice,onChange:N=>v.handleWorkspaceChoiceChange(N.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:v.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[v.workspaceRows.map(N=>s.jsxs("option",{value:N.id,children:[N.id===v.defaultWorkspaceId?"⭐ ":"",an(N.path,N.label)||N.path]},N.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),v.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.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:s.jsx(Cs,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:v.resolvedWorkspacePath||v.browseCurrentPath||"No folder selected yet."})]})]})}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.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…"}),s.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&&b(v.resolvedWorkspacePath)},disabled:!v.resolvedWorkspacePath||v.browseBusy,children:"Save as workspace"})]})]}),v.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[v.hasIdeOptions&&s.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&&s.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&&s.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&&s.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[s.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"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:v.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(N=>s.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:M,selectedKey:O}=os({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspaceId:v.workspaceChoice!=="__custom__"?v.workspaceChoice:null,currentWorkspacePath:v.resolvedWorkspacePath});v.openLaunchConfirm({title:`Launch ${N.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:M,selectedWorkspaceKey:O,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:N.name}]},async()=>{const $=M.find(E=>E.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption($),x(N.type,{workspacePath:($==null?void 0:$.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:N.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath||"Use selected workspace"})]},N.type)):(v.activeLauncherKind==="cli"?n:a).map(N=>s.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 M=v.activeLauncherKind==="cli"?"cli":"acp",{options:O,selectedKey:$}=os({machine:{workspaces:v.workspaceRows,defaultWorkspaceId:v.defaultWorkspaceId},currentWorkspaceId:v.workspaceChoice!=="__custom__"?v.workspaceChoice:null,currentWorkspacePath:v.resolvedWorkspacePath});v.openLaunchConfirm({title:`Launch ${N.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${M.toUpperCase()}`,workspaceOptions:O,selectedWorkspaceKey:$,details:[{label:"Mode",value:M.toUpperCase()},{label:"Provider",value:N.displayName}],showArgsInput:!0,showModelInput:M==="acp",initialArgs:"",initialModel:"",providerType:N.type},async()=>{const E=O.find(U=>U.key===v.launchConfirmWorkspaceKeyRef.current);v.setWorkspaceSelectionFromOption(E),I(M,N.type,{workspaceId:(E==null?void 0:E.workspaceId)??null,workspacePath:(E==null?void 0:E.workspacePath)??null,args:v.launchConfirmArgs,model:v.launchConfirmModel,resumeSessionId:v.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[N.icon?`${N.icon} `:"",N.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:v.resolvedWorkspacePath||"Use selected workspace"})]},N.type))})]}),l.message&&s.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&&s.jsx("div",{className:"mt-2",children:s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>b(v.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&s.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:S,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),v.browseDialogOpen&&s.jsx(mn,{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:N=>{v.loadBrowsePath(N)},onConfirm:N=>{v.chooseCustomWorkspacePath(N),v.setBrowseDialogOpen(!1)}}),v.launchConfirm&&s.jsx(no,{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?Xr(!!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)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),v.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Va()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:v.launchConfirmTextFilter,onChange:N=>v.setLaunchConfirmTextFilter(N.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:v.launchConfirmWorkspaceFilter,onChange:N=>v.setLaunchConfirmWorkspaceFilter(N.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:v.launchConfirmModelFilter,onChange:N=>v.setLaunchConfirmModelFilter(N.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),s.jsxs("select",{value:v.launchConfirmSortMode,onChange:N=>v.setLaunchConfirmSortMode(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:v.launchConfirmResumableOnly,onChange:N=>v.setLaunchConfirmResumableOnly(N.target.checked),disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:v.launchConfirmResumeId,onChange:N=>v.setLaunchConfirmResumeId(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:v.launchConfirmBusy||v.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:ap()}),v.filteredLaunchConfirmSavedSessions.map(N=>s.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":"(workspace missing)"]},N.providerSessionId))]}),!v.launchConfirmSessionsLoading&&v.launchConfirmSavedSessions.length>0&&v.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),v.launchConfirmResumeId&&(()=>{const N=v.filteredLaunchConfirmSavedSessions.find(O=>O.providerSessionId===v.launchConfirmResumeId);if(!N)return null;const M=ml(N);return s.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:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:M.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:M.providerSessionId}),s.jsx("div",{className:"mt-1",children:M.metaLine}),M.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:M.updatedLabel}),M.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:M.preview})]})})()]}),onConfirm:v.handleConfirmLaunch,onCancel:v.closeLaunchConfirm}),d&&s.jsx(ul,{section:m,onSectionChange:f})]})}function $r(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function gx(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:$r(e)}function yx(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function vx(e,t){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:ds(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,m,d;const a=nr(n)?"cli":ws(n)?"acp":"ide",i=ds(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(nr(n)?n.cliName||n.type:ws(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ws(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(m=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:m.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function wx(e,t){const r=new Map;for(const n of t){const a=hs(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((h,f)=>f.timestamp-h.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ia(n),u=a.filter(h=>h.unread||h.requiresAction).length,m=yx(n),d=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Ct(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?Hf(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 jx(e){return e==="chat"}function Ar(e,t){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}`,t)}catch{}}function kx({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:w,setSelectedTabKey:k,setScreen:p,setSelectedMachineId:S,setSection:x,setMachineBackTarget:b,resetMachineAction:y}){const I=o.useRef(null),g=o.useCallback(T=>{if(!(T!=null&&T.sessionId))return;const A=zr(T,c),j=Math.max(Date.now(),es(T),A.lastUpdated||0);Ar("mark_read:start",{tabKey:T.tabKey,sessionId:T.sessionId,displayPrimary:ot(T),inboxBucket:A.inboxBucket,unread:A.unread,lastSeenAt:A.lastSeenAt,lastUpdated:A.lastUpdated,activityAt:es(T),readAt:j}),l(hs(T)||T.routeId,"mark_session_seen",{sessionId:T.sessionId,providerSessionId:T.providerSessionId,seenAt:j,completionMarker:A.completionMarker}).then(v=>{Ar("mark_read:result",{tabKey:T.tabKey,sessionId:T.sessionId,result:v})}).catch(v=>{Ar("mark_read:error",{tabKey:T.tabKey,sessionId:T.sessionId,error:v instanceof Error?v.message:String(v)})})},[c,l]);return o.useEffect(()=>{var A;if(!n){jx(i)&&p("inbox"),k(((A=e[0])==null?void 0:A.tabKey)||null),I.current=null;return}if(i!=="chat"){I.current=null;return}const T=`${n.tabKey}:${n.sessionId||""}`;I.current!==T&&(I.current=T,g(n))},[e,g,i,n,p,k]),o.useEffect(()=>{if(!u)return;const T=e.find(A=>A.tabKey===u);T&&(k(T.tabKey),p("chat"),m==null||m())},[e,m,u,p,k]),o.useEffect(()=>{if(!d)return;const T=t.find(A=>A.id===d);T&&(S(T.id),y(),x("machines"),b("inbox"),p("machine"),h==null||h())},[t,h,d,y,b,p,x,S]),o.useEffect(()=>{f&&(x(f),p("inbox"),w==null||w())},[w,f,p,x]),o.useEffect(()=>{const T=r.filter(A=>A.inboxBucket==="task_complete"||A.unread);T.length!==0&&Ar("inbox_state",{screen:i,selectedTabKey:a,items:T.map(A=>{const j=zr(A.conversation,c);return{liveState:j,tabKey:A.conversation.tabKey,sessionId:A.conversation.sessionId,displayPrimary:ot(A.conversation),serverBucket:j.inboxBucket,computedBucket:A.inboxBucket,serverUnread:j.unread,computedUnread:A.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:es(A.conversation)}})})},[r,c,i,a]),{markConversationRead:g}}function Sx(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ai(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Nx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Cx({sendDaemonCommand:e,navigate:t,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,m]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),m(null)},[]),h=o.useCallback(async(b,y,I)=>{var g;try{i("loading"),l(`Launching ${y}…`);const T={ideType:y,enableCdp:!0};(g=I==null?void 0:I.workspacePath)!=null&&g.trim()&&(T.workspace=I.workspacePath.trim()),await e(b,"launch_ide",T),i("done"),l(`${y} launch requested`)}catch(T){i("error"),l(T instanceof Error?T.message:"Launch IDE failed"),console.error("Launch IDE failed",T)}},[e]),f=o.useCallback(async(b,y,I)=>{if(y.trim())try{i("loading"),l(I!=null&&I.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(b,"workspace_add",{path:y.trim(),createIfMissing:(I==null?void 0:I.createIfMissing)===!0});if(g!=null&&g.success){i("done"),l(I!=null&&I.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((g==null?void 0:g.error)||"Could not save workspace")}catch(g){i("error"),l(g instanceof Error?g.message:"Could not save workspace")}},[e]),w=o.useCallback(async b=>{var y,I,g,T,A,j;try{i("loading"),l("Starting daemon upgrade…");const v=await e(b,"daemon_upgrade",{});if((y=v==null?void 0:v.result)!=null&&y.alreadyLatest){i("done"),l(`Already on v${((I=v==null?void 0:v.result)==null?void 0:I.version)||"latest"}.`);return}if((g=v==null?void 0:v.result)!=null&&g.upgraded||(T=v==null?void 0:v.result)!=null&&T.success){i("done"),l(`Upgrade to v${((A=v==null?void 0:v.result)==null?void 0:A.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((j=v==null?void 0:v.result)==null?void 0:j.error)||"Upgrade failed")}catch(v){i("error"),l(v instanceof Error?v.message:"Upgrade failed")}},[e]),k=o.useCallback(async(b,y,I,g)=>{var j,v,K;const T=Date.now(),A={machineId:b,kind:y,providerType:I,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:T};try{i("loading"),l(`Launching ${I}…`),m(A);const _={cliType:I};(j=g==null?void 0:g.workspacePath)!=null&&j.trim()?_.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(_.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(_.resumeSessionId=g.resumeSessionId),(v=g==null?void 0:g.args)!=null&&v.trim()&&(_.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(K=g==null?void 0:g.model)!=null&&K.trim()&&(_.initialModel=g.model.trim());const C=await e(b,"launch_cli",_),H=(C==null?void 0:C.result)||C,F=(H==null?void 0:H.sessionId)||(H==null?void 0:H.id);if(C!=null&&C.success&&F){m(null),i("done"),l(`${I} launched`),t(Gt(F));return}if(C!=null&&C.success){i("loading"),l(`${I} launch requested — waiting for session…`);return}m(null),i("error"),l((C==null?void 0:C.error)||(H==null?void 0:H.error)||`Could not launch ${y.toUpperCase()} workspace`)}catch(_){if(Nx(_)){i("loading"),l(`${I} launch requested — waiting for session…`);return}m(null),i("error"),l(_ instanceof Error?_.message:`Could not launch ${y.toUpperCase()} workspace`)}},[t,e]),p=o.useCallback(async(b,y)=>{try{const I=await e(b,"list_saved_sessions",{providerType:y,kind:"cli",limit:30}),g=(I==null?void 0:I.result)??I;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(I){return console.error("Failed to list saved sessions on mobile:",I),[]}},[e]),S=o.useCallback(async(b,y)=>un(e,b,y),[e]);o.useEffect(()=>{if(!u)return;const b=ai(u.workspacePath),y=r.find(g=>{var _,C,H,F;if(!g||g.type==="adhdev-daemon"||Sx(g.daemonId||g.id)!==u.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==u.kind||String(g.agentType||g.type||"")!==u.providerType)return!1;const v=String(g.providerSessionId||"");if(u.resumeSessionId&&v)return v===u.resumeSessionId;if(b){const P=ai(g.workspace||g.runtimeWorkspaceLabel);return P?P===b:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((F=(H=(C=(_=g.activeChat)==null?void 0:_.messages)==null?void 0:C.at)==null?void 0:H.call(C,-1))==null?void 0:F.timestamp)||0)>=u.startedAt-5e3});if(!y)return;const I=yc({entrySessionId:y.sessionId,entryInstanceId:y.instanceId,entryRouteId:y.id,conversations:n});I&&(m(null),i("done"),l(`${u.providerType} launched`),t(Gt(I)))},[n,r,t,u]),o.useEffect(()=>{if(!u)return;const b=window.setTimeout(()=>{m(y=>!y||y.startedAt!==u.startedAt?y:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(b)},[u]);const x=o.useCallback(async(b,y)=>{if(y.kind==="ide"&&y.providerType){await h(b,y.providerType,{workspacePath:y.workspace||null});return}(y.kind==="cli"||y.kind==="acp")&&y.providerType&&await k(b,y.kind,y.providerType,{workspacePath:y.workspace||null,resumeSessionId:y.providerSessionId||null})},[h,k]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:h,handleAddWorkspace:f,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:k,handleListSavedSessions:p,handleBrowseDirectory:S,handleOpenRecent:x}}function Tx({conversations:e,selectedConversation:t,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:m}){const d=o.useCallback(x=>{i(x.tabKey),c("chat"),n(x)},[n,c,i]),h=o.useCallback(x=>{const b=e.find(y=>y.routeId===x.routeId&&y.streamSource==="native");b&&(i(b.tabKey),c("chat"),n(b))},[e,n,c,i]),f=o.useCallback(()=>{n(t),c("inbox")},[n,t,c]),w=o.useCallback((x,b="inbox")=>{l(x),a(),u("machines"),m(b),c("machine")},[a,m,c,u,l]),k=o.useCallback(x=>{const b=hs(x);b&&w(b,"chat")},[w]),p=o.useCallback(()=>{a(),c(r)},[r,a,c]),S=o.useCallback(x=>{u(x),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:h,backFromConversation:f,openMachine:w,openConversationMachine:k,backFromMachine:p,changeMachineSection:S}}function fs(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Ax(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Ix({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:w,onOpenHistory:k,onOpenRemote:p,onStopCli:S,wsStatus:x,isConnected:b,onShowAllHiddenConversations:y,onHideConversation:I,onOpenNewSession:g,liveSessionInboxState:T,setCliViewModeOverrides:A}){const[j,v]=o.useState(()=>{var Z;return((Z=e[0])==null?void 0:Z.tabKey)||null}),[K,_]=o.useState(()=>e[0]?"chat":"inbox"),[C,H]=o.useState("chats"),[F,P]=o.useState(null),[N,M]=o.useState("inbox"),O=o.useRef([]),$=_s(),E="0.9.65",U=o.useMemo(()=>e.find(Z=>Z.tabKey===j)||e[0]||null,[e,j]),X=o.useMemo(()=>U?r.find(Z=>Z.id===U.routeId):void 0,[r,U]),he=o.useMemo(()=>!U||Xe(U)||!et(U)?null:Ds(U),[U]),ce=o.useMemo(()=>r.filter(Z=>Z.type==="adhdev-daemon").sort(Pa),[r]),te=o.useMemo(()=>ce.find(Z=>Z.id===F)||null,[ce,F]),ye=cn({sendDaemonCommand:a,activeConv:U||void 0,setActionLogs:i,isStandalone:c}),fe=Cx({sendDaemonCommand:a,navigate:$,ides:r,conversations:e}),be=o.useMemo(()=>e.map(Z=>{const Ce=K==="chat"&&(U==null?void 0:U.tabKey)===Z.tabKey,Pe=nn(Z,T,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ce}),We=es(Z),He=Ic(Z);return{conversation:Z,timestamp:We,preview:He,unread:Pe.unread,requiresAction:Pe.requiresAction,isWorking:Pe.isWorking,inboxBucket:Pe.inboxBucket}}),[e,T,K,U]),{markConversationRead:J}=kx({conversations:e,machineEntries:ce,items:be,selectedConversation:U,selectedTabKey:j,screen:K,liveSessionInboxState:T,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:m,requestedMachineId:d,onRequestedMachineConsumed:h,requestedMobileSection:f,onRequestedMobileSectionConsumed:w,setSelectedTabKey:v,setScreen:_,setSelectedMachineId:P,setSection:H,setMachineBackTarget:M,resetMachineAction:fe.resetMachineAction}),ae=Tx({conversations:e,selectedConversation:U,machineBackTarget:N,markConversationRead:J,resetMachineAction:fe.resetMachineAction,setSelectedTabKey:v,setScreen:_,setSelectedMachineId:P,setSection:H,setMachineBackTarget:M}),ge=o.useMemo(()=>$r(be.filter(Z=>Z.requiresAction)),[be]),ee=o.useMemo(()=>$r(be.filter(Z=>Z.unread&&!Z.requiresAction)),[be]),de=o.useMemo(()=>gx(be.filter(Z=>!Z.unread&&!Z.requiresAction&&Z.isWorking),O.current),[be]);o.useEffect(()=>{O.current=de.map(Z=>Z.conversation.tabKey)},[de]);const we=o.useMemo(()=>$r(be.filter(Z=>!Z.unread&&!Z.requiresAction&&!Z.isWorking)),[be]),ue=o.useMemo(()=>te?be.filter(Z=>hs(Z.conversation)===te.id):[],[be,te]),xe=o.useMemo(()=>vx(te,r),[r,te]),se=(te==null?void 0:te.version)||null,ie=!!te&&!!se&&!0&&se!==E,re=o.useMemo(()=>(te==null?void 0:te.availableProviders)||[],[te]),G=o.useMemo(()=>re.filter(Z=>fs(Z,"cli")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[re]),Y=o.useMemo(()=>re.filter(Z=>fs(Z,"acp")).map(Z=>({type:Z.type,displayName:Z.displayName||Z.type,icon:Z.icon})),[re]),le=o.useMemo(()=>wx(ce,be),[be,ce]),ke=o.useCallback(async Z=>{te&&await fe.handleOpenRecent(te.id,Z)},[fe,te]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:K==="chat"&&U?s.jsx(cx,{selectedConversation:U,isAcp:Xe(U),isStandalone:c,selectedIdeEntry:X,actionLogs:n,userName:l,isSendingChat:ye.isSendingChat,sendFeedbackMessage:ye.sendFeedbackMessage,isFocusingAgent:ye.isFocusingAgent,handleModalButton:ye.handleModalButton,handleRelaunch:ye.handleRelaunch,onBack:ae.backFromConversation,onOpenNativeConversation:ae.openNativeConversation,onOpenMachine:ae.openConversationMachine,onOpenHistory:k,onOpenRemote:p,onStopCli:S,cliViewMode:he,onSetCliViewMode:async Z=>{await rl({conversation:U,mode:Z,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:A})},handleSendChat:ye.handleSendChat,handleFocusAgent:ye.handleFocusAgent}):K==="machine"&&te?s.jsx(bx,{selectedMachineEntry:te,selectedMachineConversations:ue,selectedMachineRecentLaunches:xe,cliProviders:G,acpProviders:Y,selectedMachineNeedsUpgrade:ie,appVersion:E,machineAction:fe.machineAction,isStandalone:c,section:C,showBottomNav:N==="inbox",onBack:ae.backFromMachine,onSectionChange:ae.changeMachineSection,onOpenConversation:ae.openConversation,onOpenRecent:ke,onOpenMachineDetails:()=>$(`/machines/${te.id}`),onMachineUpgrade:()=>fe.handleMachineUpgrade(te.id),onLaunchDetectedIde:(Z,Ce)=>fe.handleLaunchDetectedIde(te.id,Z,Ce),onAddWorkspace:(Z,Ce)=>fe.handleAddWorkspace(te.id,Z,Ce),onBrowseDirectory:Z=>fe.handleBrowseDirectory(te.id,Z),onLaunchWorkspaceProvider:(Z,Ce,Pe)=>fe.handleLaunchWorkspaceProvider(te.id,Z,Ce,Pe),onListSavedSessions:Z=>fe.handleListSavedSessions(te.id,Z)}):s.jsx(ux,{section:C,attentionItems:ge,unreadItems:ee,workingItems:de,completedItems:we,hiddenConversations:t,machineCards:le,getAvatarText:Ax,actionLogs:n,sendDaemonCommand:a,onOpenConversation:ae.openConversation,onShowAllHidden:y,onHideConversation:I,onOpenNewSession:g,onOpenMachine:ae.openMachine,onOpenSettings:()=>$("/settings"),onSectionChange:H,wsStatus:x,isConnected:b,isStandalone:c})})}function $n(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function Mx({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[m,d]=o.useState(null),h=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const f=o.useCallback(S=>{S.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),w=o.useCallback(S=>{if(!S.dataTransfer.types.includes("text/tab-key"))return;if(S.preventDefault(),!$n(t,r)){d("merge");return}const x=S.currentTarget.getBoundingClientRect(),b=S.clientX-x.left,y=x.width/3;b<y?d("split-left"):b>y*2?d("split-right"):d("merge")},[t,r]),k=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),p=o.useCallback(S=>{c.current=0,u(!1);const x=S.dataTransfer.getData("text/tab-key"),b=x?e.some(I=>I.tabKey===x):!1,y=m;if(d(null),i(),!!x){if(S.preventDefault(),y==="split-left"&&$n(t,r)){r==null||r(x,"split-left");return}if(y==="split-right"&&$n(t,r)){r==null||r(x,"split-right");return}if(b){a(x);return}n==null||n(x)}},[e,m,t,r,n,a,i]);return{dragOver:l,dropAction:m,resetDragState:h,handleDragEnter:f,handleDragOver:w,handleDragLeave:k,handleDrop:p}}function Rx(e,t){const r=new Set(t.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=t.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function Lx({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(t??null),[l,u]=o.useState(r??[]),[m,d]=o.useState(null),h=o.useRef(null),f=o.useRef(null),w=o.useRef(n),k=o.useRef(a);o.useEffect(()=>{w.current=n},[n]),o.useEffect(()=>{k.current=a},[a]),o.useEffect(()=>{t&&t!==i&&c(t)},[t,i]),o.useEffect(()=>{u(A=>{const j=Rx(A,e);return j.length===A.length&&j.every((v,K)=>v===A[K])?A:j})},[e]);const p=o.useMemo(()=>{const A=m??l;if(A.length===0)return e;const j=new Map(A.map((v,K)=>[v,K]));return[...e].sort((v,K)=>{const _=j.get(v.tabKey)??999,C=j.get(K.tabKey)??999;return _-C})},[e,m,l]);o.useEffect(()=>{var j,v;if(p.length===0){i!==null&&(c(null),(j=w.current)==null||j.call(w,null));return}if(i&&p.some(K=>K.tabKey===i))return;const A=p[0].tabKey;A!==i&&(c(A),(v=w.current)==null||v.call(w,A))},[p,i]);const S=o.useMemo(()=>p.find(A=>A.tabKey===i),[p,i]),x=o.useCallback(A=>{var j;c(A),(j=w.current)==null||j.call(w,A)},[]),b=o.useCallback((A,j,v)=>{u(K=>{var F;const _=K.filter(P=>P!==A),C=_.indexOf(j);if(C<0)return K;const H=v==="left"?C:C+1;return _.splice(H,0,A),(F=k.current)==null||F.call(k,_),_}),d(null)},[]),y=o.useCallback((A,j,v)=>{const _=(l.length>0?l:e.map(F=>F.tabKey)).filter(F=>F!==A),C=_.indexOf(j);if(C<0)return;const H=v==="left"?C:C+1;_.splice(H,0,A),h.current=_,d(_)},[l,e]),I=o.useCallback(()=>{var j;const A=h.current;A&&(u(A),(j=k.current)==null||j.call(k,A))},[]),g=o.useCallback(()=>{h.current=null,d(null)},[]),T=o.useCallback(A=>{u(j=>{var K;const v=j.filter(_=>_!==A);return v.push(A),(K=k.current)==null||K.call(k,v),v})},[]);return{activeTabId:i,activeConv:S,sortedConversations:p,previewOrderRef:h,draggingTabRef:f,selectTab:x,handleTabReorder:b,updatePreviewOrder:y,commitPreviewOrder:I,clearPreviewOrder:g,moveTabToEnd:T,setDraggingTabKey:A=>{f.current=A}}}function _x({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.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:t?1:.45},children:s.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"})}),s.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:s.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"})}),s.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:t?1:.45},children:s.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 ao({conversationsCount:e,isSplitMode:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:i}){if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!r&&!n,l=n&&!!i,u=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?_c: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&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:u}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),l&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:i,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Et,"aria-label":Et,children:[s.jsx(Hi,{size:14}),s.jsx("span",{children:Et})]})}),c&&s.jsx(dl,{}),c&&s.jsx("div",{className:"mt-8",children:s.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 →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const pl="adhdev-tab-shortcuts";function hl(){try{return JSON.parse(localStorage.getItem(pl)||"{}")}catch{return{}}}function xl({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>hl()),[l,u]=o.useState(null),m=o.useCallback(h=>{const f=[];return h.metaKey&&f.push(a?"⌘":"Meta"),h.ctrlKey&&f.push("Ctrl"),h.altKey&&f.push(a?"⌥":"Alt"),h.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(f.push(h.key.length===1?h.key.toUpperCase():h.key),f.join("+"))},[a]),d=o.useCallback(h=>{c(h);try{localStorage.setItem(pl,JSON.stringify(h))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const h=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){u(null);return}const w=m(f);if(!w)return;const k={...i};for(const[p,S]of Object.entries(k))S===w&&delete k[p];k[l]=w,d(k),u(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,l,i,d,m]),o.useEffect(()=>{if(!e)return;const h=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[w,k]of Object.entries(i))if(t.includes(w)&&m(f)===k){f.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,i,t,r,n,m]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const Bn=e=>{e.preventDefault()},Px=o.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:m,onConversationActivated:d,onPreviewReorder:h,onReorderTab:f,onCommitPreviewOrder:w,onClearPreviewOrder:k,onDragStateReset:p,onDragTabKeyChange:S,onReceiveTab:x,onOpenContextMenu:b,longPressTimer:y,isGroupActive:I}){const g=Ps(t),T=g.isGenerating?"agent-tab-generating":g.isWaiting?"agent-tab-waiting":"",A=g.isReconnecting,j=o.useCallback(M=>{l.current=t.tabKey,S(t.tabKey),M.dataTransfer.setData("text/tab-key",t.tabKey),M.dataTransfer.effectAllowed="move"},[t.tabKey,l,S]),v=o.useCallback(()=>{l.current=null,S(null),w(),k(),p()},[l,S,w,k,p]),K=o.useCallback(M=>{const O=l.current;if(!(!O||O===t.tabKey)&&M.dataTransfer.types.includes("text/tab-key")){M.preventDefault(),M.stopPropagation();const $=M.currentTarget.getBoundingClientRect(),E=M.clientX<$.left+$.width/2?"left":"right";h(O,t.tabKey,E)}},[t.tabKey,l,h]),_=o.useCallback(M=>{M.preventDefault(),M.stopPropagation();const O=M.dataTransfer.getData("text/tab-key");if(O&&O!==t.tabKey){const $=M.currentTarget.getBoundingClientRect(),E=M.clientX<$.left+$.width/2?"left":"right";c.includes(O)?f(O,t.tabKey,E):x&&x(O)}k()},[t.tabKey,c,f,x,k]),C=o.useCallback(M=>{M.stopPropagation(),u(),m(t.tabKey),d(t)},[t,d,u,m]),H=o.useCallback(M=>{M.preventDefault(),b(M.clientX,M.clientY,t.tabKey)},[t.tabKey,b]),F=o.useCallback(M=>{const O=M.touches[0];y.current=setTimeout(()=>{b(O.clientX,O.clientY,t.tabKey)},600)},[t.tabKey,y,b]),P=o.useCallback(()=>{y.current&&clearTimeout(y.current)},[y]),N=["adhdev-dockview-tab",T,r&&"is-active",I&&"is-group-active",A&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:N,draggable:!0,onDragStart:j,onDragEnd:v,onDragOver:K,onDrop:_,onClick:C,onContextMenu:H,onTouchStart:F,onTouchEnd:P,onTouchMove:P,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:g.isGenerating?s.jsx("div",{className:"tab-spinner"}):g.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):A?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):g.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:ot(t),children:ot(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[A?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:ts(t)}):g.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[ts(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:ts(t)}),s.jsx(Is,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),i&&s.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,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function Dx({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:w,onReceiveTab:k,onHideTab:p,isGroupActive:S,allowTabShortcuts:x=!0}){const[b,y]=o.useState(null),I=o.useRef(null),g=o.useRef(null),T=o.useMemo(()=>e.map(H=>H.tabKey),[e]);ir("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:A,tabShortcuts:j,shortcutListening:v,setShortcutListening:K,saveShortcuts:_}=xl({enabled:x,sortedTabKeys:e.map(H=>H.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!b)return;const H=F=>{const P=document.querySelector("[data-pane-context-menu]");P&&P.contains(F.target)||y(null)};return window.addEventListener("mousedown",H,!0),()=>window.removeEventListener("mousedown",H,!0)},[b]),o.useEffect(()=>{const H=g.current;if(!H)return;const F=P=>{Math.abs(P.deltaY)<=Math.abs(P.deltaX)||(P.preventDefault(),H.scrollLeft+=P.deltaY)};return H.addEventListener("wheel",F,{passive:!1}),()=>H.removeEventListener("wheel",F)},[]);const C=o.useCallback((H,F,P)=>{y({x:H,y:F,tabKey:P})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:g,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(H=>s.jsx(Px,{conv:H,isActive:t===H.tabKey,isDraggedTab:a.current===H.tabKey,isTaskCompleteUnread:n.has(H.tabKey),shortcut:x?j[H.tabKey]:void 0,conversationKeys:T,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:m,onCommitPreviewOrder:d,onClearPreviewOrder:h,onDragStateReset:f,onDragTabKeyChange:w,onReceiveTab:k,onOpenContextMenu:C,longPressTimer:I,isGroupActive:S},H.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:b.x,top:b.y},children:[x&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Bn,onClick:H=>{H.stopPropagation(),K(b.tabKey),y(null)},children:["⌨ ",j[b.tabKey]?`Change shortcut (${j[b.tabKey]})`:"Set shortcut"]}),j[b.tabKey]&&s.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:Bn,onClick:()=>{const H={...j};delete H[b.tabKey],_(H),y(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.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:Bn,onClick:()=>{p(b.tabKey),y(null)},children:"🚫 Hide from Dashboard"})]})]}),x&&v&&s.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:()=>K(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:H=>H.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",A?"⌘+1":"Ctrl+1",", ",A?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Ex({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,userName:u,groupIndex:m,onFocus:d,isSplitMode:h,numGroups:f,onMoveTab:w,onReceiveTab:k,style:p,onActiveTabChange:S,initialActiveTabId:x,initialTabOrder:b,onTabOrderChange:y,onHideTab:I,isFocused:g,allowTabShortcuts:T=!0,onOpenNewSession:A,liveSessionInboxState:j}){const{sendCommand:v}=ft(),K=o.useRef(null),{activeTabId:_,activeConv:C,sortedConversations:H,draggingTabRef:F,selectTab:P,handleTabReorder:N,updatePreviewOrder:M,commitPreviewOrder:O,clearPreviewOrder:$,moveTabToEnd:E,setDraggingTabKey:U}=Lx({conversations:e,initialActiveTabId:x,initialTabOrder:b,onActiveTabChange:S,onTabOrderChange:y}),X=cn({sendDaemonCommand:a,activeConv:C,setActionLogs:i,isStandalone:c}),{dragOver:he,dropAction:ce,resetDragState:te,handleDragEnter:ye,handleDragOver:fe,handleDragLeave:be,handleDrop:J}=Mx({conversations:e,numGroups:f,onMoveTab:w,onReceiveTab:k,onOwnTabDrop:E,onClearPreviewOrder:$}),ae=C&&!Xe(C)&&Ds(C)==="terminal",ge=o.useMemo(()=>C?t.find(ue=>ue.id===C.routeId):void 0,[t,C]),ee=o.useMemo(()=>C?n.filter(ue=>ue.routeId===C.tabKey):[],[n,C]),de=o.useMemo(()=>new Set(H.filter(ue=>Pu(ue,j,{isOpenConversation:ue.tabKey===_})).map(ue=>ue.tabKey)),[_,j,H]);ir("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:_,dragOver:he});const we=o.useCallback(ue=>{ue.streamSource==="agent-stream"&&ue.agentType&&v(ue.routeId,uc(),{agentType:ue.agentType,...ue.sessionId&&{targetSessionId:ue.sessionId}}).catch(()=>{})},[v]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:he?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(Dx,{conversations:H,activeTabId:_,groupIndex:m,numGroups:f,unreadTabKeys:de,draggingTabRef:F,onFocus:d,onSelectTab:P,onConversationActivated:we,onPreviewReorder:M,onReorderTab:N,onCommitPreviewOrder:O,onClearPreviewOrder:$,onDragStateReset:te,onDragTabKeyChange:U,onMoveTab:w,onReceiveTab:k,onHideTab:I,isGroupActive:g??!1,allowTabShortcuts:T}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ye,onDragOver:fe,onDragLeave:be,onDrop:J,children:[he&&s.jsx(_x,{dropAction:ce,canSplit:!!(f<4&&w)}),C?s.jsx(ro,{activeConv:C,clearToken:r[C.tabKey]||0,isCliTerminal:!!ae,ideEntry:ge,terminalRef:K,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,handleSendChat:X.handleSendChat,isSendingChat:X.isSendingChat,sendFeedbackMessage:X.sendFeedbackMessage,handleFocusAgent:X.handleFocusAgent,isFocusingAgent:X.isFocusingAgent,actionLogs:ee,userName:u,isInputActive:!h||!!g}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(ao,{conversationsCount:e.length,isSplitMode:h,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:A})})]})]})}function $x({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,focusedGroup:w,focusGroup:k,moveTabToGroup:p,splitTabRelative:S,closeGroup:x,handleResizeStart:b,groupActiveTabIds:y,setGroupActiveTab:I,groupTabOrders:g,setGroupTabOrder:T,toggleHiddenTab:A,onOpenNewSession:j,allowTabShortcuts:v=!0,liveSessionInboxState:K}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((_,C)=>{const H=t&&n.length===r?`${n[C]}%`:void 0;return s.jsxs(kt.Fragment,{children:[t&&C>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:F=>b(C-1,F),onDoubleClick:()=>x(C),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(Ex,{style:t?{flexBasis:H??`${100/r}%`,flexGrow:H?0:1,flexShrink:H?0:1}:void 0,conversations:_,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setActionLogs:m,isStandalone:d,hasRegisteredMachines:h,userName:f,groupIndex:C,isFocused:t&&w===C,onFocus:()=>k(C),isSplitMode:t,numGroups:r,onMoveTab:(F,P)=>{P==="left"&&C>0?p(F,C-1):P==="right"&&C<r-1?p(F,C+1):P==="split-left"&&r<4?S(F,C,"left"):P==="split-right"&&r<4&&S(F,C,"right")},onReceiveTab:F=>p(F,C),onActiveTabChange:F=>I(C,F),initialActiveTabId:y[C],initialTabOrder:g[C],onTabOrderChange:F=>T(C,F),onHideTab:A,onOpenNewSession:j,allowTabShortcuts:v,liveSessionInboxState:K})]},C)})})}function bl({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?it.onScreenshot("ide-page",(d,h)=>{if(d!==e)return;const f=new FileReader;f.onload=()=>i(f.result),f.readAsDataURL(h)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var d;return e?((d=it.onStatus)==null?void 0:d.call(it,(h,f)=>{h===e&&f!=null&&f.screenshotUsage&&l(f.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,t]),o.useEffect(()=>{const m=e?it.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const u=o.useCallback(async(m,d)=>{const h=e?it.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,d,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const gl="adhdev-dashboard-action-shortcuts",Bx=1200,Kx=[["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 Ox(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function st(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+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 t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function yl(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:st("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:st("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:st("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:st("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:st("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:st("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:st("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:st("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:st("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:st("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:st("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:st("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:st("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:st("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:st("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:st("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:st("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:st("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:st("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:st("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:st("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:st("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:st("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:st("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:st("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:st("toggleCliView",e)}]}function ya(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Zr(e){const t=Object.fromEntries(yl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(gl)||"{}"),n={...t,...r};for(const[a,i]of Kx)n[a]===i&&(n[a]=t[a]);return n}catch{return t}}function vl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Wx({enabled:e=!0,onTrigger:t}){const r=Ox(),[n,a]=o.useState(()=>Zr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),m=o.useRef({parts:[],timer:null}),d=o.useCallback(p=>{const S=[];return p.metaKey&&S.push(r?"⌘":"Meta"),p.ctrlKey&&S.push("Ctrl"),p.altKey&&S.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&S.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(S.push(vl(p.key)),S.join("+"))},[r]),h=o.useCallback(p=>{a(p);try{localStorage.setItem(gl,JSON.stringify(p))}catch{}},[]);o.useEffect(()=>{const p=Zr(r),S=Object.entries(n),x=Object.entries(p);S.length===x.length&&S.every(([b,y])=>p[b]===y)||h(p)},[n,r,h]);const f=o.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),w=o.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},Bx))},[]);o.useEffect(()=>{if(!i)return;const p=S=>{if(S.preventDefault(),S.stopPropagation(),S.key==="Escape"){c(null),u([]);return}const x=d(S);if(!x)return;const y=!(S.metaKey||S.ctrlKey||S.altKey)&&/^[A-Z0-9]$/.test(x);if(l.length===0&&y){u([x]);return}const g=[...l,x].slice(0,2).join(" "),T={...n};for(const[A,j]of Object.entries(T))j===g&&delete T[A];T[i]=g,h(T),c(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,d,h,i,l]),o.useEffect(()=>{if(!e||i)return;const p=S=>{if(S.defaultPrevented)return;const x=d(S);if(!x)return;const b=S.metaKey||S.ctrlKey||S.altKey;if(ya(S.target))return;const y=m.current.parts,I=b?[x]:[...y.slice(-1),x].slice(-2),g=I.join(" "),T=I[I.length-1],A=Object.entries(n).filter(([,C])=>!!C),j=A.find(([,C])=>C===g);if(j){S.preventDefault(),f(),t(j[0]);return}if(A.some(([,C])=>C.startsWith(`${g} `))){S.preventDefault(),m.current.parts=I,w();return}const K=A.find(([,C])=>C===T);if(K){S.preventDefault(),f(),t(K[0]);return}if(A.some(([,C])=>C.startsWith(`${T} `))){S.preventDefault(),m.current.parts=[T],w();return}f()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,w,e,d,t,f,i]),o.useEffect(()=>()=>f(),[f]);const k=o.useMemo(()=>yl(r),[r]);return{isMac:r,actionDefinitions:k,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:h}}function Hx({isTabInPopout:e,isTabFloating:t,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(t&&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})):t?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 wl(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function oi({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!wl(n):!0}function Fx({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:wl(r)}const jl=1e3,Ux=4;function ii(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function ci(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function zx({detachDelayMs:e=jl,stillnessThresholdPx:t=Ux,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let i=null,c=null,l=null,u=null,m=null,d=!1;const h=()=>{m!=null&&(a(m),m=null)},f=()=>{h(),l=null},w=()=>{h(),i=null,c=null,l=null,u=null,d=!1},k=()=>{!i||!l||!u||d||m!=null||(m=n(()=>{m=null,!(!i||!l||!u||d)&&ii(u,c)&&(ci(l,u,t)||(d=!0,r({panelId:i,clientX:u.clientX,clientY:u.clientY})))},e))},p=x=>{if(!(!i||d)){if(!ii(x,c)){u={clientX:x.clientX,clientY:x.clientY},f();return}(!l||ci(l,x,t))&&(h(),l={clientX:x.clientX,clientY:x.clientY}),u={clientX:x.clientX,clientY:x.clientY},k()}},S=x=>{!i||d||(x&&(u={clientX:x.clientX,clientY:x.clientY}),f())};return{startDrag:x=>{h(),i=x.panelId,c=x.selfPanelBounds??null,l=null,u={clientX:x.clientX,clientY:x.clientY},d=!1},markSelfPanel:p,markNonSelfPanel:S,markNoDropTarget:S,markDockTarget:S,endDrag:w,isDragging:()=>i!=null,hasDetached:()=>d,dispose:w}}function Vx(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}const kl=o.createContext(null);function fn(){const e=o.useContext(kl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Br(e){return ot(e)||e.tabKey}function Gx(e){return`remote:${e}`}function Rt(e){return e.startsWith("remote:")}function li(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function qx(e){e.preventDefault()}function Kn(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function On(e,t){e.classList.remove(ea.className,ta.className),e.classList.add(t==="light"?ea.className:ta.className)}function di(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function Yx(e){const[,t]=o.useState(0);o.useEffect(()=>{const r=()=>t(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 Xx(e,t,r){var c;const n=[t];let a;for(const l of n){let u;for(const m of l){const d=e.addPanel({id:m.tabKey,component:"conversation",title:Br(m),params:{kind:"conversation",tabKey:m.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=t[0])==null?void 0:c.tabKey)??null}function ui(e,t){const r=new Set(t.map(n=>n.tabKey));for(const n of[...e.panels])Rt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of t){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==Br(n)&&a.api.setTitle(Br(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Br(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 mi(e,t,r){var u,m;const n=r?Gx(r):null;for(const d of[...e.panels])Rt(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=Pt(t,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=Lc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((m=e.panels.find(d=>!Rt(d.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 Jx({params:e,api:t}){var h;const r=fn(),n=o.useRef(null),[a,i]=o.useState(t.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=cn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(t.isActive);const f=[t.onDidActiveChange(w=>i(w.isActive)),t.onDidActiveGroupChange(w=>{if(!t.isActive&&!w.isActive){i(!1);return}i(t.isActive)})];return()=>{for(const w of f)w.dispose()}},[t]);const u=o.useMemo(()=>c?r.ides.find(f=>f.id===c.routeId):void 0,[r.ides,c]),m=o.useMemo(()=>c?r.actionLogs.filter(f=>f.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(ao,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const d=!Xe(c)&&Ds(c)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(ro,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:m,userName:r.userName,scrollToBottomRequestNonce:((h=r.scrollToBottomRequest)==null?void 0:h.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:a})})}function Qx({params:e}){var u;const t=fn(),r=o.useMemo(()=>Pt([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=bl({doId:a,targetSessionId:r?dc(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?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(qi,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):s.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 Zx(){const e=fn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(ao,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function eb(e){var w,k;Yx(e);const t=fn(),r=o.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Pt([...t.conversationsByTabKey.values()],e.params.routeId),S=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,x=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${S?" is-active":""}${x?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,i=e.api.isGroupActive,c=nn(n,t.liveSessionInboxState,{isOpenConversation:a}),l=c.isReconnecting,u=c.isConnecting,m=c.isGenerating,d=c.isWaiting,h=c.unread,f=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:ot(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var S;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((S=p.target)==null?void 0:S.ownerDocument)??document})},children:[h&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?s.jsx("div",{className:"tab-spinner"}):d?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?s.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:ot(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(n)}):u?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):s.jsx("span",{children:ts(n)})})]}),f&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:f,children:f})]})}function tb({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,hasRegisteredMachines:l,initialDataLoaded:u,userName:m,toggleHiddenTab:d,actionShortcuts:h,registerActionHandlers:f,onActiveTabChange:w,onOpenNewSession:k,onRequestScrollToBottom:p,requestedActiveTabKey:S,requestedRemoteIdeId:x,onRequestedActiveTabConsumed:b,scrollToBottomRequest:y,liveSessionInboxState:I,layoutProfile:g}){var Qe,qe,tt;const{theme:T}=Ja(),{sendCommand:A}=ft(),j=o.useRef(null),v=o.useRef(null),K=o.useRef(null),_=o.useRef(!1),C=o.useRef(!1),H=o.useRef(!1),F=o.useRef(null),P=o.useRef([]),[N,M]=o.useState(null),[O,$]=o.useState(0),E=o.useRef(typeof window>"u"?{}:Nh(g)),U=o.useMemo(()=>new Map(e.map(W=>[W.tabKey,W])),[e]),X=o.useMemo(()=>{const W=j.current;return W?W.groups.some(z=>{try{const R=z.model.location.type;return R!=="floating"&&R!=="popout"?!1:z.panels.some(V=>U.has(V.id))}catch{return!1}}):!1},[U,O,e]),he=o.useCallback(()=>{var W;(W=j.current)==null||W.focus()},[]),ce=o.useCallback((W,z)=>{p==null||p(W,z)},[p]),te=o.useCallback(W=>{const z=document,R=W.document;for(const ne of z.querySelectorAll('link[rel="stylesheet"]')){const ve=R.createElement("link");ve.rel="stylesheet",ve.href=ne.href,ne.crossOrigin&&(ve.crossOrigin=ne.crossOrigin),R.head.appendChild(ve)}for(const ne of z.querySelectorAll("style")){const ve=R.createElement("style");ve.textContent=ne.textContent,R.head.appendChild(ve)}const V=[];for(const ne of z.styleSheets)try{for(const ve of ne.cssRules)ve instanceof CSSStyleRule&&(ve.selectorText===":root"||ve.selectorText==="html")&&V.push(ve.cssText)}catch{}if(V.length>0){const ne=R.createElement("style");ne.textContent=V.join(`
|
|
52
|
+
`),R.head.appendChild(ne)}const L=z.documentElement.getAttribute("data-theme");L&&R.documentElement.setAttribute("data-theme",L),R.documentElement.style.colorScheme=L==="light"?"light":"dark",R.body.className=z.body.className;const q=z.documentElement.getAttribute("style");q&&R.documentElement.setAttribute("style",q);const Q=R.getElementById("dv-popout-window");Q instanceof HTMLElement&&(Q.classList.add("adhdev-dockview"),On(Q,T))},[T]),ye=o.useCallback(()=>{var z;const W=j.current;if(W)for(const R of W.groups)try{const V=(z=R.element)==null?void 0:z.ownerDocument;if(!V||V===document)continue;const L=V.getElementById("dv-popout-window");L instanceof HTMLElement&&(L.classList.add("adhdev-dockview"),On(L,T));const q=document.documentElement.getAttribute("data-theme");q&&V.documentElement.setAttribute("data-theme",q),V.documentElement.style.colorScheme=q==="light"?"light":"dark",V.body.className=document.body.className;const Q=document.documentElement.getAttribute("style");Q?V.documentElement.setAttribute("style",Q):V.documentElement.removeAttribute("style")}catch{}},[T]),fe=o.useCallback(W=>{const z=j.current;if(!z)return;const R=z.getPanel(W);R&&z.addPopoutGroup(R,{popoutUrl:"/popout.html",onDidOpen:({window:V})=>{te(V),xe();const L=U.get(W);V.document.title=L?`${ot(L)} — ADHDev`:"ADHDev — Popout"}})},[U,te]),be=o.useCallback(W=>{const z=j.current,R=z==null?void 0:z.getPanel(W);if(!z||!R)return;const V=z.groups.filter(L=>{var q;try{return((q=L.element)==null?void 0:q.ownerDocument)===document}catch{return!0}});V.length>0?R.api.moveTo({group:V[0],position:"center"}):R.api.moveTo({position:"center"}),R.api.setActive()},[]),J=o.useCallback(W=>{var V;const z=j.current;if(!z)return!1;const R=z.getPanel(W);if(!R)return!1;try{return((V=R.group.element)==null?void 0:V.ownerDocument)!==document}catch{return!1}},[]),ae=o.useCallback(W=>{J(W)&&be(W),d(W)},[J,be,d]),ge=o.useCallback(W=>{const z=j.current,R=z==null?void 0:z.getPanel(W);!z||!R||z.addFloatingGroup(R,{width:600,height:500})},[]),ee=o.useCallback(W=>{var R;const z=(R=j.current)==null?void 0:R.getPanel(W);if(!z)return!1;try{return z.group.model.location.type==="floating"}catch{return!1}},[]),de=o.useCallback(()=>{var z,R;const W=(R=(z=j.current)==null?void 0:z.activePanel)==null?void 0:R.id;return!W||Rt(W)?null:U.has(W)?W:null},[U]),we=o.useCallback(W=>{const z=j.current,R=z==null?void 0:z.getPanel(W);if(!z||!R)return;const V=z.groups.filter(L=>{try{return L.model.location.type==="grid"}catch{return!0}});V.length>0?R.api.moveTo({group:V[0],position:"center"}):R.api.moveTo({position:"center"}),R.api.setActive()},[]),ue=o.useCallback(()=>{var q;const W=j.current;if(!W)return;const R=W.groups.filter(Q=>{var ne;try{return((ne=Q.element)==null?void 0:ne.ownerDocument)===document&&Q.model.location.type==="grid"}catch{return!1}})[0]||null,V=[...W.panels];for(const Q of V){const ne=(q=Q.group.element)==null?void 0:q.ownerDocument,ve=Q.group.model.location.type;ne===document&&ve==="grid"||(R&&R.id!==Q.group.id?Q.api.moveTo({group:R,position:"center"}):Q.api.moveTo({position:"center"}))}const L=W.activePanel;L&&(L.group.model.openPanel(L),L.api.setActive()),Kn(document)},[]),xe=o.useCallback(()=>{var z,R;const W=j.current;if(W)for(const V of W.groups){const L=(z=V.element)==null?void 0:z.ownerDocument;if(!L||L===document)continue;const q=L.getElementById("dv-popout-window");if(!(q instanceof HTMLElement))continue;let Q=null,ne=L.title||"ADHDev",ve="Popout workspace";const Ae=V.activePanel;if(Ae)if(Q=Ae.id,Rt(Ae.id)){const Le=((R=Ae.params)==null?void 0:R.routeId)||Ae.id.slice(7),ze=Pt([...U.values()],Le);ne=Lc(ze),ve=ze!=null&&ze.machineName?`Remote view · ${ze.machineName}`:"Remote view"}else{const Le=U.get(Ae.id);ne=Le?ot(Le):Ae.title||Ae.id,ve=Le?ts(Le):"Dockview panel"}L.title=`${ne} — ADHDev`;const _e=Array.from(L.querySelectorAll("#adhdev-popout-header"));for(const Le of _e)Le.remove();const Ne=L.createElement("div");Ne.id="adhdev-popout-header",L.body.appendChild(Ne),Ne.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(";")),Ne.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;">${li(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;">${li(ve)}</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
|
+
`,q.style.top="52px",q.style.height="calc(100% - 52px)";const De=Ne.querySelector("[data-adhdev-popout-focus]");De&&(De.onclick=()=>{window.focus()});const Be=Ne.querySelector("[data-adhdev-popout-dock]");Be&&(Be.disabled=!Q,Be.style.opacity=Q?"1":"0.5",Be.style.cursor=Q?"pointer":"default",Be.onclick=()=>{var Le;Q&&be(Q),(Le=L.defaultView)==null||Le.focus()})}},[U,be]),se=o.useCallback(W=>{var V;const z=j.current,R=z==null?void 0:z.getPanel(W);if(!(!z||!R)){R.group.model.openPanel(R),R.api.setActive(),ce(W,"dockview-shortcut");try{const L=R.group.model.location;L.type==="popout"?L.getWindow().focus():Kn((V=R.group.element)==null?void 0:V.ownerDocument)}catch{}}},[ce]),ie=o.useCallback(W=>{const z=j.current,R=z==null?void 0:z.activePanel,V=(z==null?void 0:z.activeGroup)||(R==null?void 0:R.group);if(!z||!R||!V)return;const L=V.panels||[];if(L.length<=1)return;const q=L.findIndex(ve=>ve.id===R.id);if(q<0)return;const Q=(q+W+L.length)%L.length,ne=L[Q];ne&&(ne.group.model.openPanel(ne),ne.api.setActive(),Rt(ne.id)||ce(ne.id,"dockview-shortcut"))},[ce]),re=o.useCallback(W=>{var De;const z=j.current,R=(z==null?void 0:z.activeGroup)||((De=z==null?void 0:z.activePanel)==null?void 0:De.group);if(!z||!R)return;const V=z.groups||[],L=V.find(Be=>Be.id===R.id);if(!L)return;const q=L.element.getBoundingClientRect(),Q=q.left+q.width/2,ne=q.top+q.height/2,ve=(Be,Le,ze,Ze)=>Math.max(0,Math.min(Le,Ze)-Math.max(Be,ze)),Ae=Be=>{const Le=Be.element.getBoundingClientRect(),ze=Le.left+Le.width/2,Ze=Le.top+Le.height/2;let mt=0,pt=0,ht=0,me=!1;if(W==="left"?(me=ze<Q,mt=Math.max(0,q.left-Le.right),pt=Math.abs(Ze-ne),ht=ve(q.top,q.bottom,Le.top,Le.bottom)):W==="right"?(me=ze>Q,mt=Math.max(0,Le.left-q.right),pt=Math.abs(Ze-ne),ht=ve(q.top,q.bottom,Le.top,Le.bottom)):W==="above"?(me=Ze<ne,mt=Math.max(0,q.top-Le.bottom),pt=Math.abs(ze-Q),ht=ve(q.left,q.right,Le.left,Le.right)):(me=Ze>ne,mt=Math.max(0,Le.top-q.bottom),pt=Math.abs(ze-Q),ht=ve(q.left,q.right,Le.left,Le.right)),!me)return Number.POSITIVE_INFINITY;const je=ht>0?0:120;return mt*3+pt+je};let _e=null,Ne=Number.POSITIVE_INFINITY;for(const Be of V){if(Be.id===L.id)continue;const Le=Ae(Be);Number.isFinite(Le)&&(Le>=Ne||(Ne=Le,_e=Be))}return _e||void 0},[]),G=o.useCallback(W=>{var V;const z=re(W);if(!z)return;const R=z.activePanel||z.panels[0];R&&(z.model.openPanel(R),R.api.setActive(),Rt(R.id)||ce(R.id,"dockview-focus"),Kn((V=z.element)==null?void 0:V.ownerDocument))},[re,ce]),Y=o.useCallback((W,z)=>{const R=j.current,V=R==null?void 0:R.activePanel,L=(R==null?void 0:R.activeGroup)||(V==null?void 0:V.group);if(!R||!V||!L)return;let q=re(W);!q&&(z!=null&&z.createGroupIfMissing)&&(q=R.addGroup({referenceGroup:L,direction:W})),q&&(V.api.moveTo({group:q,position:"center"}),V.group.model.openPanel(V),V.api.setActive(),Rt(V.id)||ce(V.id,z!=null&&z.createGroupIfMissing?"dockview-split":"dockview-move"))},[re,ce]),{isMac:le,tabShortcuts:ke,shortcutListening:Z,setShortcutListening:Ce,saveShortcuts:Pe}=xl({sortedTabKeys:e.map(W=>W.tabKey),onFocus:he,onSelectTab:se}),We=o.useCallback(()=>{var R;const W=j.current;if(!W)return;const z=W.activePanel;if(z){if(Rt(z.id)){const V=((R=z.params)==null?void 0:R.routeId)||z.id.slice(7),L=Pt(e,V);L!=null&&L.tabKey&&Ce(L.tabKey);return}U.has(z.id)&&Ce(z.id)}},[U,se,Ce,e]),He=o.useCallback(W=>{const z=[];return W.metaKey&&z.push(le?"⌘":"Meta"),W.ctrlKey&&z.push("Ctrl"),W.altKey&&z.push(le?"⌥":"Alt"),W.shiftKey&&W.key.length!==1&&z.push(le?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(W.key)?null:(z.push(vl(W.key)),z.join("+"))},[le]),D=o.useCallback(W=>{var z,R;switch(W){case"splitActiveTabRight":Y("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Y("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const V=de();V&&ge(V);return}case"popoutActiveTab":{const V=de();V&&fe(V);return}case"dockActiveTab":{const V=de();if(!V)return;J(V)?be(V):ee(V)&&we(V);return}case"focusLeftPane":G("left");return;case"focusRightPane":G("right");return;case"focusUpPane":G("above");return;case"focusDownPane":G("below");return;case"moveActiveTabToLeftPane":Y("left");return;case"moveActiveTabToRightPane":Y("right");return;case"moveActiveTabToUpPane":Y("above");return;case"moveActiveTabToDownPane":Y("below");return;case"selectPreviousGroupTab":ie(-1);return;case"selectNextGroupTab":ie(1);return;case"setActiveTabShortcut":We();return;case"hideCurrentTab":{const V=(R=(z=j.current)==null?void 0:z.activePanel)==null?void 0:R.id;V&&!Rt(V)&&ae(V);return}default:return}},[ie,we,G,ge,de,ae,ee,J,be,Y,fe,We]);o.useEffect(()=>{if(!N)return;const W=N.sourceDocument,z=W.defaultView??window,R=V=>{const L=W.querySelector("[data-dockview-tab-context-menu]");L&&L.contains(V.target)||M(null)};return z.addEventListener("mousedown",R,!0),z!==window&&window.addEventListener("mousedown",()=>M(null),!0),()=>{z.removeEventListener("mousedown",R,!0),z!==window&&window.removeEventListener("mousedown",()=>M(null),!0)}},[N]);const Se=o.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:U,hasDetachedConversationPanels:X,ides:r,isStandalone:c,hasRegisteredMachines:l,onOpenNewSession:k,liveSessionInboxState:I,sendDaemonCommand:a,setActionLogs:i,toggleHiddenTab:ae,userName:m,scrollToBottomRequest:y,tabShortcuts:ke,openTabContextMenu:({x:W,y:z,tabKey:R,sourceDocument:V})=>M({x:W,y:z,tabKey:R,sourceDocument:V??document}),popoutTab:fe,moveTabBackToMain:be,isTabInPopout:J,floatTab:ge,isTabFloating:ee}),[n,t,U,X,r,c,l,k,I,a,i,ae,m,y,ke,fe,be,J,ge,ee]),Ie=N?Hx({isTabInPopout:J(N.tabKey),isTabFloating:ee(N.tabKey),tabShortcut:ke[N.tabKey],actionShortcuts:h}):[],Re=o.useCallback(W=>{var V;const z=j.current;if((((V=z==null?void 0:z.activePanel)==null?void 0:V.id)??null)===W.id){W.group.model.openPanel(W);return}W.group.model.openPanel(W),W.api.setActive()},[]),Ee=o.useCallback((W,z="requested-tab")=>{if(!W)return!1;const R=j.current;if(!R)return!1;const V=R.getPanel(W);return V?(Re(V),ce(W,z),b==null||b(),!0):!1},[Re,b,ce]),Fe=o.useCallback(()=>{if(H.current)return!1;const W=Ee(F.current,"stored-layout-restore");return W&&(H.current=!0),W},[Ee]),Ue=o.useCallback(()=>{var z;const W=j.current;W&&Sh(g,{activeTabId:((z=W.activePanel)==null?void 0:z.id)??null,layout:W.toJSON()})},[g]),Je=o.useCallback(()=>{Ch(g,E.current)},[g]),dt=o.useCallback(W=>{var V,L,q,Q;const z=j.current;if(!z)return{kind:"grid"};const R=z.toJSON();for(const ne of R.floatingGroups||[])if((L=(V=ne.data)==null?void 0:V.views)!=null&&L.includes(W)&&ne.position)return{kind:"floating",position:ne.position};for(const ne of R.popoutGroups||[])if((Q=(q=ne.data)==null?void 0:q.views)!=null&&Q.includes(W))return{kind:"popout",position:ne.position,popoutUrl:ne.url};return{kind:"grid"}},[]),ut=o.useCallback(W=>{const z=j.current;if(!z)return;const R=z.getPanel(W),V=E.current[W];if(!R||!V||V.kind==="grid")return;if(R.group.model.location.type===V.kind){delete E.current[W],Je();return}if(V.kind==="floating"){z.addFloatingGroup(R,{x:V.position.left??24,y:V.position.top??24,width:V.position.width,height:V.position.height}),delete E.current[W],Je();return}delete E.current[W],Je()},[Je]);o.useEffect(()=>(f==null||f({setShortcutForActiveTab:We,restoreHiddenTabToSavedLocation:ut,activateConversationTab:se,resetAllPanelsToMain:ue,activatePreviousTabInGroup:()=>ie(-1),activateNextTabInGroup:()=>ie(1),floatActiveTab:()=>{const W=de();W&&ge(W)},popoutActiveTab:()=>{const W=de();W&&fe(W)},dockActiveTab:()=>{const W=de();W&&(J(W)?be(W):ee(W)&&we(W))},splitActiveTabRight:()=>Y("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Y("below",{createGroupIfMissing:!0}),focusLeftPane:()=>G("left"),focusRightPane:()=>G("right"),focusUpPane:()=>G("above"),focusDownPane:()=>G("below"),moveActiveTabToLeftPane:()=>Y("left"),moveActiveTabToRightPane:()=>Y("right"),moveActiveTabToUpPane:()=>Y("above"),moveActiveTabToDownPane:()=>Y("below")}),()=>f==null?void 0:f(null)),[ie,we,ge,G,de,ee,J,Y,be,fe,f,ue,ut,se,We]),o.useEffect(()=>()=>{var W;(W=K.current)==null||W.call(K),K.current=null},[]);const lt=o.useCallback(W=>{var R,V;j.current=W.api,(R=K.current)==null||R.call(K),K.current=null;const z=kh(g);if(F.current=(z==null?void 0:z.activeTabId)??null,z!=null&&z.layout&&W.api.fromJSON(z.layout,{reuseExistingPanels:!1}),C.current=oi({hasStoredLayout:!!(z!=null&&z.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:r}),C.current||(ui(W.api,e),mi(W.api,e,x)),W.api.totalPanels===0&&e.length>0){const L=Xx(W.api,e,S);if(L){const q=W.api.getPanel(L);q&&Re(q)}}else!C.current&&!Ee(S)&&Fe();if(_.current=!0,W.api.onDidActivePanelChange(L=>{var Q;if(F.current=(L==null?void 0:L.id)??null,H.current=!0,xe(),L&&Rt(L.id)){const ne=((Q=L.params)==null?void 0:Q.routeId)||L.id.slice(7),ve=Pt(e,ne);w((ve==null?void 0:ve.tabKey)??null),Ue();return}if(w((L==null?void 0:L.id)??null),Ue(),!L)return;const q=U.get(L.id);(q==null?void 0:q.streamSource)==="agent-stream"&&q.agentType&&A(q.routeId,uc(),{agentType:q.agentType,...q.sessionId&&{targetSessionId:q.sessionId}}).catch(()=>{})}),W.api.onDidLayoutChange(()=>{Ue(),xe(),$(L=>L+1)}),Vx()){const L=Ne=>({clientX:Ne.clientX,clientY:Ne.clientY}),q=Ne=>{const De=Ne==null?void 0:Ne.getBoundingClientRect();return De?{left:De.left,right:De.right,top:De.top,bottom:De.bottom}:null},Q=Ne=>{var Be;const De=(Be=v.current)==null?void 0:Be.getBoundingClientRect();return De?Ne.clientX<De.left||Ne.clientX>De.right||Ne.clientY<De.top||Ne.clientY>De.bottom:!1},ne=zx({detachDelayMs:jl,onDetach:({panelId:Ne,clientX:De,clientY:Be})=>{var ht,me;const Le=W.api.getPanel(Ne);if(!Le)return;try{if(Le.group.model.location.type!=="grid")return}catch{return}const ze=(ht=v.current)==null?void 0:ht.getBoundingClientRect(),Ze=(me=Le.group.element)==null?void 0:me.getBoundingClientRect(),mt=Math.round(Math.min(Math.max((Ze==null?void 0:Ze.width)??600,360),720)),pt=Math.round(Math.min(Math.max((Ze==null?void 0:Ze.height)??500,260),640));W.api.addFloatingGroup(Le,{x:ze?Math.max(0,De-ze.left-32):void 0,y:ze?Math.max(0,Be-ze.top-18):void 0,width:mt,height:pt}),Le.api.setActive(),Ue(),xe(),$(je=>je+1)}}),ve=[W.api.onWillDragPanel(Ne=>{if(!(Ne.nativeEvent.defaultPrevented||Ne.nativeEvent.shiftKey)){try{if(Ne.panel.group.model.location.type!=="grid")return}catch{return}ne.startDrag({panelId:Ne.panel.id,selfPanelBounds:q(Ne.panel.group.element),...L(Ne.nativeEvent)})}}),W.api.onWillShowOverlay(Ne=>{if(ne.hasDetached()){Ne.preventDefault();return}ne.markDockTarget(L(Ne.nativeEvent))}),W.api.onWillDrop(Ne=>{if(ne.hasDetached()){Ne.preventDefault(),ne.endDrag();return}ne.markDockTarget(L(Ne.nativeEvent))}),W.api.onDidDrop(()=>ne.endDrag()),W.api.onUnhandledDragOverEvent(Ne=>{ne.isDragging()&&ne.markSelfPanel(L(Ne.nativeEvent))})],Ae=Ne=>{if(!ne.isDragging())return;const De=L(Ne);Q(De)&&ne.markNonSelfPanel(De)},_e=()=>ne.endDrag();window.addEventListener("dragover",Ae,!0),window.addEventListener("drop",_e,!0),window.addEventListener("dragend",_e,!0),K.current=()=>{ne.dispose();for(const Ne of ve)Ne.dispose();window.removeEventListener("dragover",Ae,!0),window.removeEventListener("drop",_e,!0),window.removeEventListener("dragend",_e,!0)}}W.api.onDidAddGroup(L=>{requestAnimationFrame(()=>{var q,Q;try{const ne=(q=L.element)==null?void 0:q.ownerDocument;if(!ne||ne===document)return;(Q=ne.getElementById("dv-popout-window"))==null||Q.classList.add("adhdev-dockview");const ve=document.documentElement.getAttribute("data-theme");ve&&ne.documentElement.setAttribute("data-theme",ve),ne.body.className=document.body.className;const Ae=document.documentElement.getAttribute("style");Ae&&ne.documentElement.setAttribute("style",Ae)}catch{}xe(),$(ne=>ne+1)})}),w(((V=W.api.activePanel)==null?void 0:V.id)??null)},[Re,Ee,U,r,u,g,w,Ue,S,x,A,xe,e]);o.useLayoutEffect(()=>{const W=j.current;if(!W||!_.current||C.current&&oi({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:r}))return;C.current&&(C.current=!1);const z=P.current,R=new Set(z),V=e.map(_e=>_e.tabKey),L=new Set(V),q=Fx({previousVisibleConversationCount:z.length,visibleConversationCount:e.length,ides:r});let Q=!1;for(const _e of z)L.has(_e)||q||(E.current[_e]=dt(_e),Q=!0);Q&&Je(),q||(ui(W,e),mi(W,e,x));const ne=V.filter(_e=>!R.has(_e));let ve=!1;for(const _e of ne){const Ne=W.getPanel(_e),De=E.current[_e];if(!Ne||!De||De.kind==="grid")continue;if(Ne.group.model.location.type===De.kind){delete E.current[_e],ve=!0;continue}if(De.kind==="floating"){W.addFloatingGroup(Ne,{x:De.position.left??24,y:De.position.top??24,width:De.position.width,height:De.position.height}),delete E.current[_e],ve=!0;continue}}if(ve&&Je(),P.current=V,S&&Ee(S))return;!W.activePanel&&W.panels[0]&&Re(W.panels[0]),!!(W.activePanel&&W.getPanel(W.activePanel.id))||Fe()},[Re,Ee,Fe,r,u,Je,dt,S,x,e]),o.useEffect(()=>{_.current&&Ee(S)},[Ee,S]),o.useEffect(()=>{const W=R=>{const V=R.target;if(!V)return;const L=V.querySelector("[data-tab-key]")||V.closest("[data-tab-key]");if(L){const q=L.getAttribute("data-tab-key");if(q&&R.dataTransfer){const Q=V.closest(".dv-tab")||L.closest(".dv-tab")||L;R.dataTransfer.effectAllowed="move",R.dataTransfer.setData("text/tab-key",q),Q instanceof HTMLElement&&R.dataTransfer.setDragImage(Q,Math.max(12,Math.round(Q.clientWidth/2)),Math.max(10,Math.round(Q.clientHeight/2)))}}};window.addEventListener("dragstart",W);const z=di(j.current);for(const R of z)R.addEventListener("dragstart",W);return()=>{window.removeEventListener("dragstart",W);for(const R of z)R.removeEventListener("dragstart",W)}},[O]),o.useEffect(()=>{var z;const W=(z=v.current)==null?void 0:z.querySelector(".adhdev-dockview");W instanceof HTMLElement&&On(W,T),ye(),xe()},[xe,ye,T]),o.useEffect(()=>{xe()},[xe]),o.useEffect(()=>{const W=z=>{if(z.defaultPrevented||Z)return;const R=He(z);if(!R)return;const V=z.metaKey||z.ctrlKey||z.altKey;ya(z.target)&&!V||Zr(le).setActiveTabShortcut!==R||(z.preventDefault(),z.stopPropagation(),We())};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[He,le,Z,We]),o.useEffect(()=>{const W=v.current;if(!W)return;const z=R=>{var ne,ve;if(!R.isTrusted)return;const V=(ve=(ne=R.target)==null?void 0:ne.closest)==null?void 0:ve.call(ne,".dv-scrollable");if(!V)return;R.preventDefault(),R.stopPropagation();const L=Math.abs(R.deltaX),q=Math.abs(R.deltaY),Q=L>q?R.deltaX:R.deltaY;V.dispatchEvent(new WheelEvent("wheel",{deltaY:Q,deltaMode:R.deltaMode,bubbles:!1,cancelable:!0}))};return W.addEventListener("wheel",z,{passive:!1,capture:!0}),()=>W.removeEventListener("wheel",z,{capture:!0})},[]),o.useEffect(()=>{const W=di(j.current);if(W.length===0)return;const z=W.map(R=>{let V=[],L=null;const q=()=>{L!=null&&R.clearTimeout(L),L=null,V=[]},Q=()=>{L!=null&&R.clearTimeout(L),L=R.setTimeout(()=>{L=null,V=[]},1200)},ne=Ae=>{if(!Ae.ctrlKey&&!Ae.metaKey&&!Ae.altKey)return;const _e=He(Ae);if(!_e)return;const Ne=hl();for(const[De,Be]of Object.entries(Ne))if(e.some(Le=>Le.tabKey===De)&&Be===_e){Ae.preventDefault(),se(De);return}},ve=Ae=>{if(Ae.defaultPrevented||Z)return;const _e=He(Ae);if(!_e)return;const Ne=Ae.metaKey||Ae.ctrlKey||Ae.altKey;if(ya(Ae.target))return;const De=Zr(le),Be=Object.entries(De).filter(([je,bt])=>!!bt&&(je==="splitActiveTabRight"||je==="splitActiveTabDown"||je==="floatActiveTab"||je==="popoutActiveTab"||je==="dockActiveTab"||je==="focusLeftPane"||je==="focusRightPane"||je==="focusUpPane"||je==="focusDownPane"||je==="moveActiveTabToLeftPane"||je==="moveActiveTabToRightPane"||je==="moveActiveTabToUpPane"||je==="moveActiveTabToDownPane"||je==="selectPreviousGroupTab"||je==="selectNextGroupTab"||je==="setActiveTabShortcut"||je==="hideCurrentTab")),Le=Ne?[_e]:[...V.slice(-1),_e].slice(-2),ze=Le.join(" "),Ze=Le[Le.length-1],mt=Be.find(([,je])=>je===ze);if(mt){Ae.preventDefault(),q(),D(mt[0]);return}if(Be.some(([,je])=>je.startsWith(`${ze} `))){Ae.preventDefault(),V=Le,Q();return}const ht=Be.find(([,je])=>je===Ze);if(ht){Ae.preventDefault(),q(),D(ht[0]);return}if(Be.some(([,je])=>je.startsWith(`${Ze} `))){Ae.preventDefault(),V=[Ze],Q();return}q()};return R.addEventListener("keydown",ne),R.addEventListener("keydown",ve),()=>{q(),R.removeEventListener("keydown",ne),R.removeEventListener("keydown",ve)}});return()=>{for(const R of z)R()}},[He,le,O,se,Z,D,e]);const Te=T==="light"?ea:ta,Ge=((tt=(qe=(Qe=j.current)==null?void 0:Qe.activePanel)==null?void 0:qe.group.element)==null?void 0:tt.ownerDocument)??document;return s.jsxs(kl.Provider,{value:Se,children:[s.jsx("div",{ref:v,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(ud,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Jx,remote:Qx},defaultTabComponent:eb,watermarkComponent:Zx,onReady:lt,singleTabMode:"default",tabAnimation:"smooth",theme:Te,popoutUrl:"/popout.html"})}),N&&er.createPortal(s.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:N.x,top:N.y},children:Ie.map(W=>{if(W.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},W.id);let z=s.jsx(ou,{size:13,className:"shrink-0 opacity-70"}),R=()=>{};switch(W.id){case"dockInWindow":case"dockBackToGrid":z=s.jsx(cu,{size:13,className:"shrink-0 opacity-70"}),R=()=>{we(N.tabKey),M(null)};break;case"moveBackToMain":z=s.jsx(au,{size:13,className:"shrink-0 opacity-70"}),R=()=>{be(N.tabKey),M(null)};break;case"floatAsPanel":z=s.jsx(iu,{size:13,className:"shrink-0 opacity-70"}),R=()=>{ge(N.tabKey),M(null)};break;case"openInNewWindow":z=s.jsx(nu,{size:13,className:"shrink-0 opacity-70"}),R=()=>{fe(N.tabKey),M(null)};break;case"setShortcut":R=V=>{V.stopPropagation(),Ce(N.tabKey),M(null)};break;case"removeShortcut":z=s.jsx(St,{size:13,className:"shrink-0 opacity-70"}),R=()=>{const V={...ke};delete V[N.tabKey],Pe(V),M(null)};break;case"hideTab":z=s.jsx(Aa,{size:13,className:"shrink-0 opacity-70"}),R=()=>{ae(N.tabKey),M(null)};break}return s.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 ${W.tone==="muted"?"text-text-muted":""}`,onMouseDown:qx,onClick:R,children:[z,s.jsx("span",{className:"flex-1 min-w-0",children:W.label}),W.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:W.shortcut}):null]},W.id)})}),N.sourceDocument.body),Z&&er.createPortal(s.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:()=>Ce(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:W=>W.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",le?"⌘+1":"Ctrl+1",", ",le?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Ge.body)]})}const Sl="adhdev-recent-launch-args-v1",sb=8;function rb(e){return String(e||"").trim().replace(/\s+/g," ")}function Nl(e,t){return`${e.trim()}::${t.trim()}`}function Cl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Sl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function nb(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Sl,JSON.stringify(e))}catch{}}function Tl(e,t){var i;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((i=Cl().byKey[Nl(r,n)])==null?void 0:i.items)||[]}function Al(e,t,r){var d;const n=String(e||"").trim(),a=String(t||"").trim(),i=rb(r);if(!n||!a||!i)return;const c=Cl(),l=Nl(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],m=[i,...u.filter(h=>h!==i)].slice(0,sb);c.byKey[l]={items:m},nb(c)}function Il(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Kr({title:e,description:t,action:r,children:n,className:a="",contentClassName:i=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function ab({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:r=0}){return e?"Refreshing saved history…":t?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 Ml({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:i,onRefresh:c,onOpenHistory:l,onClearSelection:u}){const m=i?ml(i):null,d=ab({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(Kr,{title:"Saved history",description:Va(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:c,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:l,children:ip()})]}),children:[m?s.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:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:m.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),s.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:u,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:d}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Wn(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>fs(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>fs(a,"acp"))?"acp":null}function Ir(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ob({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:i,onLaunchProvider:c,onListSavedSessions:l}){var W,z;const u=dr(),m=o.useMemo(()=>[...e].sort(Pa),[e]),[d,h]=o.useState(((W=m[0])==null?void 0:W.id)||""),f=o.useMemo(()=>m.find(R=>R.id===d)||m[0],[d,m]),w=o.useMemo(()=>((f==null?void 0:f.workspaces)||[]).map(R=>({id:R.id,path:R.path,label:R.label})),[f]),k=(f==null?void 0:f.defaultWorkspaceId)||null,[p,S]=o.useState(""),[x,b]=o.useState(""),[y,I]=o.useState(Wn(m[0])),[g,T]=o.useState(""),[A,j]=o.useState(""),[v,K]=o.useState([]),[_,C]=o.useState(""),[H,F]=o.useState([]),[P,N]=o.useState(!1),[M,O]=o.useState(!1),[$,E]=o.useState(""),[U,X]=o.useState(!1),[he,ce]=o.useState(()=>xt()),[te,ye]=o.useState(null),[fe,be]=o.useState(!1),[J,ae]=o.useState(""),[ge,ee]=o.useState(!1),[de,we]=o.useState(""),[ue,xe]=o.useState([]),[se,ie]=o.useState(!1),[re,G]=o.useState(""),[Y,le]=o.useState(!1),ke=o.useRef(null),Z=o.useRef(0);o.useEffect(()=>{var R;!d&&((R=m[0])!=null&&R.id)&&h(m[0].id)},[d,m]),o.useEffect(()=>{!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||u(f.id,{minFreshMs:3e4}).catch(()=>{})},[u,f]);const Ce=o.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(R=>fs(R,"cli")),[f]),Pe=o.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(R=>fs(R,"acp")),[f]),We=o.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(R=>({id:R.type,label:R.name||R.type,meta:R.running?"Detected locally":"Available to open"})),[f]),He=o.useMemo(()=>y==="cli"?Ce.map(R=>({id:R.type,label:R.displayName||R.type,meta:"CLI provider"})):y==="acp"?Pe.map(R=>({id:R.type,label:R.displayName||R.type,meta:"ACP provider"})):We,[Pe,y,Ce,We]);o.useEffect(()=>{var V;if(!f)return;if(ke.current!==f.id){ke.current=f.id,S(k||((V=w[0])==null?void 0:V.id)||"__home__"),b(""),I(Wn(f)),T(""),j(""),C(""),F([]),O(!1),E(""),ce(xt()),ae("");return}S(L=>{var q;return L==="__custom__"||L==="__home__"||w.some(Q=>Q.id===L)?L:k||((q=w[0])==null?void 0:q.id)||"__home__"}),I(L=>L==="ide"&&We.length>0||L==="cli"&&Ce.length>0||L==="acp"&&Pe.length>0?L:Wn(f))},[Pe.length,Ce.length,k,We.length,f,w]),o.useEffect(()=>{var R;y&&(He.some(V=>V.id===g)||T(((R=He[0])==null?void 0:R.id)||""))},[y,He,g]);const D=o.useCallback(async(R,V)=>{const L=Z.current+1;return Z.current=L,N(!0),E(""),l(R,V).then(q=>{Z.current===L&&F(q)}).catch(q=>{Z.current===L&&(F([]),E(q instanceof Error?q.message:"Could not load saved sessions"))}).finally(()=>{Z.current===L&&(N(!1),O(!0))})},[l]),Se=o.useCallback((R,V)=>{K(Tl(R,V))},[]);o.useEffect(()=>{Z.current+=1,C(""),ce(xt()),!f||!g||y==="ide"?K([]):Se(f.id,g),O(!1),F([]),E(""),N(!1)},[y,Se,D,f,g]),o.useEffect(()=>{if(!_)return;const R=H.find(V=>V.providerSessionId===_);R!=null&&R.canResume||C("")},[H,_]);const Ie=p==="__custom__"?x.trim():p==="__home__"?"":((z=w.find(R=>R.id===p))==null?void 0:z.path)||"",Re=o.useMemo(()=>f?t.filter(R=>R.id!==f.id&&R.daemonId===f.id).map(R=>R.workspace):[],[t,f]),Ee=o.useMemo(()=>((f==null?void 0:f.recentLaunches)||[]).map(R=>R.workspace),[f]),Fe=o.useCallback(R=>{const V=String(R.workspace||"").trim();if(!V)return;const L=w.find(q=>Ir(q.path)===Ir(V));if(L){S(L.id),b("");return}S("__custom__"),b(V)},[w]),Ue=o.useCallback(R=>{const V=String(R.workspace||"").trim();if(!V)return{workspaceId:null,workspacePath:null};const L=w.find(q=>Ir(q.path)===Ir(V));return L?{workspaceId:L.id,workspacePath:null}:{workspaceId:null,workspacePath:V}},[w]),Je=o.useMemo(()=>H.find(R=>R.providerSessionId===_)||null,[H,_]),dt=o.useMemo(()=>{var V;if(y!=="cli"||!f||!g)return null;const R=((V=Ce.find(L=>L.type===g))==null?void 0:V.displayName)||g;return{routeId:f.id,daemonId:f.id,providerSessionId:_||void 0,transport:"pty",mode:"chat",agentName:R,agentType:g,status:"idle",title:R,messages:[],ideType:g,workspaceName:Ie,workspacePath:Ie,displayPrimary:R,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${f.id}:${g}`,machineName:Ct(f,{fallbackId:f.id})}},[y,Ce,Ie,f,_,g]),ut=o.useCallback(()=>{var V;if(!f)return;S("__custom__"),ee(!0),G("");const R=dn(f.platform,ln(x.trim(),Ie,Re,Ee,f.defaultWorkspacePath,(V=w.find(L=>L.id===k))==null?void 0:V.path,w.map(L=>L.path)));ie(!0),n(f.id,R).then(L=>{we(L.path),b(L.path),xe(L.directories)}).catch(L=>{G(L instanceof Error?L.message:"Could not load folder")}).finally(()=>ie(!1))},[x,k,Ee,Re,n,Ie,f,w]),lt=o.useCallback(R=>{f&&(ie(!0),G(""),n(f.id,R).then(V=>{we(V.path),b(V.path),xe(V.directories)}).catch(V=>{G(V instanceof Error?V.message:"Could not load folder")}).finally(()=>ie(!1)))},[n,f]),Te=o.useCallback(async()=>{if(!f||!Ie)return;le(!0),ae("");const R=await a(f.id,Ie);if(le(!1),!R.ok){ae(R.error||"Could not save workspace");return}ae("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,Ie,f]),Ge=o.useCallback(async()=>{if(!f||!y||!g)return;be(!0),ae("");const R=A.trim()?A.trim().split(/\s+/).filter(Boolean):[],V=y==="ide"?await i(f.id,g,{workspacePath:Ie||null}):await c(f.id,y,g,{workspaceId:p!=="__home__"&&p!=="__custom__"?p:null,workspacePath:p==="__custom__"&&Ie||null,resumeSessionId:y==="cli"&&_?_:null,cliArgs:R});if(be(!1),!V.ok){ae(V.error||"Could not start session");return}y!=="ide"&&A.trim()&&(Al(f.id,g,A),Se(f.id,g)),r()},[y,A,Se,r,i,c,Ie,f,_,g,p]),Qe=y?Dc(y,y==="cli"&&!!_):"Start",qe=y?Ec(y,y==="cli"&&!!_):"Starting…",tt=m.length>5;return f?s.jsxs(s.Fragment,{children:[s.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:s.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:[s.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:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.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."})]}),s.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:s.jsx(St,{size:16})})]}),s.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:[s.jsx(Kr,{title:"Machine",children:tt?s.jsx("select",{"aria-label":"Machine",value:f.id,onChange:R=>h(R.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:fe,children:m.map(R=>s.jsx("option",{value:R.id,children:Ct(R,{fallbackId:R.id})},R.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:m.map(R=>{const V=Ct(R,{fallbackId:R.id}),L=f.id===R.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${V}`,"aria-pressed":L,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${L?"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:()=>h(R.id),disabled:fe,title:V,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${R.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:V})]},R.id)})})}),s.jsxs(Kr,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ut,disabled:fe,children:"Browse…"}),children:[s.jsxs("select",{value:p,onChange:R=>{const V=R.target.value;S(V),V==="__custom__"?ut():ae("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:fe,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),w.map(R=>s.jsxs("option",{value:R.id,children:[R.id===k?"⭐ ":"",an(R.path,R.label)||R.path]},R.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:p==="__home__"?"Launch without a workspace.":Ie||"Select a workspace folder."}),p==="__custom__"&&Ie&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ut,disabled:fe,children:[s.jsx(Cs,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Te,disabled:fe||Y,children:Y?"Saving…":"Save workspace"})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:Ce.length>0},{id:"ide",label:"IDE",enabled:We.length>0},{id:"acp",label:"ACP",enabled:Pe.length>0}].map(R=>s.jsx("button",{type:"button",className:`btn btn-sm ${y===R.id?"btn-primary":"btn-secondary"}`,onClick:()=>I(R.id),disabled:!R.enabled||fe,children:R.label},R.id))})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:y==="ide"?"Choose IDE":y==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[He.map(R=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${g===R.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>T(R.id),disabled:fe,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:R.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:R.meta})]},R.id)),He.length===0&&s.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."})]})]}),y!=="ide"&&s.jsxs(Kr,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:A,onChange:R=>j(R.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:fe}),v.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:v.map(R=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>j(R),disabled:fe,title:R,children:R},R))})]}),y==="cli"&&s.jsx(Ml,{busy:fe,savedSessionsLoading:P,savedSessionsError:$,selectedSession:Je,onRefresh:()=>{!f||!g||D(f.id,g)},onOpenHistory:()=>{!f||!g||(X(!0),Il({hasLoadedInitialResults:M,isLoading:P})&&D(f.id,g))},onClearSelection:()=>C("")}),J&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${J.includes("saved")||J.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:J})]}),s.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:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:fe,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:Ge,disabled:fe||!y||!g||p==="__custom__"&&!Ie,children:[s.jsx(Ma,{size:14}),fe?qe:Qe]})]})]})}),ge&&s.jsx(mn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:de,directories:ue,busy:se,error:re,onClose:()=>ee(!1),onNavigate:lt,onConfirm:R=>{b(R),we(R),S("__custom__"),ee(!1)}}),U&&dt&&s.jsx(Ya,{activeConv:dt,ides:[],isCreatingChat:!1,isRefreshingHistory:P,savedSessions:H,isSavedSessionsLoading:P,isResumingSavedSessionId:te,savedHistoryFilters:he,missingWorkspaceResumePath:Ie||null,onSavedHistoryFiltersChange:ce,onClose:()=>X(!1),onNewChat:()=>{C(""),X(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!f||!g||D(f.id,g)},onResumeSavedSession:R=>{if(!f||!g||te||!R.canResume)return;const V=Ue(R);C(R.providerSessionId),Fe(R),ye(R.providerSessionId),X(!1),be(!0),ae(""),c(f.id,"cli",g,{workspaceId:V.workspaceId,workspacePath:V.workspacePath,resumeSessionId:R.providerSessionId}).then(L=>{if(!L.ok){ae(L.error||"Could not resume session");return}r()}).finally(()=>{be(!1),ye(L=>L===R.providerSessionId?null:L)})}})]}):null}function ib(e,t){const{sendCommand:r}=ft(),[n,a]=o.useState(null),[i,c]=o.useState(!1);o.useEffect(()=>{if(!e||!t){a(null);return}c(!0),r(e,"git_remote_url",{workspace:t}).then(u=>{const m=(u==null?void 0:u.result)??u;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>c(!1))},[e,t,r]);const l=cb(n);return{remoteUrl:n,githubUrl:l,loading:i}}function cb(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const Rl=5e3;function lb(e){return`git:${e}`}function db({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Rl}){return{type:"subscribe",topic:"workspace.git",key:lb(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function oo(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function ps(e,t){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 t}function ub(e){const t=oo(e);return(t==null?void 0:t.success)===!1?{status:null,error:ps(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:ps(t,"Git status response did not include status")}}function mb(e){const t=oo(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:ps(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:ps(t,"Git diff summary response did not include diffSummary")}}function Hn(e){return e===void 0||typeof e=="boolean"}function fb(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Hn(t.binary)&&Hn(t.truncated)&&Hn(t.staged)}function pb(e){const t=oo(e);return(t==null?void 0:t.success)===!1?{diff:null,error:ps(t,"Git file diff request failed")}:fb(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:ps(t,"Git file diff response did not include a valid diff object")}}function hb({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Rl}){const{sendCommand:i,sendData:c}=ft(),l=typeof t=="string"?t.trim():"",u=!!(r&&e&&l),[m,d]=o.useState(null),[h,f]=o.useState(null),[w,k]=o.useState(!1),[p,S]=o.useState(null),x=o.useCallback(async()=>{if(!(!u||!e||!l)){k(!0),S(null);try{const y=ub(await i(e,"git_status",{workspace:l}));if(y.error){d(null),f(null),S(y.error);return}if(d(y.status),!n){f(null);return}const I=mb(await i(e,"git_diff_summary",{workspace:l}));if(I.error){f(null),S(I.error);return}f(I.diffSummary)}catch(y){S(ps(y,"Git status request failed"))}finally{k(!1)}}},[u,e,n,i,l]),b=o.useMemo(()=>l?db({workspace:l,includeDiffSummary:n,intervalMs:a}):null,[n,a,l]);return o.useEffect(()=>{if(!u||!e||!l||!b){d(null),f(null),k(!1),S(null);return}const y=c?Ht.subscribe({sendData:c},e,b,I=>{var g,T;I.workspace===l&&(d(I.status),f(I.diffSummary??null),S(((g=I.status)==null?void 0:g.error)||((T=I.diffSummary)==null?void 0:T.error)||null),k(!1))},{retryIntervalMs:1e3}):null;return x(),()=>{y==null||y()}},[u,e,x,b,c,l]),{status:m,diffSummary:h,loading:w,error:p,refresh:x}}const xb={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},bb={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 fi(e){return e.split("/").pop()??e}function gb(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function yb({files:e,truncated:t,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${a}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(i=>{const c=n===i.path,l=xb[i.status]??"?",u=bb[i.status]??"text-zinc-400",m=gb(i.path),d=fi(i.path),h=i.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.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:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${u}`,title:i.status,children:l}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:d}),i.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",fi(i.oldPath)]}),h]}),!i.binary&&(i.insertions>0||i.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[i.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",i.insertions]}),i.insertions>0&&i.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),i.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",i.deletions]})]}),i.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${i.path}-${i.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function vb(e,t){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"),s.jsx("div",{className:`px-3 ${r}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function wb({diff:e,binary:t,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 s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${i}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${i}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${i}`,children:"No diff available."});const l=e.split(`
|
|
63
|
+
`);return s.jsxs("div",{ref:c,className:`overflow-auto ${i}`,children:[s.jsx("div",{className:"py-1",children:l.map((u,m)=>vb(u,m))}),r&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function jb(e,t){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const n={};for(const a of t.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 Ll({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=ft(),{status:a,diffSummary:i,loading:c,error:l,refresh:u}=hb({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,d]=o.useState(null),[h,f]=o.useState(null),[w,k]=o.useState(""),[p,S]=o.useState(!1),[x,b]=o.useState(!1),[y,I]=o.useState(null),[g,T]=o.useState(null),{githubUrl:A}=ib(e,t),j=o.useCallback(async F=>{if(!((m==null?void 0:m.path)===F.path&&!m.loading)){d({path:F.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const P=await n(e,"git_diff_file",{workspace:t,path:F.path,staged:F.staged}),N=pb(P);if(N.error||!N.diff){d({path:F.path,diff:"",binary:!1,truncated:!1,loading:!1,error:N.error??"Failed to load diff"});return}d({path:F.path,diff:N.diff.diff,binary:N.diff.binary??!1,truncated:N.diff.truncated??!1,loading:!1,error:null})}catch(P){const N=P instanceof Error?P.message:"Failed to load diff";d({path:F.path,diff:"",binary:!1,truncated:!1,loading:!1,error:N})}}},[e,n,m,t]),v=o.useCallback(F=>{k(""),S(!1),I(null),T(null),f(F)},[]),K=o.useCallback(()=>{f(null),I(null),b(!1)},[]),_=o.useCallback(async()=>{var F,P,N;if(h){b(!0),I(null);try{let M;h==="checkpoint"?M=await n(e,"git_checkpoint",{workspace:t,message:w,includeUntracked:p}):h==="stash"?M=await n(e,"git_stash_push",{workspace:t,message:w,includeUntracked:p}):h==="stash_pop"?M=await n(e,"git_stash_pop",{workspace:t}):h==="checkout_files"&&m&&(M=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const O=(M==null?void 0:M.result)??M;if((O==null?void 0:O.success)===!1||O!=null&&O.error){I((O==null?void 0:O.error)??"Action failed"),b(!1);return}h==="checkpoint"?T(`Checkpoint created: ${((P=(F=O==null?void 0:O.checkpoint)==null?void 0:F.commit)==null?void 0:P.slice(0,7))??"done"}`):h==="stash"?T(`Stashed as ${((N=O==null?void 0:O.stash)==null?void 0:N.stashRef)??"stash@{0}"}`):h==="stash_pop"?T("Stash restored"):(T("File reverted"),d(null)),f(null),await u()}catch(M){I(M instanceof Error?M.message:"Action failed")}finally{b(!1)}}},[h,n,e,t,w,p,m,u]),C=!!(a!=null&&a.hasConflicts),H=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:F=>{F.target===F.currentTarget&&r()},children:s.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:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),A&&s.jsx("a",{href:`${A}/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 ↗"})]}),s.jsx("button",{onClick:u,disabled:c,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(St,{className:"h-4 w-4"})})]}),a&&s.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&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),H===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),i&&i.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[i.files.length," file",i.files.length!==1?"s":"",i.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",i.totalInsertions]}),i.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",i.totalDeletions]})]})]}),l&&s.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}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[c&&!i&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),i&&s.jsx(yb,{files:i.files,truncated:i.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:j}),!c&&!i&&!l&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?s.jsx(wb,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),g&&s.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:[s.jsx("span",{children:g}),s.jsx("button",{onClick:()=>T(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>v("checkpoint"),disabled:C,title:C?"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"}),s.jsx("button",{onClick:()=>v("stash"),disabled:C,title:C?"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"}),s.jsx("button",{onClick:()=>v("stash_pop"),disabled:C||!(a!=null&&a.stashCount),title:C?"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"}),s.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&&s.jsx("button",{onClick:()=>{const F=jb((a==null?void 0:a.branch)??null,i);navigator.clipboard.writeText(F),T("Copied to clipboard"),setTimeout(()=>T(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),h&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[h==="checkpoint"&&"Create checkpoint commit",h==="stash"&&"Stash changes",h==="stash_pop"&&"Restore latest stash?",h==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(h==="checkpoint"||h==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:w,onChange:F=>k(F.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}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:p,onChange:F=>S(F.target.checked)}),"Include untracked files"]})]}),y&&s.jsx("p",{className:"text-xs text-red-400",children:y}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:K,disabled:x,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:_,disabled:x||(h==="checkpoint"||h==="stash")&&!w.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:x?"Working…":"Confirm"})]})]})})]})})}function kb({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=o.useState(!1),[i,c]=o.useState(!1),[l,u]=o.useState(!1),[m,d]=o.useState(!1),[h,f]=o.useState(!1),[w,k]=o.useState("quickstart"),[p,S]=o.useState("workspace"),x=o.useMemo(()=>!t&&!e,[t,e]),b=o.useCallback(j=>{a(j),j&&c(!1)},[]),y=o.useCallback(j=>{c(j),j&&a(!1)},[]),I=o.useCallback(()=>{k(r===0?"quickstart":"shortcuts"),S("workspace"),u(!0),a(!1),c(!1)},[r]),g=o.useCallback(()=>{u(!1)},[]),T=o.useCallback(()=>{d(!0)},[]),A=o.useCallback(()=>{d(!1)},[]);return o.useEffect(()=>{if(!x){f(!1);return}f(!0);const j=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(j)},[x]),{inboxOpen:n,hiddenOpen:i,shortcutHelpOpen:l,newSessionOpen:m,guideNudgeVisible:h,guideTab:w,shortcutSection:p,isDesktopDashboard:x,setGuideTab:k,setShortcutSection:S,handleInboxOpenChange:b,handleHiddenOpenChange:y,handleOpenShortcutHelp:I,closeShortcutHelp:g,openNewSession:T,closeNewSession:A}}function Sb(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 Nb(e){return e instanceof Error?e.message:String(e||"")}function Cb(e){const t=Nb(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Tb({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetActiveCliViewMode:m,mobileChatConversations:d,hiddenConversations:h,ides:f,actionLogs:w,sendDaemonCommand:k,setActionLogs:p,setCliViewModeOverrides:S,isStandalone:x,initialDataLoaded:b,userName:y,requestedMobileTabKey:I,onRequestedMobileTabConsumed:g,requestedMachineId:T,onRequestedMachineConsumed:A,requestedMobileSection:j,onRequestedMobileSectionConsumed:v,containerRef:K,isSplitMode:_,numGroups:C,groupSizes:H,groupedConvs:F,clearedTabs:P,focusedGroup:N,focusGroup:M,moveTabToGroup:O,splitTabRelative:$,closeGroup:E,handleResizeStart:U,groupActiveTabIds:X,setGroupActiveTab:he,groupTabOrders:ce,setGroupTabOrder:te,toggleHiddenTab:ye,visibleConversations:fe,requestedDesktopTabKey:be,onRequestedDesktopTabConsumed:J,onDesktopActiveTabChange:ae,onRequestScrollToBottom:ge,onHideConversation:ee,onShowHiddenConversation:de,onShowAllHiddenConversations:we,scrollToBottomRequest:ue,machineEntries:xe,layoutProfile:se,onBrowseMachineDirectory:ie,onSaveMachineWorkspace:re,onLaunchMachineIde:G,onLaunchMachineProvider:Y,onListMachineSavedSessions:le,notifications:ke,notificationUnreadCount:Z,liveSessionInboxState:Ce,onMarkNotificationRead:Pe,onMarkNotificationUnread:We,onDeleteNotification:He}){const D=kt.useRef(null),{inboxOpen:Se,hiddenOpen:Ie,shortcutHelpOpen:Re,newSessionOpen:Ee,guideNudgeVisible:Fe,guideTab:Ue,shortcutSection:Je,isDesktopDashboard:dt,setGuideTab:ut,setShortcutSection:lt,handleInboxOpenChange:Te,handleHiddenOpenChange:Ge,handleOpenShortcutHelp:Qe,closeShortcutHelp:qe,openNewSession:tt,closeNewSession:W}=kb({isMobile:t,showMobileChatMode:e,visibleConversationCount:fe.length}),[z,R]=kt.useState(null),V=kt.useCallback((me,je)=>{R({daemonId:me,workspace:je})},[]),L=kt.useCallback(me=>{var je;er.flushSync(()=>{de(me)}),(je=D.current)==null||je.restoreHiddenTabToSavedLocation(me.tabKey)},[de]),q=kt.useCallback(me=>{var bt;const je=d.find(wt=>da(wt,me))||h.find(wt=>da(wt,me));je&&(h.some(wt=>wt.tabKey===je.tabKey)&&L(je),ae(je.tabKey),(bt=D.current)==null||bt.activateConversationTab(je.tabKey),ge(je.tabKey,"notification-open")),Pe(me.id),Te(!1)},[L,h,d,ae,Pe,ge]),Q=kt.useCallback(()=>{var je;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((je=D.current)==null||je.resetAllPanelsToMain(),Ge(!1))},[Ge]),ne=kt.useCallback(async me=>{var oe;if(!r)return;const je=(oe=r.modalButtons)==null?void 0:oe[me];if(!je)return;const bt=As(r);if(!bt)return;const wt=je.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),B=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(wt);try{await k(bt,"resolve_action",{button:je,action:B?"approve":"reject",buttonIndex:me,...Zt(r)})}catch(pe){Cb(pe)||console.error("[Shortcut approval] Failed:",pe)}},[r,k]),{isMac:ve,actionDefinitions:Ae,actionShortcuts:_e,shortcutListening:Ne,shortcutListeningDraft:De,setShortcutListening:Be,setShortcutListeningDraft:Le,saveShortcuts:ze}=Wx({enabled:dt&&!Re,onTrigger:me=>{var je,bt,wt,B,oe,pe,Ke,Me,$e,nt,jt,ct,Ut,mr,fr,pr;if(me==="openShortcutHelp"){Qe();return}if(me==="openNewSession"){tt();return}if(me==="hideCurrentTab"){r&&ee(r);return}if(me==="toggleHiddenTabs"){Ge(!Ie);return}if(me==="openHistoryForActiveTab"){r&&!Xe(r)&&i(r);return}if(me==="openRemoteForActiveTab"){r&&!et(r)&&!Xe(r)&&c(r);return}if(me==="splitActiveTabRight"){(je=D.current)==null||je.splitActiveTabRight();return}if(me==="splitActiveTabDown"){(bt=D.current)==null||bt.splitActiveTabDown();return}if(me==="floatActiveTab"){(wt=D.current)==null||wt.floatActiveTab();return}if(me==="popoutActiveTab"){(B=D.current)==null||B.popoutActiveTab();return}if(me==="dockActiveTab"){(oe=D.current)==null||oe.dockActiveTab();return}if(me==="focusLeftPane"){(pe=D.current)==null||pe.focusLeftPane();return}if(me==="focusRightPane"){(Ke=D.current)==null||Ke.focusRightPane();return}if(me==="focusUpPane"){(Me=D.current)==null||Me.focusUpPane();return}if(me==="focusDownPane"){($e=D.current)==null||$e.focusDownPane();return}if(me==="moveActiveTabToLeftPane"){(nt=D.current)==null||nt.moveActiveTabToLeftPane();return}if(me==="moveActiveTabToRightPane"){(jt=D.current)==null||jt.moveActiveTabToRightPane();return}if(me==="moveActiveTabToUpPane"){(ct=D.current)==null||ct.moveActiveTabToUpPane();return}if(me==="moveActiveTabToDownPane"){(Ut=D.current)==null||Ut.moveActiveTabToDownPane();return}if(me==="triggerPrimaryApprovalAction"){ne(0);return}if(me==="triggerSecondaryApprovalAction"){ne(1);return}if(me==="triggerTertiaryApprovalAction"){ne(2);return}if(me==="setActiveTabShortcut"){(mr=D.current)==null||mr.setShortcutForActiveTab();return}if(me==="selectPreviousGroupTab"){(fr=D.current)==null||fr.activatePreviousTabInGroup();return}if(me==="selectNextGroupTab"){(pr=D.current)==null||pr.activateNextTabInGroup();return}!r||!et(r)||Xe(r)||me==="toggleCliView"&&m(u==="chat"?"terminal":"chat")}}),Ze=kt.useCallback(()=>{qe(),Be(null),Le([])},[qe,Be,Le]),mt=kt.useMemo(()=>Je==="all"?Ae:Ae.filter(me=>Sb(me)===Je),[Ae,Je]),pt=kt.useCallback(()=>{const me=Object.fromEntries(Ae.map(je=>[je.id,""]));ze(me)},[Ae,ze]),ht=kt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const me=Object.fromEntries(Ae.map(je=>[je.id,je.defaultShortcut]));ze(me)},[Ae,ze]);return kt.useEffect(()=>{const me=je=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?je.metaKey&&je.key.toLowerCase()==="w":je.ctrlKey&&je.key.toLowerCase()==="w")&&(je.preventDefault(),r&&ee&&ee(r))};return window.addEventListener("keydown",me),()=>window.removeEventListener("keydown",me)},[r,ee]),kt.useEffect(()=>{if(!Re||Ne)return;const me=je=>{je.key==="Escape"&&(je.preventDefault(),Ze())};return window.addEventListener("keydown",me,!0),()=>window.removeEventListener("keydown",me,!0)},[Ze,Re,Ne]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(tp,{activeConv:r,wsStatus:n,isConnected:a,conversations:fe,hiddenConversations:h,onOpenHistory:i,onHideConversation:ee,onShowConversation:L,onShowAllHidden:we,onResetPanelsToMain:Q,notifications:ke,notificationUnreadCount:Z,onOpenNotification:q,onMarkNotificationRead:Pe,onMarkNotificationUnread:We,onDeleteNotification:He,inboxOpen:Se,onInboxOpenChange:Te,hiddenOpen:Ie,onHiddenOpenChange:Ge,onOpenNewSession:t?void 0:tt,onOpenDashboardGuide:Qe,guideNudgeVisible:Fe,actionShortcuts:_e,onOpenRemote:()=>{!r||et(r)||Xe(r)||c(r)},onStopCli:l,activeCliViewMode:u,onSetCliViewMode:m,onOpenGitDialog:V}),e?s.jsx(Ix,{conversations:d,hiddenConversations:h,ides:f,actionLogs:w,sendDaemonCommand:k,setActionLogs:p,setCliViewModeOverrides:S,isStandalone:x,userName:y,requestedActiveTabKey:I,onRequestedActiveTabConsumed:g,requestedMachineId:T,onRequestedMachineConsumed:A,requestedMobileSection:j,onRequestedMobileSectionConsumed:v,onOpenHistory:i,onOpenRemote:c,onStopCli:l,wsStatus:n,isConnected:a,onShowAllHiddenConversations:we,onHideConversation:ee,onOpenNewSession:tt,liveSessionInboxState:Ce}):t?s.jsx($x,{containerRef:K,isSplitMode:_,numGroups:C,groupSizes:H,groupedConvs:F,clearedTabs:P,ides:f,actionLogs:w,sendDaemonCommand:k,setActionLogs:p,isStandalone:x,hasRegisteredMachines:xe.length>0,userName:y,focusedGroup:N,focusGroup:M,moveTabToGroup:O,splitTabRelative:$,closeGroup:E,handleResizeStart:U,groupActiveTabIds:X,setGroupActiveTab:he,groupTabOrders:ce,setGroupTabOrder:te,toggleHiddenTab:ye,onOpenNewSession:tt,allowTabShortcuts:!1,liveSessionInboxState:Ce}):s.jsx(tb,{visibleConversations:fe,clearedTabs:P,ides:f,actionLogs:w,sendDaemonCommand:k,setActionLogs:p,isStandalone:x,hasRegisteredMachines:xe.length>0,initialDataLoaded:b,userName:y,toggleHiddenTab:ye,actionShortcuts:_e,registerActionHandlers:me=>{D.current=me},onActiveTabChange:ae,requestedActiveTabKey:be,onRequestedActiveTabConsumed:J,onRequestScrollToBottom:ge,scrollToBottomRequest:ue,onOpenNewSession:tt,liveSessionInboxState:Ce,layoutProfile:se}),Ee&&s.jsx(ob,{machines:xe,ides:f,onClose:W,onBrowseDirectory:ie,onSaveWorkspace:re,onLaunchIde:G,onLaunchProvider:Y,onListSavedSessions:le}),z&&s.jsx(Ll,{daemonId:z.daemonId,workspace:z.workspace,onClose:()=>R(null)}),Re&&s.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:Ze,children:s.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:me=>me.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.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."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Ze,"aria-label":"Close dashboard guide",children:s.jsx(St,{size:14})})]}),s.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(me=>s.jsx("button",{type:"button",className:`btn btn-sm ${Ue===me.id?"btn-primary":"btn-secondary"}`,onClick:()=>ut(me.id),children:me.label},me.id))}),Ue==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",ve?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Ue==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.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."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),Ue==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.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(me=>s.jsx("button",{type:"button",className:`btn btn-sm ${Je===me.id?"btn-primary":"btn-secondary"}`,onClick:()=>lt(me.id),children:me.label},me.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:pt,children:"Disable all"}),s.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:ht,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:mt.map(me=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ne===me.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:me.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:me.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:me.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.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:Ne===me.id?De.length>0?`${De.join(" ")} ...`:"Listening...":_e[me.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Be(me.id),Le([])},children:Ne===me.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const je={..._e};je[me.id]="",ze(je)},children:"Disable"})]})]})},me.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",ve?"⌘⇧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 Fn=[{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 Ab({onClose:e}){const[t,r]=o.useState(0),n=Fn[t],a=t===Fn.length-1;return s.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:[s.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:[s.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:s.jsx(St,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Fn.map((i,c)=>s.jsx("div",{style:{width:c===t?24:8,height:8,borderRadius:4,background:c===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.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:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.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 →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.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 Ib({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.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:t}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",u=i.status==="generating";return s.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:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&s.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 Mb({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[i,c]=o.useState(()=>a||"native"),l=o.useMemo(()=>Bc(t),[t]),u=o.useMemo(()=>e?Xa(e,{machineNames:l,connectionStates:r,defaultConnectionState:"new"}):[],[e,l,r]),m=o.useMemo(()=>u.find(p=>p.streamSource==="native"),[u]),d=o.useMemo(()=>u.filter(p=>p.streamSource==="agent-stream"),[u]),h=o.useMemo(()=>e?Pt(u,e.id):null,[u,e]);o.useEffect(()=>{a&&c(a)},[a]),o.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||i===p||i==="native"&&c(p)},[i,h,a]),o.useEffect(()=>{var p;i!=="native"&&(d.some(S=>S.tabKey===i)||c(((p=d[0])==null?void 0:p.tabKey)||"native"))},[i,d]),o.useEffect(()=>{i==="native"&&(m||d[0]&&c(d[0].tabKey))},[i,m,d]);const f=o.useMemo(()=>i==="native"&&m?m:d.find(p=>p.tabKey===i)||h||m||d[0],[i,m,h,d]),w=o.useMemo(()=>d.map(p=>({tabKey:p.tabKey,title:Rc(p)||n,status:p.status})),[d,n]),k=o.useCallback(p=>{if(p)return u.find(S=>da(S,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[u]);return{activeChatTab:i,setActiveChatTab:c,activeConv:f,conversations:u,extensionTabs:w,hasExtensions:w.length>0,resolveConversationByTarget:k}}function Rb({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:i,setActionLogs:c,isStandalone:l,userName:u,onOpenHistory:m,onConversationChange:d,onClose:h}){const[f,w]=o.useState("split"),[k,p]=o.useState(()=>Vt(e)?"native":e.tabKey),S=o.useRef(null),x=o.useMemo(()=>t||r.find(M=>M.id===e.routeId),[e.routeId,t,r]),b=o.useMemo(()=>at((x==null?void 0:x.type)||""),[x==null?void 0:x.type]),{conversations:y,extensionTabs:I,hasExtensions:g}=Mb({ideData:x,allIdes:r,connectionStates:n,ideName:b||"IDE",preferredTabKey:Vt(e)?void 0:e.tabKey}),T=o.useMemo(()=>x?Pt(y,x.id):null,[x,y]);o.useEffect(()=>{const M=S.current,O={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(S.current=O,!(M&&M.routeId===O.routeId&&M.tabKey===O.tabKey&&M.streamSource===O.streamSource)){if(Vt(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(k==="native"){if(y.some(M=>M.streamSource==="native"))return;(T==null?void 0:T.streamSource)==="agent-stream"&&p(T.tabKey);return}if(!y.some(M=>M.tabKey===k)){if((T==null?void 0:T.streamSource)==="agent-stream"){p(T.tabKey);return}p("native")}},[y,k,T]);const A=o.useMemo(()=>k==="native"?y.find(M=>M.streamSource==="native")||e:y.find(M=>M.tabKey===k)||e,[e,y,k]),j=Qc(A),v=o.useMemo(()=>j.status||j.modalMessage||j.modalButtons?{...A,...j.status?{status:j.status}:{},...j.modalMessage!==void 0?{modalMessage:j.modalMessage}:{},...j.modalButtons!==void 0?{modalButtons:j.modalButtons}:{}}:A,[A,j]),K=cr(v),_=cn({sendDaemonCommand:i,activeConv:v,setActionLogs:c,isStandalone:l}),{connScreenshot:C,screenshotUsage:H,handleRemoteAction:F}=bl({doId:K,targetSessionId:dc(v),connState:v.connectionState||"new",viewMode:f}),P=o.useMemo(()=>a.filter(M=>M.routeId===v.tabKey),[a,v.tabKey]);o.useEffect(()=>{d==null||d(v)},[v,d]),o.useEffect(()=>{const M=O=>{O.key==="Escape"&&h()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[h]);const N=o.useCallback(M=>{M.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:s.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:N,children:[s.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:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.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:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Tt,{size:16})}),s.jsx("span",{className:"truncate",children:$a(A)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(M=>{const O=f===M;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${O?"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:()=>w(M),title:M==="split"?"Split view":"Remote only",children:M==="split"?s.jsx(Vd,{size:15}):s.jsx(Tt,{size:15})},M)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>m(A),title:"Chat History",children:[s.jsx(Ta,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="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:[f!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(Ib,{hasExtensions:g,ideName:b||"IDE",activeChatTab:k,extensionTabs:I,onSelectTab:p}),s.jsx(Xi,{activeConv:v,onModalButton:_.handleModalButton}),s.jsx(pa,{activeConv:v,ideEntry:x,showMetaChips:!1,handleSendChat:_.handleSendChat,isSendingChat:_.isSendingChat,sendFeedbackMessage:_.sendFeedbackMessage,handleFocusAgent:_.handleFocusAgent,isFocusingAgent:_.isFocusingAgent,actionLogs:P,userName:u})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${f==="split"?"order-1 md:order-2":""}`,children:s.jsx(qi,{addLog:()=>{},connState:v.connectionState||"new",connScreenshot:C,screenshotUsage:H,transportType:v.transport,onAction:F})})]})]})})}function Lb({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=Uf(e);return s.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:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.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:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"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."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.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"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function _b({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(Yf,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Ya,{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}),t.conversation&&s.jsx(Rb,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(et(r.targetConv)||Xe(r.targetConv))&&s.jsx(Lb,{activeConv:r.targetConv,canSaveAndStop:et(r.targetConv)&&!Xe(r.targetConv)&&!!((c=r.targetConv.resume)!=null&&c.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx($c,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),i.open&&s.jsx(Ab,{onClose:i.onClose})]})}function Pb({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:s.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:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(or,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(c=>{const l=Ct(c,{fallbackId:c.id}),u=n[c.id],m=c.version||c.daemonVersion||"unknown",d=c.versionUpdateRequired===!0;return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:l}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),d&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:d?"Update now":"Upgrade"})]},c.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:s.jsx(St,{size:16})})]})}function Db(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Eb(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function $b(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>Eb(t)).map(t=>t.id)}}function Bb(){var po,ho,xo,bo;const{sendCommand:e}=ft(),t=dr(),r=Jc(),n=Sa(),a=_s(),[i,c]=md(),l=i.get("activeTab"),u=((po=n.state)==null?void 0:po.openRemoteForTabKey)||null,m=((ho=n.state)==null?void 0:ho.openMachineId)||null,d=((xo=n.state)==null?void 0:xo.mobileSection)||null,h=Tc(),f=h.ides||[],w=h.initialLoaded??!0,{updateRouteChats:k,setToasts:p}=h,[S,x]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=h.toasts||[],y=h.wsStatus||"connected",I=h.isConnected??!0,g=h.connectionStates||{},T=h.showReconnected||!1,{layoutProfile:A,groupAssignments:j,updateGroupAssignments:v,focusedGroup:K,updateFocusedGroup:_,focusGroup:C,groupActiveTabIds:H,updateGroupActiveTabIds:F,setGroupActiveTab:P,groupTabOrders:N,updateGroupTabOrders:M,setGroupTabOrder:O,groupSizes:$,updateGroupSizes:E,isMobile:U,hasHydratedStoredLayout:X,hydrateStoredLayout:he,focusConversationTab:ce}=Ih(),[te,ye]=o.useState(()=>eo());o.useEffect(()=>Gp(ye),[]);const fe=o.useMemo(()=>Db({isMobile:U,mobileViewMode:te}),[U,te]),[be,J]=o.useState([]),[ae,ge]=o.useState({}),[ee,de]=o.useState({});ir("Dashboard",{ideCount:f.length,toastCount:b.length,focusedGroup:K,groupCount:Object.keys(j).length,actionLogCount:be.length});const we=o.useMemo(()=>f.filter(Ve=>Ve.type==="adhdev-daemon").sort(Pa),[f]),ue=we[0],xe=!!ue;o.useEffect(()=>{const{metadataDaemonIds:Ve,runtimeDaemonIds:Mt}=$b(we);for(const Es of Ve)t(Es,{minFreshMs:3e4}).catch(()=>{});for(const Es of Mt)r(Es,{minFreshMs:3e4}).catch(()=>{})},[t,r,we]);const se=(ue==null?void 0:ue.terminalBackend)||null,ie=ue?Ct(ue,{fallbackId:ue.id}):null,re=(ue==null?void 0:ue.id)||null,G=o.useMemo(()=>nh(f,ae),[f,ae]),{hiddenTabs:Y,hideTarget:le,toggleTarget:ke,showTarget:Z,showAllTabs:Ce}=rh(),{conversations:Pe,visibleConversations:We,visibleTabKeys:He,resolveConversationBySessionId:D,resolveConversationByTarget:Se}=ph({ides:G,connectionStates:g,clearedTabs:ee,hiddenTabs:Y}),Ie=o.useMemo(()=>new Map(Pe.map(Ve=>[Ve.tabKey,Ve])),[Pe]);wf(We,fe),o.useEffect(()=>{Object.keys(ae).length!==0&&ge(Ve=>ah(Ve,f))},[f,ae]);const Re=o.useMemo(()=>_u(f),[f]),{notifications:Ee,unreadCount:Fe}=Uh({conversations:Pe,liveSessionInboxState:Re}),{handleMarkDashboardNotificationRead:Ue,handleMarkDashboardNotificationUnread:Je,handleDeleteDashboardNotification:dt}=zh({notifications:Ee,sendDaemonCommand:e}),{containerRef:ut,normalizedGroupAssignments:lt,numGroups:Te,isSplitMode:Ge,groupedConvs:Qe,moveTabToGroup:qe,closeGroup:tt,handleResizeStart:W,splitTabRelative:z}=Eh({groupAssignments:j,updateGroupAssignments:v,updateFocusedGroup:_,updateGroupActiveTabIds:F,updateGroupTabOrders:M,groupSizes:$,updateGroupSizes:E,isMobile:U,visibleConversations:We,visibleTabKeys:He}),{activeConv:R,openDesktopConversation:V,requestScrollToBottom:L,scrollToBottomRequest:q,setDesktopActiveTab:Q}=tx({isMobile:U,conversations:Pe,visibleConversations:We,groupActiveTabIds:H,focusedGroup:K,groupedConvs:Qe,setSearchParams:c});nx({activeConv:R,isMobile:U,liveSessionInboxState:Re,sendDaemonCommand:e});const{requestedDesktopTabKey:ne,requestedMobileTabKey:ve,consumeRequestedActiveTab:Ae}=hh({isMobile:U,urlActiveTab:l,resolveConversationBySessionId:D,setSearchParams:c}),{remoteDialogConv:_e,remoteDialogIdeEntry:Ne,remoteDialogActiveConv:De,setRemoteDialogActiveConv:Be,openRemoteDialog:Le,closeRemoteDialog:ze,cliStopDialogOpen:Ze,cliStopTargetConv:mt,requestCliStop:pt,cancelCliStop:ht,confirmCliStop:me}=ix({isMobile:U,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:ne,conversations:Pe,ides:f,resolveConversationByTarget:Se,activeConv:R,sendDaemonCommand:e}),{historyModalOpen:je,openHistoryModal:bt,closeHistoryModal:wt,historyTargetConv:B,isSavedSessionHistoryTarget:oe,isHistoryCreatingChat:pe,isHistoryRefreshingHistory:Ke,handleHistorySwitchSession:Me,handleHistoryNewChat:$e,handleHistoryRefresh:nt,savedHistorySessions:jt,savedHistoryFilters:ct,setSavedHistoryFilters:Ut,missingWorkspaceResumePath:mr,isSavedHistoryLoading:fr,resumingSavedHistorySessionId:pr,handleRefreshSavedHistory:$l,handleResumeSavedHistorySession:Bl}=ax({activeConv:R,remoteDialogConv:_e,remoteDialogActiveConv:De,ides:f,sendDaemonCommand:e,updateRouteChats:k,setToasts:p,setClearedTabs:de,setSearchParams:c}),Kl=o.useMemo(()=>We,[We]),hr=U&&te==="chat",Ol=o.useMemo(()=>Pe.filter(Ve=>to(Y,Ve)),[Pe,Y]),uo=o.useCallback(Ve=>{const Mt=new URLSearchParams(i);Mt.set("activeTab",Ve),c(Mt,{replace:!0})},[i,c]),{trackPendingLaunch:Wl}=Jh({ides:f,conversations:Pe,onOpenSession:uo}),{handleBrowseMachineDirectory:Hl,handleSaveMachineWorkspace:Fl,handleLaunchMachineIde:Ul,handleLaunchMachineProvider:zl,handleListMachineSavedSessions:Vl,setActiveCliViewMode:Gl}=Qh({sendDaemonCommand:e,trackPendingLaunch:Wl,onOpenSession:uo,activeConv:R,ides:f,setCliViewModeOverrides:ge});oh({visibleConversations:We,clearedTabs:ee,setClearedTabs:de,setActionLogs:J}),xh({ides:f,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Se});const{isRefreshingHistory:ql,handleRefreshHistory:Yl}=cl({sendDaemonCommand:e,activeConv:R,chats:(bo=f.find(Ve=>Ve.id===(R==null?void 0:R.routeId)))==null?void 0:bo.chats,updateRouteChats:k,setToasts:p,setClearedTabs:de});Rh({urlActiveTab:U&&!hr?l:null,conversations:Pe,resolveConversationBySessionId:D,normalizedGroupAssignments:lt,hasHydratedStoredLayout:U&&!hr?X:!0,hydrateStoredLayout:U&&!hr?he:()=>{},focusConversationTab:ce,setSearchParams:c,historyModalOpen:je,activeConv:R,isRefreshingHistory:ql,ides:f,handleRefreshHistory:Yl});const Xl=o.useMemo(()=>!R||!et(R)||Xe(R)?null:Ds(R),[R]),{versionMismatchDaemons:Jl,hasRequiredVersionDaemons:mo,appVersion:Ql,versionBannerDismissed:Zl,setVersionBannerDismissed:ed,upgradingDaemons:td,handleBannerUpgrade:sd}=$h({ides:f,sendDaemonCommand:e}),fo=o.useCallback(Ve=>{Z(Ve),V(Ve)},[V,Z]),rd=o.useCallback(Ve=>{le(Ve)},[le]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(Xf,{terminalBackend:se,isStandalone:xe,machineLabel:ie,machineKey:re}),(!Zl||mo)&&s.jsx(Pb,{daemons:Jl,targetVersion:Ql,required:mo,upgradingDaemons:td,onUpgrade:sd,onDismiss:()=>ed(!0)}),s.jsx(Tb,{showMobileChatMode:hr,isMobile:U,activeConv:R,wsStatus:y,isConnected:I,onOpenHistory:Ve=>{Ve&&Be(Ve),bt()},onOpenRemote:Le,onStopCli:pt,activeCliViewMode:Xl,onSetActiveCliViewMode:Gl,mobileChatConversations:Kl,ides:f,actionLogs:be,sendDaemonCommand:e,setActionLogs:J,setCliViewModeOverrides:ge,isStandalone:xe,initialDataLoaded:w,userName:h.userName,requestedMobileTabKey:ve,onRequestedMobileTabConsumed:Ae,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:ut,isSplitMode:Ge,numGroups:Te,groupSizes:$,groupedConvs:Qe,clearedTabs:ee,focusedGroup:K,focusGroup:C,moveTabToGroup:qe,splitTabRelative:z,closeGroup:tt,handleResizeStart:W,groupActiveTabIds:H,setGroupActiveTab:P,groupTabOrders:N,setGroupTabOrder:O,toggleHiddenTab:Ve=>ke(Ie.get(Ve)||{tabKey:Ve}),visibleConversations:We,hiddenConversations:Ol,requestedDesktopTabKey:ne,onRequestedDesktopTabConsumed:Ae,onDesktopActiveTabChange:Q,onRequestScrollToBottom:L,onHideConversation:rd,onShowHiddenConversation:fo,onShowAllHiddenConversations:Ce,scrollToBottomRequest:q,machineEntries:we,layoutProfile:A,onBrowseMachineDirectory:Hl,onSaveMachineWorkspace:Fl,onLaunchMachineIde:Ul,onLaunchMachineProvider:zl,onListMachineSavedSessions:Vl,notifications:Ee,notificationUnreadCount:Fe,liveSessionInboxState:Re,onMarkNotificationRead:Ue,onMarkNotificationUnread:Je,onDeleteNotification:dt}),s.jsx("style",{children:`
|
|
68
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
69
|
+
`}),s.jsx(_b,{historyModal:{open:je,targetConv:B,ides:f,isCreatingChat:pe,isRefreshingHistory:oe?!1:Ke,savedSessions:jt,savedHistoryFilters:ct,missingWorkspaceResumePath:mr||null,onSavedHistoryFiltersChange:Ut,isSavedSessionsLoading:fr,isResumingSavedSessionId:pr,onClose:wt,onNewChat:$e,onSwitchSession:Me,onRefreshHistory:oe?$l:nt,onResumeSavedSession:Bl},remoteDialog:{conversation:_e,ideEntry:Ne,ides:f,connectionStates:g,actionLogs:be,sendDaemonCommand:e,setActionLogs:J,isStandalone:xe,userName:h.userName,onOpenHistory:Ve=>{Ve&&Be(Ve),bt()},onConversationChange:Be,onClose:ze},cliStopDialog:{open:Ze,targetConv:mt,onCancel:ht,onStopNow:async()=>{await me("hard")},onSaveAndStop:async()=>{await me("save")}},connectionBanner:{wsStatus:y,showReconnected:T,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:b,onDismiss:Ve=>p(Mt=>Mt.filter(Es=>Es.id!==Ve)),onClick:Ve=>{if(Ve.targetKey){const Mt=Se(Ve.targetKey);Mt&&(ce(Mt.tabKey,lt),fo(Mt),L(Mt.tabKey,"toast-open"))}}},onboarding:{open:S,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}x(!1)}}})]})}function Kb({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[m,d]=o.useState(null),[h,f]=o.useState(!1),[w,k]=o.useState(null),[p,S]=o.useState(!1),[x,b]=o.useState(""),y=o.useRef(null),I=o.useCallback($=>{y.current=$},[]),g=o.useCallback(($,E,U=!1)=>{c(X=>[...X.slice(-100),{timestamp:Date.now(),level:$,message:E}]),setTimeout(()=>{var X;return(X=a.current)==null?void 0:X.scrollIntoView({behavior:"smooth"})},100),U&&rt.showToast(E,$==="error"||$==="warn"?"warning":"success")},[a]),T=o.useCallback($=>{const E=$ instanceof Error?$.message:String($||"");return E.includes("P2P command timeout")||E.includes("P2P not connected")||E.includes("P2P not available")},[]),A=o.useCallback(async($,E)=>{var U;if(!e||l)return!1;u($),g("info",`Launching ${at($)}${E!=null&&E.workspace?` in ${E.workspace}`:""}...`);try{const X={ideType:$,enableCdp:!0};(U=E==null?void 0:E.workspace)!=null&&U.trim()?X.workspace=E.workspace.trim():E!=null&&E.useDefaultWorkspace&&(X.useDefaultWorkspace=!0);const he=await r(e,"launch_ide",X);return g(he!=null&&he.success?"info":"error",he!=null&&he.success?`${at($)} launched`:`Failed: ${he==null?void 0:he.error}`,!0),!!(he!=null&&he.success)}catch(X){return g("error",`Launch error: ${X.message}`,!0),!1}finally{u(null)}},[e,l,g,r]),j=o.useCallback(async $=>{if(!e)return{success:!1};const{cliType:E,dir:U,workspaceId:X,useDefaultWorkspace:he,useHome:ce,argsStr:te,model:ye,resumeSessionId:fe}=$;if(!E)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const be=te?te.split(/\s+/).filter(Boolean):void 0,J=(U==null?void 0:U.trim())||(X?"(saved id)":he?"(default workspace)":ce?"(home)":"");g("info",`Launching ${E}${J?` in ${J}`:""}${ye?` (model: ${ye})`:""}...`),d(E);try{const ae={cliType:E,cliArgs:be,initialModel:ye||void 0};U!=null&&U.trim()?ae.dir=U.trim():X?ae.workspaceId=X:he?ae.useDefaultWorkspace=!0:ce&&(ae.useHome=!0),fe&&(ae.resumeSessionId=fe);const ge=await r(e,"launch_cli",ae),ee=(ge==null?void 0:ge.result)||ge;return ge!=null&&ge.success?(g("info",`${E} launched`,!0),(ee==null?void 0:ee.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(ee==null?void 0:ee.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ee==null?void 0:ee.sessionId}):(g("error",`Failed: ${(ge==null?void 0:ge.error)||(ee==null?void 0:ee.error)}`,!0),(ge==null?void 0:ge.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&k({cliType:E,argsStr:te,model:ye}),{success:!1,sessionId:ee==null?void 0:ee.sessionId})}catch(ae){return T(ae)?(g("warn",`${E} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${ae.message}`,!0),{success:!1})}finally{d(null)}},[e,g,T,r]),v=o.useCallback(async($,E,U,X)=>e?$?E.trim()?j({cliType:$,dir:E,argsStr:U,model:X}):(k({cliType:$,argsStr:U,model:X}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,j]),K=o.useCallback(async($,E,U)=>{if(e&&window.confirm(`Stop ${$}?
|
|
70
|
+
This will terminate the process.`))try{const X=await r(e,"stop_cli",{cliType:$,dir:E,targetSessionId:U});X!=null&&X.success?g("info",`${$} stopped`,!0):g("error",`Stop failed: ${(X==null?void 0:X.error)||"Unknown error"}`,!0)}catch(X){g("error",`Stop failed: ${X.message}`,!0)}},[e,g,r]),_=o.useCallback(async $=>{try{await r($.daemonId,"restart_ide",{ideType:$.type}),g("info",`${at($.type)} restart initiated`,!0)}catch(E){g("error",`Restart failed: ${E.message}`,!0)}},[g,r]),C=o.useCallback(async $=>{if(window.confirm(`Stop ${at($.type)}?
|
|
71
|
+
This will disconnect CDP and optionally kill the process.`))try{const E=await r($.daemonId,"stop_ide",{ideType:$.type,killProcess:!0});E!=null&&E.success?g("info",`${at($.type)} stopped`,!0):g("error",`Stop failed: ${(E==null?void 0:E.error)||"Unknown error"}`,!0)}catch(E){g("error",`Stop failed: ${E.message}`,!0)}},[g,r]),H=o.useCallback(async()=>{if(e)try{const $=await r(e,"detect_ides",{});g("info",`Found ${(($==null?void 0:$.result)||[]).length} IDE(s)`,!0)}catch($){g("error",`Detection failed: ${$.message}`,!0)}},[e,g,r]),F=o.useCallback(async $=>{if(!e||!$.trim())return!1;f(!0);try{const E=await r(e,"workspace_add",{path:$.trim()});return E!=null&&E.success?(g("info",`Workspace added: ${$.trim()}`),!0):(g("error",(E==null?void 0:E.error)||"workspace_add failed"),!1)}catch(E){return g("error",E.message),!1}finally{f(!1)}},[e,g,r]),P=o.useCallback(async $=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){f(!0);try{const E=await r(e,"workspace_remove",{id:$});E!=null&&E.success?g("info","Workspace removed",!0):g("error",(E==null?void 0:E.error)||"workspace_remove failed",!0)}catch(E){g("error",E.message,!0)}finally{f(!1)}}},[e,g,r]),N=o.useCallback(async $=>{var E;if(e){f(!0);try{const U=await r(e,"workspace_set_default",$===null?{clear:!0}:{id:$});if(U!=null&&U.success){g("info",$?"Default workspace updated":"Default workspace cleared",!0);const X=typeof U.defaultWorkspacePath=="string"?U.defaultWorkspacePath:"";X&&((E=y.current)==null||E.call(y,X))}else g("error",(U==null?void 0:U.error)||"workspace_set_default failed",!0)}catch(U){g("error",U.message,!0)}finally{f(!1)}}},[e,g,r]),M=o.useCallback(async $=>{var U;if(!e||!$.trim())return;const E=$.trim();f(!0);try{const X=await r(e,"workspace_set_default",{path:E});X!=null&&X.success?(g("info","Default workspace set from history"),(U=y.current)==null||U.call(y,E)):g("error",(X==null?void 0:X.error)||"Could not set default (path missing on disk?)")}catch(X){g("error",X.message)}finally{f(!1)}},[e,g,r]),O=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:x}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:x})}catch($){g("warn",`Live nickname updated, but account sync failed: ${$.message}`)}g("info",`Nickname set to "${x||"(cleared)"}"`),S(!1)}catch($){g("error",`Failed: ${$.message}`)}},[e,x,t,g,n,r]);return{logs:i,launchingIde:l,launchingAgentType:m,workspaceBusy:h,launchPick:w,setLaunchPick:k,editingNickname:p,setEditingNickname:S,nicknameInput:x,setNicknameInput:b,addLog:g,handleLaunchIde:A,runLaunchCliCore:j,handleLaunchCli:v,handleStopCli:K,handleRestartIde:_,handleStopIde:C,handleDetectIdes:H,handleWorkspaceAdd:F,handleWorkspaceRemove:P,handleWorkspaceSetDefault:N,handleWorkspaceResumePath:M,handleSaveNickname:O,setOnDefaultWorkspaceChanged:I}}function Ob({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var _;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:m,handleWorkspaceSetDefault:d}=i,[h,f]=o.useState(!1),[w,k]=o.useState(""),[p,S]=o.useState([]),[x,b]=o.useState(!1),[y,I]=o.useState(""),g=o.useCallback(async C=>{b(!0),I("");try{const H=await un(c,e,C);k(H.path),S(H.directories)}catch(H){I(H instanceof Error?H.message:"Could not load folder")}finally{b(!1)}},[e,c]),T=o.useCallback(()=>{f(!0);const C=[...r.map(F=>F.workspace),...n.map(F=>F.workspace),...a.map(F=>F.workspace)],H=dn(t.platform,ln(C,t.defaultWorkspacePath,(t.workspaces||[]).map(F=>F.path)));g(H)},[a,n,r,g,t.defaultWorkspacePath,t.platform,t.workspaces]),A=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,j=t.availableMem??t.freeMem??t.totalMem,v=A&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-j)/t.totalMem*100))):0,K=((_=t.loadavg)==null?void 0:_[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(gr,{icon:s.jsx(Wi,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Ku(t.uptime):"Waiting…"}),s.jsx(gr,{icon:s.jsx(Tt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(gr,{icon:s.jsx(Ia,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(gr,{icon:s.jsx(qd,{size:16}),label:"ACPs",value:`${a.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(Co,{value:A?Math.min(Math.round(K/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:A?`${K.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Co,{value:v,max:100,label:"Memory",color:"#3b82f6",detail:A?`${vn(t.totalMem-j)} / ${vn(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${vn(t.totalMem)} total`})]})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[s.jsx(Cs,{size:14})," Workspaces"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),s.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:t.defaultWorkspaceId||"",onChange:C=>void d(C.target.value===""?null:C.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(C=>s.jsx("option",{value:C.id,children:C.label||C.path},C.id))]}),t.defaultWorkspacePath&&s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:t.defaultWorkspacePath,children:t.defaultWorkspacePath})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.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:T,children:"Select workspace…"}),s.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(t.workspaces||[]).length>0&&s.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(t.workspaces||[]).map(C=>s.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:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[C.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:an(C.path,C.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:C.path,children:C.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void m(C.id),children:"Remove"})]},C.id))})]}),h&&s.jsx(mn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:p,busy:x,error:y,confirmLabel:"Add workspace",onClose:()=>f(!1),onNavigate:C=>{g(C)},onConfirm:C=>{(async()=>{if(!C)return;await u(C)&&f(!1)})()}})]})}function Wb(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function Hb(e,t,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=t.find(u=>u.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function Un(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function pi(e){if(!e||typeof e!="object")return null;if(Un(e))return e;const t=e,r=t.result;return Un(r)?r:Un(t.sourceConfig)?t.sourceConfig:null}function Fb(e){const t=e.trim();return t||null}const hi=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Ub=[{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 zb({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,m]=o.useState([]),[d,h]=o.useState(""),[f,w]=o.useState([]),[k,p]=o.useState(""),S=o.useRef(null),x=o.useRef(null),b=j=>{m(v=>v.includes(j)?v.filter(K=>K!==j):[...v,j])},y=()=>m([...hi]),I=()=>m([]);o.useEffect(()=>{var j;(j=S.current)==null||j.scrollIntoView({behavior:"smooth"})},[f]),o.useEffect(()=>()=>{x.current&&clearInterval(x.current)},[]);const g=o.useCallback(()=>{x.current&&clearInterval(x.current),x.current=setInterval(async()=>{try{const j=await r(e,"provider_auto_fix_status",{providerType:t.type});(j==null?void 0:j.running)===!1&&a==="running"&&(i("done"),w(v=>[...v,`
|
|
72
|
+
✅ Auto-fix completed!`]),x.current&&clearInterval(x.current))}catch{}},3e3)},[e,t.type,r,a]),T=async()=>{if(u.length!==0){i("running"),w(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,d?`💬 Comment: ${d}`:"",""]),p("");try{const j=await r(e,"provider_auto_fix",{providerType:t.type,functions:u,agent:c,...d?{comment:d}:{}});j!=null&&j.success&&(j!=null&&j.started||j!=null&&j.running)?(w(v=>[...v,"✅ Agent started. Monitoring progress..."]),g()):(i("error"),p((j==null?void 0:j.error)||"Failed to start auto-fix"))}catch(j){i("error"),p((j==null?void 0:j.message)||"Connection failed")}}},A=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),w(j=>[...j,`
|
|
73
|
+
⚠️ Auto-fix cancelled.`]),i("done"),x.current&&clearInterval(x.current)}catch{}};return s.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:s.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:j=>j.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:Ub.map(j=>s.jsxs("button",{onClick:()=>l(j.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===j.value?j.color+"66":"var(--border-subtle)",background:c===j.value?j.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===j.value?j.color:"var(--text-primary)"},children:j.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:j.desc})]},j.value))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:y,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),s.jsx("button",{onClick:I,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:hi.map(j=>s.jsxs("button",{onClick:()=>b(j),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(j)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(j)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(j)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(j)?"☑ ":"☐ ",j]},j))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:d,onChange:j=>h(j.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")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.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:[f.map((j,v)=>s.jsx("div",{className:j.startsWith("✅")?"text-green-400":"",style:j.startsWith("❌")||j.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:j},v)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:S})]}),k&&s.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:k})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&u.length>0&&`${u.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:T,disabled:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&s.jsx("button",{onClick:A,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{i("config"),w([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Vb({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var g;const i=t.filter(T=>T.category==="ide"),[c,l]=o.useState(((g=i[0])==null?void 0:g.type)||""),[u,m]=o.useState(""),[d,h]=o.useState(""),[f,w]=o.useState(!1),[k,p]=o.useState(""),[S,x]=o.useState(!1),b=T=>{const A=T.toLowerCase().replace(/[^a-z0-9-]/g,"");m(A),(!d||d===y(u))&&h(y(A))},y=T=>T.split("-").map(A=>A.charAt(0).toUpperCase()+A.slice(1)).join(" "),I=async()=>{if(!(!u||!d||!c)){w(!0),p("");try{const T=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:c});T!=null&&T.success||T!=null&&T.created?(x(!0),a==null||a(u)):p((T==null?void 0:T.error)||"Failed to create provider")}catch(T){p((T==null?void 0:T.message)||"Connection failed")}w(!1)}};return s.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:s.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:T=>T.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.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:S?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:u})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(T=>s.jsxs("button",{onClick:()=>l(T.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===T.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===T.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:T.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===T.type?"#a78bfa":"var(--text-secondary)"},children:T.displayName})]},T.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:u,onChange:T=>b(T.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"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",u||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:d,onChange:T=>h(T.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"})]}),k&&s.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:k})]})}),s.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:S?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:I,disabled:!u||!d||f,className:"machine-btn",style:{background:u&&d?"rgba(34,197,94,0.12)":void 0,borderColor:u&&d?"rgba(34,197,94,0.3)":void 0,color:u&&d?"#86efac":void 0,opacity:!u||!d||f?.4:1},children:f?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function xi(e){return e==="cli"||e==="acp"}function Gb(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 qb(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 bi(e){if(!e)return"No result yet";const t=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t}: ${r} — ${n}`:`${t}: ${r}`}function Yb({machineId:e,providers:t,sendDaemonCommand:r}){var F;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[m,d]=o.useState("all"),[h,f]=o.useState(null),[w,k]=o.useState(!1),[p,S]=o.useState(null),[x,b]=o.useState("normal"),[y,I]=o.useState(""),[g,T]=o.useState(!1),A=o.useCallback(async()=>{if(e)try{const P=await r(e,"get_provider_source_config",{}),N=pi(P);N&&(S(N),b(N.sourceMode),I(N.explicitProviderDir||""))}catch{}},[e,r]),j=o.useCallback(async()=>{if(e){c(!0);try{const P=await r(e,"get_provider_settings",{}),N=Wb(P);if(N){const M=Hb(N,t,{filterSchema:O=>O.filter($=>$.key!=="enabled")});M.sort((O,$)=>O.category.localeCompare($.category)||O.displayName.localeCompare($.displayName)),a(M)}}catch{}c(!1)}},[e,t,r]);o.useEffect(()=>{n.length===0&&j(),p||A()},[]);const v=async(P,N,M)=>{u(`${P}.${N}`),a(O=>O.map($=>$.type===P?{...$,values:{...$.values,[N]:M}}:$));try{const O=await r(e,"set_provider_setting",{providerType:P,key:N,value:M});O!=null&&O.success||j()}catch{j()}u(null)},K=async(P,N)=>{await v(P,"enabled",N),await j()},_=async P=>{u(`${P}.detect`);try{await r(e,"detect_provider",{providerType:P})}finally{await j(),u(null)}},C=async P=>{await v(P,"executablePath",""),await v(P,"executableArgs",""),await j()},H=async()=>{T(!0);try{const P=await r(e,"set_provider_source_config",{providerSourceMode:x,providerDir:Fb(y)}),N=pi(P);N?(S(N),b(N.sourceMode),I(N.explicitProviderDir||"")):await A(),await j()}catch{await A()}T(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-4",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(P=>s.jsx("button",{onClick:()=>d(P),className:`machine-btn text-[10px] px-2 py-0.5 ${m===P?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:P.toUpperCase()},P))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>k(!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"}),s.jsx("button",{onClick:j,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.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."})]}),s.jsx("button",{onClick:A,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:x,onChange:P=>b(P.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:y,onChange:P=>I(P.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void H(),disabled:g,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:g?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((F=p==null?void 0:p.providerRoots)==null?void 0:F.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(P=>P.category===m).length>1&&(()=>{const P=n.filter($=>$.category===m),N=new Map;for(const $ of P)for(const E of $.schema){if(E.type!=="boolean")continue;const U=N.get(E.key),X=!!($.values[E.key]??E.default);U?(U.onCount+=X?1:0,U.total+=1):N.set(E.key,{label:E.label||E.key,onCount:X?1:0,total:1})}const M=[...N.entries()].filter(([,$])=>$.total===P.length);if(M.length===0)return null;const O=async($,E)=>{for(const U of P)await v(U.type,$,E)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",P.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:M.map(([$,E])=>{const U=E.onCount===E.total,X=E.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:E.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",E.onCount,"/",E.total,")"]}),s.jsx("button",{onClick:()=>void O($,!0),disabled:U,className:`machine-btn text-[9px] px-1.5 py-px ${U?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void O($,!1),disabled:X,className:`machine-btn text-[9px] px-1.5 py-px ${X?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},$)})})]})})(),i&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter(P=>m==="all"||P.category===m).map(P=>s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[s.jsx("span",{className:"text-lg",children:P.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:P.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:P.category==="acp"?"rgba(139,92,246,0.08)":P.category==="cli"?"rgba(59,130,246,0.08)":P.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:P.category==="acp"?"#a78bfa":P.category==="cli"?"#60a5fa":P.category==="ide"?"#86efac":"var(--status-warning)"},children:P.category}),xi(P.category)&&(()=>{const N=t.find($=>$.type===P.type),M=(N==null?void 0:N.enabled)===!0||P.values.enabled===!0,O=(N==null?void 0:N.machineStatus)||(M?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${qb(O)}`,children:Gb(O)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void K(P.type,!M),disabled:l===`${P.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${M?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:M?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void _(P.type),disabled:!M||l===`${P.type}.detect`,title:M?"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 ${M?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void C(P.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),P.category==="ide"&&s.jsx("button",{onClick:()=>f(t.find(N=>N.type===P.type)||{type:P.type,name:P.displayName,displayName:P.displayName,icon:P.icon,category:P.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"})]}),xi(P.category)&&(()=>{const N=t.find(M=>M.type===P.type);return s.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:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",bi(N==null?void 0:N.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",bi(N==null?void 0:N.lastVerification)]}),s.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."})]})})(),s.jsx("div",{className:"flex flex-col gap-2",children:P.schema.map(N=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[N.label||N.key,l===`${P.type}.${N.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),N.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:N.description})]}),s.jsx("div",{className:"shrink-0",children:N.type==="boolean"?s.jsx("button",{onClick:()=>v(P.type,N.key,!(P.values[N.key]??N.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:P.values[N.key]??N.default?"#8b5cf6":"var(--border-subtle)"},children:s.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:P.values[N.key]??N.default?21:3}})}):N.type==="number"?s.jsx("input",{type:"number",value:Number(P.values[N.key]??N.default??0)||0,min:N.min,max:N.max,onChange:M=>{const O=parseInt(M.target.value)||0;N.min!==void 0&&O<N.min||N.max!==void 0&&O>N.max||v(P.type,N.key,O)},className:"machine-input w-20 text-center text-[11px]"}):N.type==="select"&&N.options?s.jsx("select",{value:String(P.values[N.key]??N.default??""),onChange:M=>v(P.type,N.key,M.target.value),className:"machine-input text-[11px]",children:N.options.map(M=>s.jsx("option",{value:M,children:M},M))}):s.jsx("input",{type:"text",value:String(P.values[N.key]??N.default??""),onBlur:M=>v(P.type,N.key,M.target.value),className:"machine-input w-[120px] text-[11px]"})})]},N.key))})]},P.type))}),h&&s.jsx(zb,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>f(null)}),w&&s.jsx(Vb,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>k(!1),onCreated:()=>{k(!1),j()}})]})}const Xb=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Jb({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Qb(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Zb(e){return e.trim().toLowerCase()}function pn(e,t){const r=Zb(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function io(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Ls(e,t=220){const r=io(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function eg(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.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 t=="string"){const r=t.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function tg(e,t){return e.filter(r=>pn([r.level,r.message],t))}function gi(e){return`${e.timestamp}:${e.level}:${e.message}`}function sg(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const c of e.entries)n.set(gi(c),c);for(const c of t.entries)n.set(gi(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 t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function rg(e,t,r=120){if(t.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values()).sort((a,i)=>a.ts-i.ts).slice(-r)}function ng(e,t){return e.split(`
|
|
74
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>pn([r],t))}function ag(e,t){return e.filter(r=>pn([r.level,r.category,r.stage,r.interactionId,io(r.payload)],t))}function og(e,t){return e.filter(r=>pn([r.kind,r.topic,r.interactionId,io(r.payload)],t))}function yi(e){return e==="warn"||e==="error"}function ig({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){return{all:e.length+t.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=>yi(a.level)).length+r.filter(a=>yi(a.level)).length}}function cg({daemonLogs:e,daemonRawLines:t,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
|
+
`)):t.length>0&&a.push(["[daemon logs]",...t].join(`
|
|
76
|
+
`)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${Ls(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}`:""} ${Ls(i.payload,500)}`.trim())].join(`
|
|
78
|
+
`)),a.join(`
|
|
79
|
+
|
|
80
|
+
`)}function lg({machineId:e,sendDaemonCommand:t}){const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,m]=o.useState([]),[d,h]=o.useState([]),[f,w]=o.useState(null),[k,p]=o.useState(!0),[S,x]=o.useState("info"),[b,y]=o.useState("all"),[I,g]=o.useState(!0),[T,A]=o.useState(!0),[j,v]=o.useState(""),[K,_]=o.useState(""),[C,H]=o.useState(0),F=o.useRef(0),P=o.useRef(0),N=o.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),M=o.useRef([]),O=o.useCallback(()=>{const te={entries:[],kind:"empty",rawText:"",lastTs:0};N.current=te,F.current=0,n([]),l(""),i("empty"),g(!0)},[]),$=o.useCallback(()=>{M.current=[],P.current=0,m([]),A(!0)},[]),E=o.useCallback(te=>{te!==S&&(O(),x(te))},[S,O]),U=o.useCallback(te=>{y(ye=>ye===te?ye:te)},[]),X=o.useCallback(()=>{O(),$(),h([]),w(null),v(""),_(""),Ss.clear()},[O,$]),he=o.useCallback(()=>{H(te=>te+1)},[]),ce=o.useCallback(async()=>{if(!e)return;const te=F.current,ye=P.current,[fe,be]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:S,since:te}),t(e,"get_debug_trace",Jb({count:120,since:ye,category:b}))]);if(fe.status==="fulfilled"){const J=fe.value,ae=(J==null?void 0:J.result)||J,ge=eg(ae),ee=sg(N.current,ge,300);N.current=ee,F.current=ee.lastTs,g(!1),v((J==null?void 0:J.success)===!1?String((J==null?void 0:J.error)||"Could not load daemon logs"):""),i(ee.kind),l(ee.rawText),n(ee.entries)}else g(!1),v(fe.reason instanceof Error?fe.reason.message:"Could not load daemon logs");if(be.status==="fulfilled"){const J=be.value,ae=(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(ae==null?void 0:ae.trace)){const ge=ae.trace,ee=rg(M.current,ge,120),de=ge.reduce((we,ue)=>Math.max(we,Number(ue.ts||0)),ye);M.current=ee,de>ye&&(P.current=de),_(""),m(ee)}else _("");A(!1)}else A(!1),_(be.reason instanceof Error?be.reason.message:"Could not load daemon trace");h(Ss.list({limit:120})),w(Date.now())},[S,e,t,b]);return o.useEffect(()=>{$()},[$,b]),o.useEffect(()=>{if(!e||(ce(),!k))return;const te=setInterval(()=>{ce()},3e3);return()=>clearInterval(te)},[k,ce,e,C]),{daemonLogs:r,daemonLogKind:a,daemonRawText:c,debugTrace:u,webEvents:d,lastUpdatedAt:f,autoRefresh:k,logLevel:S,traceCategory:b,daemonLoading:I,traceLoading:T,daemonFetchError:j,traceFetchError:K,setAutoRefresh:p,setLogLevel:E,setTraceCategory:U,refresh:he,clear:X}}function dg({daemonLoading:e,traceLoading:t,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:i,daemonRawLineCount:c,traceCount:l,webEventCount:u}){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":t?"loading":l>0?"ok":"empty",detail:n||`${l} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:u>0?"ok":"empty",detail:u>0?`${u} local browser event(s)`:"No browser events captured"}]}function vi(e){return e==="warn"||e==="error"}function ug(e){const t=e.toLowerCase();return/\[(err|error)\]/i.test(e)||t.includes(" error ")||t.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||t.includes(" warning ")||t.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function mg(e,t){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+t}function wi(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function fg(e){const t=Ls(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function pg(e){const t=Ls(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function hg({daemonLogs:e,daemonRawLines:t,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:pg(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:fg(i),category:i.category,stage:i.stage,interactionId:i.interactionId,payload:i.payload})}),t.forEach((i,c)=>{a.push({id:`raw-file-${c}`,source:"raw_file",ts:mg(i,c),severity:ug(i),message:i,raw:i})}),a.sort((i,c)=>i.ts!==c.ts?i.ts-c.ts:wi(i.source)-wi(c.source))}function xg(e){return`${e.source}:${e.severity}:${e.message}`}function bg(e){const t=e.filter(n=>vi(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!vi(n.severity))continue;const a=xg(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:t.length,latestIssue:t[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 gg(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function ji(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${gg(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function yg({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
81
|
+
`)),a.push(["[source status]",...r.map(c=>`${c.label}: ${c.status} - ${c.detail}`)].join(`
|
|
82
|
+
`)),t.latestIssue&&a.push(["[latest issue]",ji(t.latestIssue)].join(`
|
|
83
|
+
`)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.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(ji):["No diagnostic events captured."]].join(`
|
|
85
|
+
`)),a.join(`
|
|
86
|
+
|
|
87
|
+
`)}function vg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function wg(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function jg({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:i,quickFilter:c,searchQuery:l,daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h}){const f=Qb(n,i),w=tg(e,l),k=ng(t,l),p=ag(f,l),S=og(a,l),x=vg(w,c),b=c==="all"?k:[],y=wg(p,c),I=c==="issues"?[]:S,g=ig({daemonLogs:w,daemonRawLines:k,trace:p,webEvents:S}),T=hg({daemonLogs:x,daemonRawLines:b,trace:y,webEvents:I}),A=bg(T),j=dg({daemonLoading:u,traceLoading:m,daemonFetchError:d,traceFetchError:h,daemonLogKind:r,daemonLogsCount:w.length,daemonRawLineCount:k.length,traceCount:p.length,webEventCount:S.length});return{filteredDaemonLogs:w,filteredDaemonRawLines:k,filteredTraceEntries:p,filteredWebEvents:S,visibleDaemonLogs:x,visibleDaemonRawLines:b,visibleTraceEntries:y,visibleWebEvents:I,quickFilterCounts:g,diagnosticEvents:T,diagnosticsSummary:A,sourceStates:j}}function kg(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function _l(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function va(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 co(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function Sg({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${va(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:_l(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:co(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function Ng({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:c,onCopyVisible:l,onToggleAutoRefresh:u,onRefresh:m,onClear:d}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(h=>s.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),s.jsx("input",{value:r,onChange:h=>i(h.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"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:u,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function Cg({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.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))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:Xb.map(a=>s.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function Tg({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:i,daemonFetchError:c,traceFetchError:l}){var d,h;const u=((d=e.latestIssue)==null?void 0:d.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=c||l?"danger":i?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${zn(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.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"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${zn(u)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[co(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:_l(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${zn(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:c||l?"Needs attention":i?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",kg(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function Ag({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",co(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Ig({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:i,visibleTraceEntries:c,visibleWebEvents:l,quickFilter:u,searchQuery:m}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,timeline:!d.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.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&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(d=>s.jsx(Sg,{event:d},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,daemon:!d.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.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)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.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&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.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&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:u==="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&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&i.map((d,h)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((d,h)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${va(d.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(d.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:d.level==="error"?"ERR":d.level==="warn"?"WRN":d.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:d.message})]},`log-${h}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,trace:!d.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.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&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&c.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&c.length===0&&!e.traceFetchError&&s.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(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${va(d.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.level.toUpperCase()}),s.jsxs("span",{children:[d.category,".",d.stage]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ls(d.payload,360)||"No payload"})]},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>r(d=>({...d,web:!d.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.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&&s.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(d=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.kind}),d.topic&&s.jsxs("span",{children:["topic=",d.topic]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ls(d.payload,360)||"No payload"})]},d.id))]})]})]})}function Mg({machineId:e,sendDaemonCommand:t}){const r=lg({machineId:e,sendDaemonCommand:t}),[n,a]=o.useState("info"),[i,c]=o.useState(""),[l,u]=o.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=o.useRef(null),d=o.useRef(!1),h=o.useMemo(()=>jg({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&&h.diagnosticEvents.length>0){const k=d.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:k}),d.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const f=o.useCallback(async()=>{var p;const k=cg({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!k.trim()){rt.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(k)),rt.showToast("Copied visible logs to clipboard.","success")}catch(S){rt.showToast(S instanceof Error?S.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),w=o.useCallback(async()=>{var p;const k=yg({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(k)),rt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(S){rt.showToast(S instanceof Error?S.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(Ng,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:i,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:c,onCopyDiagnostics:()=>{w()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>r.setAutoRefresh(k=>!k),onRefresh:r.refresh,onClear:r.clear}),s.jsx(Cg,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Tg,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:i,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(Ag,{patterns:h.diagnosticsSummary.repeatedPatterns}),s.jsx(Ig,{streams:r,sectionsOpen:l,setSectionsOpen:u,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:i}),s.jsx("div",{ref:m})]})}function Rg(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 Pl(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function Lg(e){var a;const t=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=Pl((i==null?void 0:i.meta)||void 0),u=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?t.push(i):(c==="stopped"||c==="failed")&&(u||l)?r.push(i):n.push(i)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function _g(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Vn(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 Gn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function qn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function ki(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/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 Pg(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Dg(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 Eg(e){var r;const t=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}`;t.set(i,(t.get(i)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function $g({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),m=eh(e,{enabled:!!e,includeSessions:!0,limit:Eo,intervalMs:sf}),d=m.diagnostics,h=m.loading,f=m.applyDiagnostics,w=o.useMemo(()=>Rg({diagnostics:d,loading:h,refreshing:l,error:n}),[d,h,l,n]),k=o.useMemo(()=>new Map(t.map(_=>[_.sessionId||_.id,_])),[t]),p=o.useCallback(async()=>{if(e){u(!0);try{const _=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Eo}),C=Gn(_);if(!(C!=null&&C.success))throw new Error((C==null?void 0:C.error)||"Could not load hosted runtime diagnostics");f(C.diagnostics||C.result||null),a("")}catch(_){const C=_ instanceof Error?_.message:"Could not load hosted runtime diagnostics";a(C)}finally{u(!1)}}},[f,e,r]);o.useEffect(()=>{!e||d||h||l||p()},[d,h,e,p,l]);const S=o.useCallback(async(_,C)=>{const H=`${_}:${C.sessionId}`;if(!(_==="session_host_stop_session"&&!window.confirm(`Stop ${C.displayName}?
|
|
88
|
+
This will terminate the hosted runtime.`))){c(H);try{const F=await r(e,_,{sessionId:C.sessionId}),P=Gn(F);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Session host action failed");const N=_==="session_host_resume_session"?"resumed":_==="session_host_restart_session"?"restarted":"stopped";rt.showToast(`Session host ${N}: ${C.displayName}`,"success"),await p()}catch(F){const P=F instanceof Error?F.message:"Session host action failed";rt.showToast(P,"warning"),a(P)}finally{c(F=>F===H?null:F)}}},[e,p,r]),x=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 C=await r(e,"session_host_prune_duplicate_sessions",{}),H=Gn(C);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Duplicate prune failed");const F=H.result||{},P=Array.isArray(F.prunedSessionIds)?F.prunedSessionIds.length:0,N=typeof F.duplicateGroupCount=="number"?F.duplicateGroupCount:0;rt.showToast(`Pruned ${P} duplicate runtime(s) across ${N} group(s)`,"success"),await p()}catch(C){const H=C instanceof Error?C.message:"Duplicate prune failed";rt.showToast(H,"warning"),a(H)}finally{c(C=>C==="session_host_prune_duplicate_sessions"?null:C)}}},[e,p,r]),b=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((_,C)=>(C.lastActivityAt||0)-(_.lastActivityAt||0)),[d==null?void 0:d.sessions]),y=o.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:Lg(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),I=y.liveRuntimes,g=y.recoverySnapshots,T=y.inactiveRecords,A=o.useMemo(()=>Eg(I),[I]),j=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),v=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[d==null?void 0:d.recentLogs]),K=(_,C)=>{var U;const H=i===`session_host_resume_session:${_.sessionId}`,F=i===`session_host_restart_session:${_.sessionId}`,P=i===`session_host_stop_session:${_.sessionId}`,N=Pl(_.meta),M=k.get(_.sessionId),O=_.attachedClients.length===1?"1 client":`${_.attachedClients.length} clients`,$=C==="recovery"?"Recover":"Resume",E=_g(C);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:_.displayName||(M==null?void 0:M.cliName)||_.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Dg(_.lifecycle)}`,children:_.lifecycle}),N&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:N})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:_.workspaceLabel||(M==null?void 0:M.runtimeWorkspaceLabel)||_.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:_.runtimeKey}),_.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",_.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((U=_.writeOwner)==null?void 0:U.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Pg(_.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx($i,{size:11})," ",O]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",ki(_.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",E]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[C==="recovery"&&(_.lifecycle==="interrupted"||_.lifecycle==="failed"||_.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{S("session_host_resume_session",_)},children:H?`${$}ing…`:$}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{S("session_host_restart_session",_)},children:F?"Restarting…":"Restart"}),C==="live"&&(_.lifecycle==="running"||_.lifecycle==="starting"||_.lifecycle==="interrupted")&&s.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:()=>{S("session_host_stop_session",_)},children:P?"Stopping…":"Stop"})]})]})},_.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(ls,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:op()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[A>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{x()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${A})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||l,children:[s.jsx(or,{size:13}),h||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&s.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:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(sr,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:g.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:ki(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:qn(d.hostStartedAt)})]})]}),v&&s.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:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(sr,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:v.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[qn(v.timestamp),v.sessionId?` · ${v.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ia,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Vn("live")}),I.length===0?s.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."}):s.jsx("div",{className:"space-y-2",children:I.map(_=>K(_,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(ls,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Vn("recovery")}),g.length===0?s.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."}):s.jsx("div",{className:"space-y-2",children:g.map(_=>K(_,"recovery"))})]}),T.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Vn("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:T.map(_=>K(_,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),j.length===0?s.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."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:j.map(_=>{var H;const C=b.find(F=>F.sessionId===_.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(C==null?void 0:C.displayName)||((H=k.get(_.sessionId))==null?void 0:H.cliName)||_.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[_.action,_.lifecycle?` · ${_.lifecycle}`:"",_.detail?` · ${_.detail}`:"",_.error?` · ${_.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${_.success===!1?"text-red-300":"text-text-secondary"}`,children:qn(_.timestamp)})]},`${_.sessionId}:${_.timestamp}:${_.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Bg({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.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:s.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:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.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."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.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=>s.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:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Yn({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function Xn({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function Kg({machineEntry:e,providers:t,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=Js(e,"0.9.65");return s.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&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Yn,{icon:s.jsx(Ft,{size:13}),children:"Current Chats"}),s.jsx(Xn,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(h=>{const f=ua(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:ot(h)}),f>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:rn(f)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:us(h)})]},h.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Yn,{icon:s.jsx(Wi,{size:13}),children:"Recent Launches"}),s.jsx(Xn,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(h=>{const{metaText:f,updatedLabel:w}=fl(h);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(h),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:h.label}),w&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:f})]},h.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Yn,{icon:s.jsx(sr,{size:13}),children:"Daemon Update"}),s.jsx(Xn,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d?"Daemon update required":"Version mismatch detected"}),s.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),s.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:[s.jsx(or,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Og(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function Wg({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:i,onCustomPathChange:c,onOpenBrowseDialog:l}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,onChange:u=>{const m=u.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?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(u=>s.jsxs("option",{value:u.id,children:[u.id===e.defaultWorkspaceId?"⭐ ":"",an(u.path,u.label)]},u.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.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…"}):s.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:u=>c(u.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}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.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?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const Hg={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 Mr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Jn({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:m,onOpenGitDialog:d}){const h=_s(),{handleLaunchIde:f,handleStopCli:w,handleRestartIde:k,handleStopIde:p,handleDetectIdes:S,launchingIde:x,launchingAgentType:b,addLog:y}=c,[I,g]=o.useState(null),T=o.useCallback(B=>{B&&h(Gt(B))},[h]),A=Hg[e],j=e==="ide",v=e==="acp",K=o.useMemo(()=>n.filter(B=>fs(B,e)),[e,n]),_=o.useMemo(()=>new Map(K.map(B=>[B.type,B.displayName||B.type])),[K]),[C,H]=o.useState(""),[F,P]=o.useState(""),[N,M]=o.useState([]),[O,$]=o.useState(""),[E,U]=o.useState(""),[X,he]=o.useState([]),[ce,te]=o.useState(!1),[ye,fe]=o.useState(!1),[be,J]=o.useState(""),[ae,ge]=o.useState(!1),[ee,de]=o.useState(()=>xt()),[we,ue]=o.useState(null),[xe,se]=o.useState(m?"__custom__":u||t.defaultWorkspaceId||""),[ie,re]=o.useState(m||""),[G,Y]=o.useState([]),[le,ke]=o.useState(!1),[Z,Ce]=o.useState(""),[Pe,We]=o.useState([]),[He,D]=o.useState(!1),[Se,Ie]=o.useState(""),Re=o.useRef(null),[Ee,Fe]=o.useState(null),Ue=o.useRef("__home__"),[Je,dt]=o.useState("__home__"),[ut,lt]=o.useState(!1),Te=o.useRef(0),Ge=G.filter(B=>!a.some(oe=>oe.type===B&&yt(oe.status)!=="stopped")),Qe=o.useRef({});o.useEffect(()=>{t.defaultWorkspaceId&&!xe&&se(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),o.useEffect(()=>{if(m){se("__custom__"),re(m);return}u&&(se(u),re(""))},[u,m]),o.useEffect(()=>{j||C&&(K.some(B=>B.type===C)||(H(""),U("")))},[K,j,C]);const qe=(()=>{if(xe==="__custom__")return ie.trim();if(!xe)return"";const B=(t.workspaces||[]).find(oe=>oe.id===xe);return(B==null?void 0:B.path)||""})(),tt=o.useCallback(B=>{const oe=Qe.current[B];oe&&(clearTimeout(oe),delete Qe.current[B]),Y(pe=>pe.includes(B)?pe.filter(Ke=>Ke!==B):pe)},[]),W=o.useRef(new Set),z=o.useCallback(async B=>{if(l){D(!0),Ie("");try{const oe=await un(l,r,B);Ce(oe.path),re(oe.path),We(oe.directories)}catch(oe){Ie(oe instanceof Error?oe.message:"Could not load folder")}finally{D(!1)}}},[r,l]),R=o.useCallback(()=>{if(!l)return;se("__custom__"),ke(!0);const B=a.map(pe=>pe.workspace),oe=dn(t.platform,ln(ie.trim(),qe,m,B,t.defaultWorkspacePath,(t.workspaces||[]).map(pe=>pe.path)));z(oe)},[ie,m,z,t.defaultWorkspacePath,t.platform,t.workspaces,a,qe,l]),V=o.useCallback(B=>{const oe=String(B.workspace||"").trim();if(!oe)return;const pe=(t.workspaces||[]).find(Ke=>Mr(Ke.path)===Mr(oe));if(pe){se(pe.id),re("");return}se("__custom__"),re(oe)},[t.workspaces]),L=o.useCallback(B=>{const oe=String(B.workspace||"").trim();if(!oe)return{workspaceId:null,workspacePath:"",useHome:!0};const pe=(t.workspaces||[]).find(Ke=>Mr(Ke.path)===Mr(oe));return pe?{workspaceId:pe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:oe,useHome:!1}},[t.workspaces]),q=o.useCallback(async B=>{if(!l||!B||e!=="cli"){he([]),te(!1),fe(!1),J("");return}const oe=Te.current+1;Te.current=oe,te(!0),J("");try{const pe=await l(r,"list_saved_sessions",{providerType:B,kind:"cli",limit:30});if(Te.current!==oe)return;const Ke=(pe==null?void 0:pe.result)??pe;he(Array.isArray(Ke==null?void 0:Ke.sessions)?Ke.sessions:[])}catch(pe){if(Te.current!==oe)return;he([]),J(pe instanceof Error?pe.message:"Could not load saved sessions")}finally{Te.current===oe&&(te(!1),fe(!0))}},[e,r,l]),Q=o.useMemo(()=>{if(e!=="cli"||!C)return null;const B=_.get(C)||C;return{routeId:r,daemonId:r,providerSessionId:E||void 0,transport:"pty",mode:"chat",agentName:B,agentType:C,status:"idle",title:B,messages:[],ideType:C,workspaceName:qe,workspacePath:qe,displayPrimary:B,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${C}`}},[e,r,_,qe,E,C]),ne=o.useCallback(B=>{if(e==="ide"||!B){M([]);return}M(Tl(r,B))},[e,r]);o.useEffect(()=>{Te.current+=1,U(""),ne(C),fe(!1),he([]),J(""),te(!1)},[e,ne,q,C]);const ve=o.useMemo(()=>X.find(B=>B.providerSessionId===E)||null,[X,E]);o.useEffect(()=>{if(!E)return;const B=X.find(oe=>oe.providerSessionId===E);B!=null&&B.canResume||U("")},[X,E]);const Ae=o.useCallback((B,oe)=>{Re.current=oe,Ue.current=B.selectedWorkspaceKey||"__home__",dt(B.selectedWorkspaceKey||"__home__"),Fe(B)},[]),_e=o.useCallback(()=>{Re.current&&(lt(!0),Re.current().finally(()=>{Re.current=null,lt(!1),Fe(null)}))},[]),Ne=o.useCallback(B=>{if(!B)return;Y(pe=>pe.includes(B)?pe:[...pe,B]);const oe=Qe.current[B];oe&&clearTimeout(oe),Qe.current[B]=setTimeout(()=>{Y(pe=>pe.includes(B)?pe.filter(Ke=>Ke!==B):pe),delete Qe.current[B]},2e4)},[]);o.useEffect(()=>{for(const oe of a)yt(oe.status)!=="stopped"&&(G.includes(oe.type)&&!W.current.has(oe.type)&&(W.current.add(oe.type),y("info",`${_.get(oe.type)||oe.type} launched`,!0)),tt(oe.type));const B=new Set(a.filter(oe=>yt(oe.status)!=="stopped").map(oe=>oe.type));W.current.forEach(oe=>{!G.includes(oe)&&!B.has(oe)&&W.current.delete(oe)})},[y,tt,a,G,_]),o.useEffect(()=>()=>{Object.values(Qe.current).forEach(clearTimeout),Qe.current={}},[]);const[De,Be]=o.useState({}),[Le,ze]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const oe=await l(r,"get_ide_extensions",{}),pe=(oe==null?void 0:oe.result)||oe;pe!=null&&pe.success&&(pe!=null&&pe.ideExtensions)&&Be(pe.ideExtensions)}catch{}})()},[j,r,l]);const Ze=B=>j?at(B.type):e==="cli"?B.cliName:B.acpName,mt=j?t.detectedIdes||[]:[],pt=o.useCallback(async B=>{const oe=(B==null?void 0:B.type)||C,pe=(B==null?void 0:B.workspacePath)??qe;if(j){await f(oe,pe?{workspace:pe}:void 0)&&Ne(oe);return}const Ke=await c.runLaunchCliCore({cliType:oe,dir:B!=null&&B.workspaceId?void 0:pe||void 0,workspaceId:(B==null?void 0:B.workspaceId)||void 0,useHome:(B==null?void 0:B.useHome)||!(B!=null&&B.workspaceId)&&!pe,argsStr:(B==null?void 0:B.argsStr)??(F||void 0),model:(B==null?void 0:B.model)??(v&&O||void 0),resumeSessionId:(B==null?void 0:B.resumeSessionId)||!v&&e==="cli"&&oe===C&&E||void 0});if(Ke.success||Ke.pending){const Me=(B==null?void 0:B.argsStr)??F;!j&&(Me!=null&&Me.trim())&&(Al(r,oe,Me),ne(oe)),Ne(oe),Ke.success&&Ke.sessionId&&T(Ke.sessionId)}},[c,f,v,j,F,O,ne,Ne,r,T,qe,E,C]),ht=Dc(j?"ide":v?"acp":"cli",!j&&!v&&!!E),me=Ec(j?"ide":v?"acp":"cli",!j&&!v&&!!E),je=()=>{var Me;const B=j?at(C):_.get(C)||C,oe=!j&&!v&&!!E,{options:pe,selectedKey:Ke}=os({machine:t,currentWorkspaceId:xe&&xe!=="__custom__"?xe:null,currentWorkspacePath:qe});Ae({title:oe?Ga(B):ss("start-fresh",B),description:oe?qa():rs("start-fresh"),confirmLabel:ht,busyLabel:me,workspaceOptions:pe,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:A.label},{label:"Provider",value:B},...!j&&e==="cli"&&E?[{label:"Resume",value:((Me=X.find($e=>$e.providerSessionId===E))==null?void 0:Me.title)||E}]:[],...!j&&F.trim()?[{label:"Arguments",value:F.trim()}]:[],...v&&O.trim()?[{label:"Model",value:O.trim()}]:[]]},async()=>{const $e=pe.find(nt=>nt.key===Ue.current);$e!=null&&$e.workspaceId?(se($e.workspaceId),re("")):$e!=null&&$e.workspacePath?(se("__custom__"),re($e.workspacePath)):(se(""),re("")),await pt({workspaceId:($e==null?void 0:$e.workspaceId)??null,workspacePath:($e==null?void 0:$e.workspacePath)??"",useHome:!($e!=null&&$e.workspaceId)&&!($e!=null&&$e.workspacePath)})})},bt=B=>{j?p(B):w(B.type,B.workspace,B.id)},wt=o.useCallback(async(B,oe,pe=!1)=>{if(B.mode===oe){pe&&B.sessionId&&T(B.sessionId);return}if(!l||!B.sessionId){pe&&B.sessionId&&T(B.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:B.sessionId,cliType:B.type,mode:oe}),pe&&T(B.sessionId)}catch(Ke){const Me=sl(Ke);tl(Ke)?console.warn(Me?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ke instanceof Error?Ke.message:String(Ke)):console.error("Failed to switch CLI view mode:",Ke)}},[r,T,l]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${A.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",A.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?mt.length>0?mt.map(B=>{const oe=a.find(nt=>(nt.type||"").toLowerCase()===(B.type||"").toLowerCase()&&yt(nt.status)!=="stopped"),pe=B.running||!!oe,Ke=!!oe&&oe.cdpConnected,Me=G.includes(B.type||B.id||""),$e=C===(B.type||"");return s.jsxs("button",{onClick:()=>{if(Ke&&oe){const nt=oe.sessionId;nt?h(Gt(nt),{state:{openRemoteForTabKey:nt}}):h("/dashboard",{state:{openRemoteForTabKey:oe.id}});return}Me||H(nt=>nt===(B.type||"")?"":B.type||"")},disabled:!!x||Me,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ke?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":$e?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:x&&x!==B.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(B.type)}),pe&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ke?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:B.name||at(B.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ke?"text-green-400":Me?"text-orange-400":$e?"text-accent-primary":"text-text-muted"}`,children:Ke?"Open Session":Me?"Starting...":$e?"Configure":"Select"})]})]},B.type)}):s.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.",s.jsxs("button",{onClick:S,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:[s.jsx(Ud,{size:14})," Scan System"]})]}):K.length>0?K.map(B=>{const oe=C===B.type,pe=G.includes(B.type),Me=!!a.find($e=>$e.type===B.type&&yt($e.status)!=="stopped");return s.jsxs("button",{onClick:()=>H($e=>$e===B.type?"":B.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${oe?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:B.icon}),Me&&s.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)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:B.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${pe?"text-orange-400":oe?"text-accent-primary":"text-text-muted"}`,children:pe?"Starting...":oe?"Configure":"Select"})]})]},B.type)}):s.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.",s.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."})]})}),C&&(j?mt.find(B=>B.type===C):K.find(B=>B.type===C))&&s.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:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:j?at(C):_.get(C)||C})]}),s.jsx(Wg,{machine:t,selectedWorkspace:xe,resolvedWorkspacePath:qe,customPath:ie,canBrowse:!!l,onWorkspaceChange:se,onCustomPathChange:re,onOpenBrowseDialog:R}),!j&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&s.jsx(Ml,{busy:!!b||!!x||G.includes(C),savedSessionsLoading:ce,savedSessionsError:be,savedSessionsLoaded:ye,savedSessionsCount:X.length,selectedSession:ve,onRefresh:()=>void q(C),onOpenHistory:()=>{C&&(ge(!0),Il({hasLoadedInitialResults:ye,isLoading:ce})&&q(C))},onClearSelection:()=>U("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:O,onChange:B=>$(B.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"})]}),s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:F,onChange:B=>P(B.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"}),N.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:N.map(B=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>P(B),title:B,children:B},B))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:je,disabled:!!b||!!x||G.includes(C),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:b===C||x===C?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+G.filter(B=>!a.some(oe=>oe.type===B&&yt(oe.status)!=="stopped")).length,")"]}),a.length===0&&Ge.length===0?s.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 ",A.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ge.map(B=>s.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:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(B)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?at(B):_.get(B)||B}),s.jsx("div",{className:"text-[11px] text-text-muted",children:b===B?"Launching process...":"Waiting for process and session to register..."})]})]}),s.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:${B}`)),a.map(B=>{const oe=j?B:null,pe=!j&&!v?B:null,Ke=yt(B.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:i(B.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ze(B),(oe==null?void 0:oe.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",oe.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:B.workspace||"—"}),d&&B.git&&B.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Me=>{Me.stopPropagation(),d(B.daemonId??r,B.workspace)},children:s.jsx(Is,{git:B.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Is,{git:B.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(pe==null?void 0:pe.mode)&&s.jsx("span",{className:pe.mode==="chat"?"text-violet-400":"text-text-secondary",children:pe.mode==="chat"?"Chat view":"Terminal view"})]}),pe&&(pe.runtimeKey||pe.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[pe.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",pe.runtimeKey]}),s.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 ${pe.runtimeKey}`),g(pe.runtimeKey||null),window.setTimeout(()=>{g($e=>$e===pe.runtimeKey?null:$e)},1200)},children:I===pe.runtimeKey?"Copied":"Copy"})]}),pe.runtimeWriteOwner&&s.jsx("span",{style:{color:pe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:pe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Og(pe.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ke==="stopped"?"bg-red-500/[0.08] text-red-500":Ke==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ke}),j&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Me=B.sessionId;if(Me){h(Gt(Me),{state:{openRemoteForTabKey:Me}});return}h("/dashboard",{state:{openRemoteForTabKey:B.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:s.jsx(Tt,{size:13})}),s.jsx("button",{onClick:()=>{const Me=B.workspace||"",{options:$e,selectedKey:nt}=os({machine:t,currentWorkspacePath:Me});Ae({title:ss("restart-ide",at(B.type)),description:rs("restart-ide"),confirmLabel:Ms("restart-ide"),busyLabel:Rs("restart-ide"),workspaceOptions:$e,selectedWorkspaceKey:nt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:at(B.type)}]},async()=>{const jt=$e.find(Ut=>Ut.key===Ue.current),ct=(jt==null?void 0:jt.workspacePath)??"";if(ct&&ct!==Me){await pt({type:B.type,workspacePath:ct});return}await k(B)})},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:s.jsx(or,{size:14})})]}),v&&s.jsx("button",{onClick:()=>{const Me=B.sessionId;Me&&T(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:!B.sessionId,children:s.jsx(Ft,{size:14})}),pe&&Ke!=="stopped"&&s.jsxs(s.Fragment,{children:[pe.mode&&s.jsx(Ua,{mode:pe.mode,onChange:Me=>void wt(pe,Me,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Me=B.sessionId;Me&&T(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:!B.sessionId,children:pe.mode==="chat"?s.jsx(Ft,{size:14}):s.jsx(Tt,{size:13})})]}),Ke==="stopped"?s.jsx("button",{onClick:()=>{const Me=B.workspace||"",$e=j?at(B.type):Ze(B),{options:nt,selectedKey:jt}=os({machine:t,currentWorkspacePath:Me});Ae({title:ss("restart-stopped",$e),description:rs("restart-stopped"),confirmLabel:Ms("restart-stopped"),busyLabel:Rs("restart-stopped"),workspaceOptions:nt,selectedWorkspaceKey:jt,details:[{label:"Mode",value:A.label},{label:"Provider",value:$e}]},async()=>{const ct=nt.find(Ut=>Ut.key===Ue.current);await pt({type:B.type,workspaceId:(ct==null?void 0:ct.workspaceId)??null,workspacePath:(ct==null?void 0:ct.workspacePath)??"",useHome:!(ct!=null&&ct.workspaceId)&&!(ct!=null&&ct.workspacePath)})})},disabled:G.includes(B.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:G.includes(B.type)?"⏳":s.jsx(Ma,{size:14})}):s.jsx("button",{onClick:()=>bt(B),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:s.jsx(St,{size:14})})]})]}),oe&&oe.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:oe.aiAgents.map(Me=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Ji(Me.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Me.name," · ",yt(Me.status)]},Me.id))}),oe&&(De[oe.type]||[]).length>0&&l&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(De[oe.type]||[]).map(Me=>s.jsxs("button",{disabled:Le===`${oe.type}.${Me.type}`,onClick:async()=>{const $e=`${oe.type}.${Me.type}`;ze($e);try{await l(r,"set_ide_extension",{ideType:oe.type,extensionType:Me.type,enabled:!Me.enabled}),Be(nt=>({...nt,[oe.type]:(nt[oe.type]||[]).map(jt=>jt.type===Me.type?{...jt,enabled:!jt.enabled}:jt)}))}catch(nt){console.error("Extension toggle failed:",nt)}finally{ze(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:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Me.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Me.name,s.jsx("span",{className:"text-[9px] font-normal",children:Me.enabled?"ON":"OFF"})]},Me.type))})]})]},B.id)})]}),le&&l&&s.jsx(mn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:Z,directories:Pe,busy:He,error:Se,confirmLabel:"Use this folder",onClose:()=>ke(!1),onNavigate:B=>{z(B)},onConfirm:B=>{re(B),se("__custom__"),ke(!1)}}),Ee&&s.jsx(no,{title:Ee.title,description:Ee.description,details:Ee.details,workspaceOptions:Ee.workspaceOptions,selectedWorkspaceKey:Je,onWorkspaceChange:B=>{Ue.current=B,dt(B)},confirmLabel:Ee.confirmLabel,busyLabel:Ee.busyLabel,busy:ut,onConfirm:_e,onCancel:()=>{Re.current=null,Fe(null)}}),ae&&Q&&s.jsx(Ya,{activeConv:Q,ides:[],isCreatingChat:!1,isRefreshingHistory:ce,savedSessions:X,isSavedSessionsLoading:ce,isResumingSavedSessionId:we,savedHistoryFilters:ee,missingWorkspaceResumePath:qe||null,onSavedHistoryFiltersChange:de,onClose:()=>ge(!1),onNewChat:()=>{U(""),ge(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{q(C)},onResumeSavedSession:B=>{if(!B.canResume||we)return;const oe=L(B);U(B.providerSessionId),V(B),ue(B.providerSessionId),ge(!1),pt({type:B.providerType,workspaceId:oe.workspaceId,workspacePath:oe.workspacePath,useHome:oe.useHome,resumeSessionId:B.providerSessionId}).finally(()=>{ue(pe=>pe===B.providerSessionId?null:pe)})}})]})}const Si=[{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 Fg({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:m,initialWorkspacePath:d,sendDaemonCommand:h,onOpenGitDialog:f}){var S;const[w,k]=o.useState(u);o.useEffect(()=>{k(u)},[u]);const p=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Si.map(x=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${w===x.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>k(x.id),children:[s.jsx("span",{children:x.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${w===x.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[x.id]})]},x.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(S=Si.find(x=>x.id===w))==null?void 0:S.helper})]}),w==="ide"&&s.jsx(Jn,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d,onOpenGitDialog:f}),w==="cli"&&s.jsx(Jn,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d,onOpenGitDialog:f}),w==="acp"&&s.jsx(Jn,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:d,onOpenGitDialog:f})]})}function Ug({onNicknameSynced:e}={}){var re,G,Y,le,ke,Z,Ce,Pe,We,He;const{id:t}=fd(),r=_s(),n=Sa(),{sendCommand:a}=ft(),i=dr(),c=Jc(),l=Tc(),u=l.ides||[],m=l.initialLoaded??!0,d=u.find(D=>D.id===t&&D.type==="adhdev-daemon"),h=u.some(D=>D.type==="adhdev-daemon"),f=t?(re=l.connectionRetryStatuses)==null?void 0:re[t]:void 0,w=!!(f!=null&&f.blocked),[k,p]=o.useState("workspace"),[S,x]=o.useState(null),b=o.useCallback((D,Se)=>{x({daemonId:D,workspace:Se})},[]),[y,I]=o.useState("ide"),g=o.useRef(null),[T,A]=o.useState(null),j=o.useRef("__home__"),[v,K]=o.useState("__home__"),[_,C]=o.useState(!1),H=o.useRef(null);o.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(t,{minFreshMs:3e4}).catch(()=>{})},[i,d,t]),o.useEffect(()=>{if(!t||!d||k!=="overview")return;const D=d.machine;(typeof(D==null?void 0:D.cpus)!="number"||typeof(D==null?void 0:D.totalMem)!="number"||typeof(D==null?void 0:D.arch)!="string"||typeof(D==null?void 0:D.release)!="string")&&c(t,{minFreshMs:3e4}).catch(()=>{})},[k,c,d,t]),Zp(t&&k==="overview"?[t]:[],{enabled:k==="overview",intervalMs:Qm});const F=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},P=Kb({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:H});o.useEffect(()=>rt.onToast(Se=>{l.setToasts(Re=>{if(Re.some(Ue=>Ue.message===Se.message&&Se.timestamp-Ue.timestamp<3e3))return Re;const Fe={id:Se.id,message:Se.message,type:Se.type,timestamp:Se.timestamp,targetKey:Se.targetKey,actions:Se.actions};return[...Re.slice(-4),Fe]});const Ie=Se.duration||5e3;setTimeout(()=>l.setToasts(Re=>Re.filter(Ee=>Ee.id!==Se.id)),Ie)}),[l]);const N=(d==null?void 0:d.availableProviders)||[],M={};for(const D of N)M[D.type]=D.icon;const O=D=>M[D]||"",$=d?{id:d.id,hostname:Qi(d,{fallbackId:d.id}),platform:((G=d.machine)==null?void 0:G.platform)||"unknown",arch:((Y=d.machine)==null?void 0:Y.arch)||"",cpus:((le=d.machine)==null?void 0:le.cpus)||0,totalMem:((ke=d.machine)==null?void 0:ke.totalMem)||0,freeMem:(Z=d.machine)==null?void 0:Z.freeMem,availableMem:(Ce=d.machine)==null?void 0:Ce.availableMem,loadavg:(Pe=d.machine)==null?void 0:Pe.loadavg,uptime:(We=d.machine)==null?void 0:We.uptime,release:((He=d.machine)==null?void 0:He.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,E=u.filter(D=>D.daemonId===t&&D.type!=="adhdev-daemon").filter(D=>!nr(D)&&!ws(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,version:D.version||"",instanceId:D.instanceId||"",status:D.status,workspace:D.workspace||null,terminals:D.terminals||0,aiAgents:Vu(D.aiAgents||(D.agents||[]).map(Se=>({id:Se.name,name:Se.name,status:Se.status,version:Se.version}))),activeChat:D.activeChat||null,chats:D.chats||[],childSessions:D.childSessions||[],cdpConnected:D.cdpConnected||!1,daemonId:t})),U=u.filter(D=>D.daemonId===t&&nr(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,cliName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,mode:D.mode,runtimeKey:D.runtimeKey,runtimeDisplayName:D.runtimeDisplayName,runtimeWorkspaceLabel:D.runtimeWorkspaceLabel,runtimeWriteOwner:D.runtimeWriteOwner||null,runtimeAttachedClients:D.runtimeAttachedClients||[],daemonId:t})),X=u.filter(D=>D.daemonId===t&&ws(D)).map(D=>({id:D.id,sessionId:D.sessionId,type:D.type,acpName:D.cliName||D.type,status:D.status,workspace:D.workspace||"",activeChat:D.activeChat||null,providerSessionId:D.providerSessionId,daemonId:t})),he=d?Ct(d,{fallbackId:t}):"",ce="workspace",te=n.state,ye=te==null?void 0:te.initialMachineTab,fe=te==null?void 0:te.initialWorkspaceCategory,be=te==null?void 0:te.initialWorkspaceId,J=te==null?void 0:te.initialWorkspacePath,ae=ye==="ides"||ye==="clis"||ye==="acps"?"workspace":ye||ce,ge=ye==="ides"?"ide":ye==="clis"?"cli":ye==="acps"?"acp":fe,ee=[...E.map(D=>{var Se,Ie,Re,Ee,Fe;return{id:`ide:${D.type}:${D.workspace||""}`,label:((Se=D.activeChat)==null?void 0:Se.title)||D.type,kind:"ide",providerType:D.type,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Fe=(Ee=(Re=(Ie=D.activeChat)==null?void 0:Ie.messages)==null?void 0:Re.at)==null?void 0:Ee.call(Re,-1))==null?void 0:Fe.timestamp)||0}}),...U.map(D=>{var Se,Ie,Re,Ee,Fe;return{id:`cli:${D.type}:${D.workspace||""}`,label:((Se=D.activeChat)==null?void 0:Se.title)||D.cliName,kind:"cli",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Fe=(Ee=(Re=(Ie=D.activeChat)==null?void 0:Ie.messages)==null?void 0:Re.at)==null?void 0:Ee.call(Re,-1))==null?void 0:Fe.timestamp)||0}}),...X.map(D=>{var Se,Ie,Re,Ee,Fe;return{id:`acp:${D.type}:${D.workspace||""}`,label:((Se=D.activeChat)==null?void 0:Se.title)||D.acpName,kind:"acp",providerType:D.type,providerSessionId:D.providerSessionId,subtitle:ds(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace||void 0,lastLaunchedAt:((Fe=(Ee=(Re=(Ie=D.activeChat)==null?void 0:Ie.messages)==null?void 0:Re.at)==null?void 0:Ee.call(Re,-1))==null?void 0:Fe.timestamp)||0}})].sort((D,Se)=>(Se.lastLaunchedAt||0)-(D.lastLaunchedAt||0)),de=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(D=>({id:D.id,label:D.title||D.providerName||D.providerType,kind:D.kind,providerType:D.providerType,providerSessionId:D.providerSessionId,subtitle:ds(D.summaryMetadata)||D.workspace||void 0,workspace:D.workspace,summaryMetadata:D.summaryMetadata,lastLaunchedAt:D.lastLaunchedAt})):ee,we=o.useMemo(()=>{var Se;const D=((Se=l.connectionStates)==null?void 0:Se[t||""])||void 0;return u.filter(Ie=>Ie.daemonId===t&&Ie.type!=="adhdev-daemon").flatMap(Ie=>Xa(Ie,{connectionStates:t&&D?{[t]:D}:void 0,defaultConnectionState:D})).filter(Ie=>!(Ie.transport==="pty"&&Ie.mode==="terminal")).sort((Ie,Re)=>ua(Re)-ua(Ie))},[u,l.connectionStates,t]),ue=o.useCallback(D=>{const Se=Ha(D);Se&&r(Gt(Se))},[r]),xe=o.useCallback(()=>{g.current&&(C(!0),g.current().finally(()=>{g.current=null,C(!1),A(null)}))},[]),se=o.useCallback(D=>{if(!$)return;const{options:Se,selectedKey:Ie}=os({machine:$,currentWorkspacePath:D.workspace}),Re=async()=>{I(D.kind),p("workspace")};g.current=async()=>{const Ee=Se.find(Je=>Je.key===j.current),Fe=(Ee==null?void 0:Ee.workspacePath)??null,Ue=(Ee==null?void 0:Ee.workspaceId)??null;if(D.kind==="ide"&&D.providerType){await P.handleLaunchIde(D.providerType,Fe?{workspace:Fe}:void 0);return}if((D.kind==="cli"||D.kind==="acp")&&D.providerType){await P.runLaunchCliCore({cliType:D.providerType,dir:Ue?void 0:Fe||"",workspaceId:Ue||void 0,model:D.kind==="acp"&&ec(D.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:D.providerSessionId});return}await Re()},j.current=Ie,K(Ie),A({title:D.kind==="ide"?ss("restart-ide",D.label):D.providerSessionId?Ga(D.label):ss("start-fresh",D.label),description:D.kind==="ide"?rs("restart-ide"):D.providerSessionId?qa():rs("start-fresh"),confirmLabel:D.kind==="ide"?Ms("restart-ide"):D.providerSessionId?Xr(!0):Ms("start-fresh"),busyLabel:D.kind==="ide"?Rs("restart-ide"):D.providerSessionId?za(!0):Rs("start-fresh"),workspaceOptions:Se,details:[{label:"Mode",value:D.kind.toUpperCase()},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]})},[P,$]);if(o.useEffect(()=>{p(ae)},[ce,ae,t]),o.useEffect(()=>{ge&&I(ge)},[ge,t]),!$)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:F,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const ie=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tt,{size:14})," Workspace"]}),count:E.length+U.length+X.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ls,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(tn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zd,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hd,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.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:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:F,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:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[P.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:P.nicknameInput,onChange:D=>P.setNicknameInput(D.target.value),onKeyDown:D=>{D.key==="Enter"&&P.handleSaveNickname(),D.key==="Escape"&&P.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]"}),s.jsx("button",{onClick:P.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"}),s.jsx("button",{onClick:()=>P.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"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{P.setEditingNickname(!0),P.setNicknameInput($.machineNickname||"")},title:"Click to set nickname",children:he}),w?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),l.retryConnection&&t&&s.jsx("button",{onClick:()=>l.retryConnection(t),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"})]}):s.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"})]}),s.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:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[$.platform," · ",$.arch]}),s.jsxs("span",{children:[$.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),$.p2p.available&&s.jsxs("span",{children:["P2P ",$.p2p.state==="connected"?"connected":$.p2p.state]}),$.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:$.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ie.map(D=>s.jsxs("button",{onClick:()=>p(D.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${k===D.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[D.label,D.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${k===D.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:D.count})]},D.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[k==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(Kg,{machineEntry:d,providers:N,recentLaunches:de,currentConversations:we,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",{})}catch{}},onOpenRecent:se,onOpenConversation:ue}),s.jsx(Fg,{machine:$,machineId:t,providers:N,ideSessions:E,cliSessions:U,acpSessions:X,actions:P,getIcon:O,initialCategory:y,initialWorkspaceId:be,initialWorkspacePath:J,sendDaemonCommand:a,onOpenGitDialog:b})]}),k==="providers"&&s.jsx(Yb,{machineId:t,providers:N,sendDaemonCommand:a}),k==="overview"&&s.jsx(Ob,{machineId:t,machine:$,ideSessions:E,cliSessions:U,acpSessions:X,actions:P,sendDaemonCommand:a}),k==="session-host"&&s.jsx($g,{machineId:t,cliSessions:U,sendDaemonCommand:a}),k==="logs"&&s.jsx(Mg,{machineId:t,sendDaemonCommand:a})]})})}),P.launchPick&&$&&s.jsx(Bg,{machine:$,launchPick:P.launchPick,actions:P}),T&&s.jsx(no,{title:T.title,description:T.description,details:T.details,workspaceOptions:T.workspaceOptions,selectedWorkspaceKey:v,onWorkspaceChange:D=>{j.current=D,K(D)},confirmLabel:T.confirmLabel,busyLabel:T.busyLabel,busy:_,onConfirm:xe,onCancel:()=>{g.current=null,A(null)}}),S&&s.jsx(Ll,{daemonId:S.daemonId,workspace:S.workspace,onClose:()=>x(null)}),s.jsx($c,{toasts:l.toasts||[],onDismiss:D=>l.setToasts(Se=>Se.filter(Ie=>Ie.id!==D)),onClickToast:D=>{D.targetKey&&r(Gt(D.targetKey))}}),s.jsx("style",{children:`
|
|
90
|
+
@keyframes toast-in {
|
|
91
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
92
|
+
to { opacity: 1; transform: translateX(0); }
|
|
93
|
+
}
|
|
94
|
+
`})]})}function lo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function zg(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=lo();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Dt(e,t){return await fetch(zg(e),{credentials:"same-origin",...t})}function Dl(){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 Vg{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(this,"statusCallbacks",new Set)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r)}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,i,c){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:i,rows:c})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,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 u=await i.json();u!=null&&u.error&&(l=u.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(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Kt=new Vg;function Gg(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=lo();return r?`${t}?token=${encodeURIComponent(r)}`:t}const Rr=Gg(),Ni=3e3,qg=3e4;let Lt=null,Yg=0;const en=new Map;let Xt=null,Zs=null;function Ci(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Us(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Xg(e){return e==="connected"?"connected":e}async function Or(e,t,r){const n=Oc(e,r||{}),a=Lt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Yg}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{en.delete(i),l(new Error(`WS command timeout: ${t}`))},3e4);en.set(i,{resolve:m=>{clearTimeout(u),c(m)},reject:m=>{clearTimeout(u),l(m)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function wa(e,t){const r=Lt;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function Jg(e,t,r){const n=Lt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=Oc(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class Qg{constructor(t){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=t}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(t,r){return Or(this.daemonId,t,r)}async sendInput(t,r){return Or(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Xt&&(clearInterval(Xt),Xt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Or(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(),Xt=setInterval(r,2e3)}stopScreenshots(t){Xt&&(clearInterval(Xt),Xt=null)}}let It=null;function Zg(e){return(!It||It.daemonId!==e)&&(It=new Qg(e)),It}function ey({children:e}){const t=o.useRef(tr()),r=tr();t.current=r;const{setUserName:n}=cs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((p,S)=>{l(p),Zs==null||Zs(p,S)},[]),m=o.useRef(null),d=o.useRef(),h=o.useRef(Ni),f=o.useRef(!0),w=o.useRef(!1),k=o.useRef("initial_connect");return o.useEffect(()=>{f.current=!0,w.current=!1;function p(){var b,y;if(!f.current||((b=m.current)==null?void 0:b.readyState)===WebSocket.OPEN||((y=m.current)==null?void 0:y.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Rr}...`),Us("connect_attempt",{url:Rr,reason:k.current,delayMs:h.current});let x;try{x=new WebSocket(Rr)}catch(I){console.error("[Standalone WS] Failed to create WebSocket:",I),S();return}m.current=x,x.onopen=()=>{if(!f.current){x.close();return}u("connected"),h.current=Ni,Us("open",{url:Rr,reason:k.current}),Ht.resubscribeAll({sendData:wa}),console.log("[Standalone WS] Connected")},Lt=x,x.onmessage=I=>{var g,T;try{const A=JSON.parse(I.data);if((A.type==="command_result"||A.type==="error")&&A.requestId){const j=en.get(A.requestId);j&&(en.delete(A.requestId),A.type==="error"?j.reject(new Error(((g=A.data)==null?void 0:g.message)||"Command failed")):j.resolve(A.data));return}if(A.type==="session_output"){const j=A.sessionId||A.cliId||A.cliType;j&&Kt.emitSessionOutput(j,typeof A.data=="string"?A.data:"",typeof A.seq=="number"?A.seq:void 0);return}if(A.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(A.sessionId,typeof A.text=="string"?A.text:"",typeof A.seq=="number"?A.seq:0,!!A.truncated,typeof A.cols=="number"?A.cols:void 0,typeof A.rows=="number"?A.rows:void 0);return}if(A.type==="topic_update"){const j=A.update;j&&Ht.publish(j);return}if(A.type==="status"||A.type==="initial_state"){const j=A.data;if(!j)return;const{injectEntries:v,markLoaded:K,getIdes:_}=t.current,C=j.instanceId||"standalone",H=_().find(N=>N.id===C),F=Zg(C);Kt.register(C,F),Kt.setState(C,"connected"),u("connected",C),Kt.emitStatus(C,j);const P=Yr(j,{daemonId:C,existingDaemon:H,existingEntries:_()});Ci("ws_status",{type:A.type,daemonId:C,sessions:(j.sessions||[]).map(N=>({id:N.id,parentId:N.parentId,providerType:N.providerType,kind:N.kind,transport:N.transport,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,title:N.title})),recentLaunches:(j.recentLaunches||[]).map(N=>({id:N.id,providerType:N.providerType,kind:N.kind,workspace:N.workspace,lastLaunchedAt:N.lastLaunchedAt}))}),Ci("entries",{daemonId:C,entries:P.filter(N=>N.type!=="adhdev-daemon").map(N=>({id:N.id,type:N.type,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,sessionId:N.sessionId}))}),P.length>0&&v(P,{authoritativeDaemonIds:[C]}),K(),c.current!==C&&((T=i.current)==null||T.call(i),c.current=C,i.current=Ht.subscribe({sendData:wa},C,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${C}`,params:{includeSessions:!0}},N=>{if(N.topic!=="daemon.metadata")return;const M=t.current.getIdes(),O=M.find(E=>E.id===C),$=Yr(N.status,{daemonId:C,existingDaemon:O,existingEntries:M,timestamp:N.timestamp});$.length>0&&t.current.injectEntries($,{authoritativeDaemonIds:[C]}),N.userName&&a.current&&a.current(N.userName)}))}}catch(A){console.error("[Standalone WS] Parse error:",A)}},x.onclose=I=>{f.current&&(It==null||It.stopScreenshots(),It&&Kt.setState(It.daemonId,"disconnected"),u("disconnected"),m.current=null,k.current=`close:${I.code}${I.wasClean?":clean":":unclean"}`,Us("close",{code:I.code,reason:I.reason||"",wasClean:I.wasClean}),S())},x.onerror=I=>{w.current||!f.current||(k.current="error",Us("error",{message:I instanceof Event?"event":String(I),readyState:x.readyState}),console.warn("[Standalone WS] Error, will reconnect:",I))}}function S(){if(!f.current)return;clearTimeout(d.current);const x=h.current;console.log(`[Standalone WS] Reconnecting in ${x}ms...`),Us("schedule_reconnect",{reason:k.current,delayMs:x}),d.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,qg),p()},x)}return p(),()=>{var x;f.current=!1,w.current=!0,(x=i.current)==null||x.call(i),i.current=null,c.current=null,clearTimeout(d.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Lt=null),It&&(It.stopScreenshots(),Kt.unregister(It.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function ty({children:e}){const[t,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Zs=(c,l)=>{r(c),l&&a(l)},()=>{Zs=null}),[]);const i=o.useMemo(()=>{const c=t==="connected",l=Xg(t),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:t,isConnected:c,connectionStates:u}},[t,n]);return s.jsx(Rd,{connectionOverrides:i,children:s.jsx(ey,{children:e})})}const El="adhdev_standalone_font_preferences",is={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},hn=[{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"}],ar=[{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"}],sy=new Set(hn.map(e=>e.id)),ry=new Set(ar.map(e=>e.id));function $t(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Wr("chat",t.chat),code:Wr("code",t.code),terminal:Wr("terminal",t.terminal)}}function Wr(e,t){const r=is[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?sy:ry).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function Hr(e,t){var a;const r=Wr(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?hn:ar;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function ny(e){const t=$t(e),r=Hr("chat",t.chat),n=Hr("code",t.code),a=Hr("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Qt(e,t=document.documentElement){const r=$t(e),n=ny(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))t.style.setProperty(a,i);return r}function ja(e){const t=$t(e);try{localStorage.setItem(El,JSON.stringify(t))}catch{}return t}function ay(){try{const e=localStorage.getItem(El);if(e)return $t(JSON.parse(e))}catch{}return is}function oy(){return Qt(ay())}function zs(e,t){var n;const r=e==="chat"?hn:ar;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const iy=[{id:"dashboard",path:"/dashboard",icon:s.jsx(Ei,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(ls,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:s.jsx(tn,{}),label:"Settings"}];function cy({children:e}){const t=_s(),r=Sa(),n=o.useMemo(()=>iy.map(i=>({...i,active:r.pathname.startsWith(i.path),onSelect:()=>t(i.path)})),[r.pathname,t]),a=o.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Bi,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(Ki,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Np,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.65"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.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:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const ly=[{icon:s.jsx(ls,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Ft,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Oi,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Tt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(rr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Bi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],dy=[{icon:s.jsx(Gd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Ei,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(sn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Wd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx($i,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Fd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],uy=[{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 my(){return s.jsxs(Uc,{icon:s.jsx(Ki,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.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.65"]}),children:[s.jsx(Nt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.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."}),s.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."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.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 ↗"}),s.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 ↗"}),s.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 ↗"})]})]})}),s.jsx(Nt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:ly.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.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]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(Nt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Wc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Fc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Hc.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(Nt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:dy.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.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]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(Nt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:uy.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(Vc,{icon:s.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:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(ru,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Qn(e,t,r){return{...e,[t]:r}}function Zn({surface:e,title:t,description:r,value:n,options:a,onChange:i}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.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=>s.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&s.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})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Hr(e,n)})]})]})]})}function fy({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.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&&s.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&&s.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}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Zn,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:hn,onChange:d=>i(Qn(e,"chat",d))}),s.jsx(Zn,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:ar,onChange:d=>i(Qn(e,"code",d))}),s.jsx(Zn,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:ar,onChange:d=>i(Qn(e,"terminal",d))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",zs("chat",e.chat.preset)," · Code: ",zs("code",e.code.preset)," · Terminal: ",zs("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",zs("chat",is.chat.preset)," / ",zs("code",is.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.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"}),s.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"}),s.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function py(){const{ides:e}=cs(),t=e.find(J=>J.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=ft(),{userName:a}=cs(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[m,d]=o.useState(null),[h,f]=o.useState(is),[w,k]=o.useState(!1),[p,S]=o.useState(""),[x,b]=o.useState(""),[y,I]=o.useState("127.0.0.1"),[g,T]=o.useState(""),[A,j]=o.useState(""),[v,K]=o.useState(""),[_,C]=o.useState(""),[H,F]=o.useState(""),[P,N]=o.useState(!1),M=async()=>{const ae=await(await Dt("/auth/session")).json();u(ae)},O=async()=>{const ae=await(await Dt("/api/v1/standalone/preferences")).json();d(ae),I(ae.standaloneBindHost);const ge=$t(ae.standaloneFontPreferences);f(ge),Qt(ge),ja(ge)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([M(),O()]).catch(J=>{C(J instanceof Error?J.message:String(J))})},[]),o.useEffect(()=>{Qt(h)},[h]);const $=J=>{const ae=J.target.value.trim();t!=null&&t.id&&ae!==a&&n(t.id,"set_user_name",{userName:ae}).catch(console.error)},[E,U]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),X=J=>{U(J);try{localStorage.setItem("adhdev_sound",J?"1":"0")}catch{}},he=async()=>{S(""),b(""),k(!0);try{const J=$t(h),ae=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:J})}),ge=await ae.json();if(!ae.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save standalone font preferences");const ee=$t(ge.standaloneFontPreferences);d(ge),f(ee),Qt(ee),ja(ee),b("Standalone chat fonts saved for this self-hosted dashboard.")}catch(J){S(J instanceof Error?J.message:String(J))}finally{k(!1)}},ce=()=>{const J=$t(m==null?void 0:m.standaloneFontPreferences);S(""),b(""),f(J),Qt(J)},te=()=>{S(""),b(""),f(is),Qt(is)},ye=async()=>{C(""),F(""),N(!0);try{const J=await Dt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:y})}),ae=await J.json();if(!J.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to save standalone network preference");d(ae),I(ae.standaloneBindHost),F(ae.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){C(J instanceof Error?J.message:String(J))}finally{N(!1)}},fe=async()=>{if(C(""),F(""),A.trim().length<4){C("Password must be at least 4 characters.");return}if(A!==v){C("New password and confirmation do not match.");return}N(!0);try{const J=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,newPassword:A})}),ae=await J.json();if(!J.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to save password");u(ae),await O(),T(""),j(""),K(""),F(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Dl()}catch(J){C(J instanceof Error?J.message:String(J))}finally{N(!1)}},be=async()=>{C(""),F(""),N(!0);try{const J=await Dt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,clear:!0})}),ae=await J.json();if(!J.ok)throw new Error((ae==null?void 0:ae.error)||"Failed to clear password");u(ae),await O(),T(""),j(""),K(""),F("Standalone password disabled.")}catch(J){C(J instanceof Error?J.message:String(J))}finally{N(!1)}};return s.jsxs(Uc,{icon:s.jsx(tn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(kr,{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)&&s.jsx(kr,{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."}),s.jsx(Nt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.65"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(Nt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.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."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.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:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:y==="127.0.0.1",onChange:()=>I("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.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."})]})]}),s.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:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:y==="0.0.0.0",onChange:()=>I("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.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."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{ye()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"Saving…":"Save default network mode"}),s.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","."]})]})]})}),s.jsx(Nt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.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."}),_&&s.jsx(kr,{variant:"error",children:_}),H&&s.jsx(kr,{variant:"success",children:H}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.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:g,onChange:J=>T(J.target.value)}),s.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:A,onChange:J=>j(J.target.value)}),s.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=>K(J.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{fe()},disabled:P,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:P?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{be()},disabled:P,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"})]})]})}),s.jsx(Nt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(J=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${J.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:J.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:J.type})]},J.type))})}),s.jsx(Nt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(Pp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(Nt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(Bp,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.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."}),s.jsx(Vp,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(fy,{value:h,savedValue:$t(m==null?void 0:m.standaloneFontPreferences),saving:w,error:p,notice:x,onChange:f,onSave:()=>{he()},onResetToSaved:ce,onResetToDefaults:te})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.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."}),s.jsx(Yp,{})]})]})}),s.jsx(Nt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Rp,{}),s.jsx(Jt,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(su,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:E,onChange:X})]})}),s.jsx(Nt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.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:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Od,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.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:$,onKeyDown:J=>{J.key==="Enter"&&J.currentTarget.blur()}})]})})})]})}kp();Up();oy();const hy=Pi({baseUrl:"",getToken:lo});function xy({children:e}){const[t,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[m,d]=o.useState(!1),h=async()=>{a(!0),u("");try{const k=await(await Dt("/auth/session")).json();r(k)}catch(w){u(w instanceof Error?w.message:String(w))}finally{a(!1)}};o.useEffect(()=>{h()},[]),o.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let w=!1;return(async()=>{try{const k=await Dt("/api/v1/standalone/preferences");if(!k.ok)return;const p=await k.json();if(w)return;const S=$t(p.standaloneFontPreferences);Qt(S),ja(S)}catch{}})(),()=>{w=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const f=async w=>{w.preventDefault(),d(!0),u("");try{const k=await Dt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),p=await k.json();if(!k.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),c(""),Dl()}catch(k){u(k instanceof Error?k.message:String(k))}finally{d(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.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:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.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."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:f,children:[s.jsx("input",{type:"password",value:i,onChange:w=>c(w.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.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"})]}):s.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&&s.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})]})}):s.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 Ti(){const{ides:e,initialLoaded:t}=cs();if(!t)return s.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?s.jsx(sa,{to:`/machines/${r.id}`,replace:!0}):s.jsx(sa,{to:"/dashboard",replace:!0})}function by(){const e=o.useMemo(()=>({sendCommand:Or,sendData:wa,sendPtyInput:Jg}),[]);return s.jsx(pd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Pd,{client:hy,children:s.jsx(xy,{children:s.jsx(ty,{children:s.jsx(Ed,{value:e,children:s.jsx(cy,{children:s.jsxs(hd,{children:[s.jsx(qt,{path:"/dashboard",element:s.jsx(Bb,{})}),s.jsx(qt,{path:"/machine",element:s.jsx(Ti,{})}),s.jsx(qt,{path:"/machines/:id",element:s.jsx(Ug,{})}),s.jsx(qt,{path:"/machines",element:s.jsx(Ti,{})}),s.jsx(qt,{path:"/about",element:s.jsx(my,{})}),s.jsx(qt,{path:"/settings",element:s.jsx(py,{})}),s.jsx(qt,{path:"*",element:s.jsx(sa,{to:"/dashboard",replace:!0})})]})})})})})})})}Bf({connectionManager:Kt});xd(document.getElementById("root")).render(s.jsx(by,{}));
|