@adhdev/daemon-standalone 0.8.70 → 0.8.72
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 +322 -188
- package/dist/index.js.map +1 -1
- package/package.json +5 -4
- package/public/assets/index-BVCb8njp.js +72 -0
- package/public/index.html +1 -1
- package/public/assets/index-DyAwVi5d.js +0 -72
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-fZXg9GuG.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Zc=Object.defineProperty;var el=(e,s,r)=>s in e?Zc(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Ye=(e,s,r)=>el(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as ea,a as ta,b as Uo,c as Fo,u as Ks,R as at,d as sr,t as tl,e as sl,D as rl,f as Kn,g as Bn,h as sa,i as nl,k as al,B as ol,l as il,m as ts,N as Wn,n as cl}from"./vendor-BRZ4K-AC.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const c of i.addedNodes)c.tagName==="LINK"&&c.rel==="modulepreload"&&n(c)}).observe(document,{childList:!0,subtree:!0});function r(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(a){if(a.ep)return;a.ep=!0;const i=r(a);fetch(a.href,i)}})();function ll(e={}){const s=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>s&&r.splice(0,r.length-s),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-a).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const Ts=ll();function Wa(e){const s={};for(const r of e)r.transport&&(s[r.transport]=(s[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:s}}function dl(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function ul(e,s){if(!e)return s??null;if(!s)return e??null;const r=Array.isArray(e.messages)&&e.messages.length>0?e.messages:s.messages,n=e.activeModal||(e.status==="waiting_approval"?s.activeModal:null);return{...s,...e,messages:r,activeModal:n,inputContent:e.inputContent??s.inputContent}}function Ys(e,s){const r=dl(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerSessionId:e.providerSessionId??(s==null?void 0:s.providerSessionId),providerName:r??(s==null?void 0:s.providerName)??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerName??e.providerType,title:e.title??(s==null?void 0:s.title)??r??(s==null?void 0:s.providerName)??e.providerName??e.providerType,workspace:e.workspace??(s==null?void 0:s.workspace)??null,mode:e.mode??(s==null?void 0:s.mode),capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??(s==null?void 0:s.capabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),activeChat:ul(e.activeChat,s==null?void 0:s.activeChat),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),summaryMetadata:e.summaryMetadata??(s==null?void 0:s.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash),unread:e.unread??(s==null?void 0:s.unread),lastSeenAt:e.lastSeenAt??(s==null?void 0:s.lastSeenAt),inboxBucket:e.inboxBucket??(s==null?void 0:s.inboxBucket),surfaceHidden:e.surfaceHidden??(s==null?void 0:s.surfaceHidden),resume:e.resume??(s==null?void 0:s.resume),runtimeKey:e.runtimeKey??(s==null?void 0:s.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(s==null?void 0:s.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(s==null?void 0:s.runtimeWorkspaceLabel)}}function Oa(e,s){if(!(s!=null&&s.length))return e;if(!(e!=null&&e.length))return s;const r=new Map(e.map(n=>[n.id,n]));return s.map(n=>{const a=r.get(n.id);return a?Ys(n,a):n})}const zo=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}),Vo=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ha(e){var r,n;let s=0;return"activeChat"in e&&(s+=4),(r=e.childSessions)!=null&&r.length&&(s+=2),e.workspace&&(s+=1),e.machine&&(s+=1),(n=e.agents)!=null&&n.length&&(s+=1),s}function un(e,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=s.version??r.version??e.version,i=s.serverVersion??e.serverVersion??r.serverVersion,c=s.versionMismatch===!0||e.versionMismatch===!0,l=s.versionUpdateRequired===!0||e.versionUpdateRequired===!0,u=s.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),u&&(n.versionUpdateReason=u),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((s.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function Kr(e){return Array.isArray(e)?e.map(Kr):!e||typeof e!="object"?e:Object.fromEntries(Object.entries(e).filter(([s])=>s!=="timestamp"&&s!=="_lastUpdate").sort(([s],[r])=>s.localeCompare(r)).map(([s,r])=>[s,Kr(r)]))}function ml(e,s){try{return JSON.stringify(Kr(e))===JSON.stringify(Kr(s))}catch{return!1}}function pr(e,s,r){return ml(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function pl(e,s,r){var u,p,m,f,w,k,T;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(d=>({...d,_lastUpdate:n}));const i=new Map;for(const d of s)i.set(d.id,d);for(const d of e){const b=i.get(d.id);if(!b){i.set(d.id,{...d,_lastUpdate:n});continue}const v=Ha(d),h=Ha(b);if(v>h){const C=(u=d.chats)!=null&&u.length?d.chats:b.chats,P=Oa(b.childSessions,d.childSessions),y=un(b,d,{...b,...d,chats:C,childSessions:P,_lastUpdate:n});i.set(d.id,pr(b,y,n))}else if(v<h){const C={};if(d.status&&d.status!==b.status&&(C.status=d.status),d.cdpConnected!==void 0&&(C.cdpConnected=d.cdpConnected),(p=d.chats)!=null&&p.length&&!((m=b.chats)!=null&&m.length)&&(C.chats=d.chats),d.machineNickname!==void 0&&d.machineNickname!==b.machineNickname&&(C.machineNickname=d.machineNickname),d.version!==void 0&&(C.version=d.version),d.serverVersion!==void 0&&(C.serverVersion=d.serverVersion),d.versionMismatch===!0&&(C.versionMismatch=!0),Object.keys(C).length>0){const P=un(b,d,{...b,...C,_lastUpdate:b._lastUpdate});i.set(d.id,pr(b,P,n))}else pr(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const C=d.timestamp||n,P=b._lastUpdate||b.timestamp||0;if(C>=P){const y=(f=d.chats)!=null&&f.length?d.chats:b.chats,S=Oa(b.childSessions,d.childSessions),j=un(b,d,{...b,...d,chats:y,childSessions:S,_lastUpdate:n});i.set(d.id,pr(b,j,n))}else(w=d.chats)!=null&&w.length&&!((k=b.chats)!=null&&k.length)&&i.set(d.id,{...b,chats:d.chats})}}const c=new Set(e.map(d=>d.id)),l=new Set;for(const d of e){const b=d.daemonId||((T=d.id)==null?void 0:T.split(":")[0]);b&&l.add(b)}for(const[d,b]of i){const v=b.daemonId||d.split(":")[0];if(!l.has(v))continue;if(a.has(v)&&!c.has(d)){i.delete(d);continue}const h=n-(b._lastUpdate||b.timestamp||0);(b.transport==="pty"&&!c.has(d)&&h>1e4||b.transport==="acp"&&!c.has(d)&&h>1e4||b.transport==="cdp-page"&&!c.has(d)&&h>3e4)&&i.delete(d)}for(const[d,b]of i)n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&i.delete(d);return Array.from(i.values())}function fl(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function hl({children:e,connectionOverrides:s}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,p]=o.useState(void 0),m=o.useRef(r);o.useEffect(()=>{m.current=r},[r]);const f=o.useCallback((v,h)=>{n(C=>{let P=!1;const y=C.map(S=>S.id!==v||S.chats===h?S:(P=!0,{...S,chats:h}));return P?y:C})},[]),w=o.useCallback((v,h)=>{n(C=>{const P=C.length===0?v:pl(v,C,h),y=!fl(C,P);return y&&Ts.record({kind:"dashboard.entries_applied",payload:{incoming:Wa(v),next:Wa(P)}}),y?P:C})},[]),k=o.useCallback(()=>i(!0),[]),T=o.useMemo(()=>({injectEntries:w,markLoaded:k,getIdes:()=>m.current}),[w,k]),d=s,b=o.useMemo(()=>({ides:r,updateRouteChats:f,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(d==null?void 0:d.wsStatus)??"connected",isConnected:(d==null?void 0:d.isConnected)??!0,connectionStates:(d==null?void 0:d.connectionStates)??{},connectionTransports:(d==null?void 0:d.connectionTransports)??{},showReconnected:(d==null?void 0:d.showReconnected)??!1,retryConnection:d==null?void 0:d.retryConnection,isP2PActive:(d==null?void 0:d.isP2PActive)??!1,p2pStates:(d==null?void 0:d.p2pStates)??{},userRole:d==null?void 0:d.userRole,userName:u,setUserName:p}),[r,f,a,c,d==null?void 0:d.wsStatus,d==null?void 0:d.isConnected,d==null?void 0:d.connectionStates,d==null?void 0:d.connectionTransports,d==null?void 0:d.showReconnected,d==null?void 0:d.retryConnection,d==null?void 0:d.isP2PActive,d==null?void 0:d.p2pStates,d==null?void 0:d.userRole,u]);return t.jsx(Vo.Provider,{value:T,children:t.jsx(zo.Provider,{value:b,children:e})})}function fs(){return o.useContext(zo)}function Br(){return o.useContext(Vo)}function Go(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${s}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),p=a(l),m=l.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return u&&m.searchParams.set("token",u),!l.startsWith("http")&&!s?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function c(l,u={}){const p={"Content-Type":"application/json",...u.headers||{}},m=r==null?void 0:r();m&&(p.Authorization=`Bearer ${m}`);const f=a(l),w=new AbortController,k=setTimeout(()=>w.abort(),15e3);try{const T=await fetch(f,{...u,headers:p,signal:w.signal});if(T.status===401)throw n==null||n(),new Error("Unauthorized");if(!T.ok){const d=await T.json().catch(()=>({error:T.statusText}));throw new Error(d.error||`API Error: ${T.status}`)}return T.json()}finally{clearTimeout(k)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,p={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),execTerminal:(l,u,p)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:p})}),sendAgentMessage:(l,u,p)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:p})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,p)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:p?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,p={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const xl=Go({baseUrl:"http://localhost:3847"}),bl=o.createContext(xl);function gl({client:e,children:s}){return t.jsx(bl.Provider,{value:e,children:s})}const yl={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},qo=o.createContext(yl);function vl({value:e,children:s}){return t.jsx(qo.Provider,{value:e,children:s})}function Mt(){return o.useContext(qo)}const Oe={size:18};function Yo({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function ra({size:e=Oe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Ut({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),t.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),t.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),t.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function na({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"9",cy:"7",r:"4"}),t.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),t.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function wl({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function jl({size:e=Oe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Xo({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),t.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),t.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),t.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function kl({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),t.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),t.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),t.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),t.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Xr({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Qo({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Sl({size:e=Oe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Ft({size:e=Oe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Tt({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function aa({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t.jsx("polyline",{points:"14 2 14 8 20 8"}),t.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),t.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Nl({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ms({size:e=Oe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function Bs({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"23 4 23 10 17 10"}),t.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function hs({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function rr({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M12 22v-5"}),t.jsx("path",{d:"M9 8V2"}),t.jsx("path",{d:"M15 8V2"}),t.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Jo({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),t.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Zo({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),t.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),t.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function ei({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Cl({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),t.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),t.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Qr({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Il({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function oa({size:e=Oe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Al({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function Nt({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Tl({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),t.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),t.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),t.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Ml({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),t.jsx("path",{d:"M12 2v6"}),t.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Ll({size:e=Oe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function _l({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),t.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function Jr({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),t.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Rl({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"5"}),t.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),t.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),t.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),t.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),t.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),t.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),t.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),t.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Pl({size:e=Oe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Dl({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function $l({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),t.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function El({size:e=Oe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Kl({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),t.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function Bl({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),t.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),t.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function Wl({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}function Ol({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Hl({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),t.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),t.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),t.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),t.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),t.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),t.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),t.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),t.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),t.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Ul({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),t.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function Fl({size:e=Oe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function Ua(e){return!!e&&typeof e=="object"&&"text"in e}function ia(e,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(i=>typeof i=="string"?i:Ua(i)?String(i.text||""):"").join(r):Ua(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Ls(e){return ia(e,{normalizeWhitespace:!0})}const mn=new Map;function Fa(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function ti(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function zl(e,s,r){return Number(e.receivedAt||r[Ss(e,s)]||0)||0}function si(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Vl(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function fr(e,s){if(!e)return s;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||s}catch{return e.split(/[\\/]/).filter(Boolean).pop()||s}}function pn(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 za(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):si(e)?t.jsx(ea,{remarkPlugins:[ta,Uo,Fo],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function hr({parts:e,renderAsPreformatted:s}){return t.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return t.jsx("div",{children:za(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=pn(r);return a?t.jsx("img",{src:a,alt:fr(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=pn(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=pn(r);return a?t.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:fr(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||fr(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=fr(r.resource.uri,"resource");if(r.resource.text)return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[t.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),za(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return t.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function Ss(e,s){const r=e,n=ia(e.content,{joiner:`
|
|
3
|
+
`});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${s}`].filter(Boolean).join("|")}const Gl=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(ea,{remarkPlugins:[ta],children:s.text}),t.jsx("span",{className:"action-time",children:ti(s.timestamp)})]})},(e,s)=>e.log===s.log),ql=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var S,j,g;const u=(s.role||"").toLowerCase(),p=u==="user"||u==="human",m=s.kind||(u==="tool"?"tool":"standard"),f=Vl(s.content)?s.content:null,w=!!(f!=null&&f.some(x=>x.type!=="text")),k=ia(s.content,{joiner:`
|
|
4
|
+
`});if(m==="thought"){const x=typeof((S=s.meta)==null?void 0:S.label)=="string"?s.meta.label:"Thought";return t.jsxs("div",{className:"self-start chat-msg-thought",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx(Ll,{size:13}),t.jsx("span",{children:x})]}),t.jsx("div",{className:"chat-msg-body",children:k})]})}if(m==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),w&&f?t.jsx("div",{className:"tool-text w-full",children:t.jsx(hr,{parts:f,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:k})]});if(m==="terminal"){const x=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",K=typeof((g=s.meta)==null?void 0:g.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:x}),t.jsx("span",{children:K})]}),w&&f?t.jsx("div",{className:"chat-msg-body",children:t.jsx(hr,{parts:f,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:k})]})}if(m==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:w&&f?t.jsx(hr,{parts:f,renderAsPreformatted:!1}):k.slice(0,100)});const T=s.meta,b=(typeof(T==null?void 0:T.renderMode)=="string"?T.renderMode.trim():"")==="preformatted",v=k,h=!1,C=v,P=b,y=!P&&si(C);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(v||w||p)&&t.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${v||w?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:p?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:ti(r)})]}),(v||w)&&t.jsx("div",{className:"chat-markdown",children:w&&f?t.jsx(hr,{parts:f,renderAsPreformatted:P}):P?t.jsx("pre",{className:"chat-preformatted",children:C}):y?t.jsx(ea,{remarkPlugins:[ta,Uo,Fo],children:C}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:C})}),h]})})},(e,s)=>e.message===s.message&&e.receivedAt===s.receivedAt&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isTextExpanded===s.isTextExpanded),Yl=o.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},emptyState:p,onLoadMore:m,isLoadingMore:f,hasMoreHistory:w,hiddenLiveCount:k=0,loadError:T,scrollToBottomRequestNonce:d},b){var Ie;const v=o.useRef(null),h=o.useRef(null),C=o.useRef(null),P=o.useRef(0),y=o.useRef(""),S=o.useRef(!1),j=o.useRef(null),g=o.useRef(!1),x=o.useRef(null),K=o.useRef(!1),[I,M]=o.useState(new Set),L=o.useRef(!1),O=o.useRef(!1),R=()=>{const te=v.current;return te?te.scrollHeight-te.scrollTop-te.clientHeight<200:!0},N=o.useCallback((te="auto")=>{const ue=v.current;ue&&ue.scrollTo({top:ue.scrollHeight,behavior:te})},[]),U=o.useCallback(()=>{var oe;const te=v.current,ue=(oe=window.getSelection)==null?void 0:oe.call(window);if(!te||!ue||ue.rangeCount===0||ue.isCollapsed){K.current=!1;return}const ae=ue.anchorNode,xe=ue.focusNode;K.current=!!(ae&&xe&&te.contains(ae)&&te.contains(xe))},[]),G=s.length>0?`${s.length}:${(((Ie=s[s.length-1])==null?void 0:Ie.content)||"").length}`:"0:0",A=o.useCallback(()=>{const te=v.current;!te||!l||mn.set(l,{top:te.scrollTop,fromBottom:Math.max(0,te.scrollHeight-te.scrollTop-te.clientHeight),messageFingerprint:G})},[l,G]),D=o.useCallback((te="auto")=>{j.current!=null&&cancelAnimationFrame(j.current),j.current=requestAnimationFrame(()=>{j.current=null,N(te)})},[N]);o.useEffect(()=>{const te=!S.current,ue=y.current!==l;if(y.current=l,te||ue){if(S.current=!0,L.current=!1,g.current=!0,!K.current){const xe=l?mn.get(l):null;xe&&Fa(xe,G)?requestAnimationFrame(()=>{const oe=v.current;if(!oe)return;const F=Math.max(0,oe.scrollHeight-oe.clientHeight-xe.fromBottom);oe.scrollTop=Number.isFinite(F)?F:xe.top,O.current=!0}):D("auto")}P.current=s.length;return}s.length>P.current?!L.current&&!K.current&&D("auto"):R()&&!L.current&&!K.current&&D("auto"),P.current=s.length},[G,l,c,s.length,D]),o.useEffect(()=>{d&&(L.current=!1,g.current=!0,O.current=!0,x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{g.current=!1,x.current=null},180),K.current||D("auto"))},[D,d]),o.useEffect(()=>()=>{A(),j.current!=null&&cancelAnimationFrame(j.current),x.current!=null&&window.clearTimeout(x.current)},[A]),o.useEffect(()=>{const te=h.current;if(!te)return;const ue=()=>{x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{g.current=!1,x.current=null},180)},ae=new ResizeObserver(()=>{g.current&&(K.current||(D("auto"),ue()))});return ae.observe(te),()=>{ae.disconnect(),x.current!=null&&(window.clearTimeout(x.current),x.current=null)}},[D,l]),o.useImperativeHandle(b,()=>({scrollToBottom:(te="smooth")=>{N(te)}}),[N]),o.useEffect(()=>{const te=v.current;if(!te)return;let ue;const ae=()=>{clearTimeout(ue),ue=setTimeout(()=>{L.current=!R(),A()},50)};return te.addEventListener("scroll",ae,{passive:!0}),()=>{te.removeEventListener("scroll",ae),clearTimeout(ue)}},[A]),o.useEffect(()=>(document.addEventListener("selectionchange",U),()=>document.removeEventListener("selectionchange",U)),[U]);const $=o.useRef(0),W=o.useRef(!1);o.useEffect(()=>{const te=v.current;if(!te||!W.current||$.current===0)return;const ue=te.scrollHeight-$.current;ue>0&&(te.scrollTop=ue),A(),$.current=0,W.current=!1},[s.length,A]),o.useEffect(()=>{if(O.current||!l)return;const te=mn.get(l),ue=v.current;if(!te||!ue)return;if(!Fa(te,G)){N("auto"),O.current=!0;return}const ae=Math.max(0,ue.scrollHeight-ue.clientHeight-te.fromBottom);ue.scrollTop=Number.isFinite(ae)?ae:te.top,O.current=!0},[l,G,s.length,N]);const X=()=>{const te=v.current;te&&($.current=te.scrollHeight),W.current=!0,m==null||m()},we=o.useMemo(()=>{const te=s.map((oe,F)=>({type:"message",data:oe,index:F,ts:zl(oe,F,u)}));if(!r||r.length===0)return te;const ue=[...r].sort((oe,F)=>oe.timestamp-F.timestamp).map((oe,F)=>({type:"action",data:oe,index:F,ts:oe.timestamp})),ae=[];let xe=0;for(const oe of te){for(;xe<ue.length&&oe.ts>0&&ue[xe].ts<oe.ts;)ae.push(ue[xe++]);ae.push(oe)}for(;xe<ue.length;)ae.push(ue[xe++]);return ae},[s,r,u]),Le=k>0||!!w,ce=k>0?`↑ Show ${Math.min(k,80)} earlier messages${k>80?` (${k} hidden)`:""}`:T?`↻ ${T}`:"↑ Load older messages";return t.jsx("div",{ref:v,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:h,className:"chat-container-content",children:[f&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),Le&&!f&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:X,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${T&&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:ce})}),we.length===0&&!Le&&(p||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),we.map(te=>{if(te.type==="action"){const se=te.data;return t.jsx(Gl,{log:se},`action-${te.index}`)}const ue=te.data,ae=te.index,xe=Ss(ue,ae),oe=ue.receivedAt||u[xe],F=`${l}-${xe}`,be=I.has(F);return t.jsx(ql,{message:ue,receivedAt:oe,agentName:n,userName:a,isCliMode:i,isTextExpanded:be,onToggleTextExpanded:()=>M(se=>{const pe=new Set(se);return be?pe.delete(F):pe.add(F),pe})},`msg-${xe}`)}),c&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:C})]})})}),Xl=o.memo(Yl,(e,s)=>e.messages===s.messages&&e.actionLogs===s.actionLogs&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isWorking===s.isWorking&&e.contextKey===s.contextKey&&e.receivedAtMap===s.receivedAtMap&&e.emptyState===s.emptyState&&e.onLoadMore===s.onLoadMore&&e.isLoadingMore===s.isLoadingMore&&e.hasMoreHistory===s.hasMoreHistory&&e.hiddenLiveCount===s.hiddenLiveCount&&e.loadError===s.loadError&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce),Ql="modulepreload",Jl=function(e){return"/"+e},Va={},Zl=function(s,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(u=>{if(u=Jl(u),u in Va)return;Va[u]=!0;const p=u.endsWith(".css"),m=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${m}`))return;const f=document.createElement("link");if(f.rel=p?"stylesheet":Ql,p||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),p)return new Promise((w,k)=>{f.addEventListener("load",w),f.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})};let Ga=!1;const ri=o.forwardRef(({onInput:e,onResize:s,fontSize:r=13,readOnly:n=!1},a)=>{const i=o.useRef(null),[c,l]=o.useState(null),u=o.useRef([]),p=o.useRef(!1),m=o.useRef(!1),f=o.useRef(!1),w=()=>{const k=i.current;if(k){p.current&&(k.clear(),p.current=!1);for(const T of u.current)k.write(T);u.current=[],m.current&&(k.fit(),m.current=!1),f.current&&(k.bumpResize(),f.current=!1)}};return o.useImperativeHandle(a,()=>({write:k=>{i.current?i.current.write(k):u.current.push(k)},clear:()=>{i.current?i.current.clear():(u.current=[],p.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(u.current=[],p.current=!0)},resize:(k,T)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(k,T)},fit:()=>{i.current?i.current.fit():m.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():f.current=!0}}),[]),o.useEffect(()=>{if(!c)return;const k=requestAnimationFrame(()=>{w()});return()=>cancelAnimationFrame(k)},[c]),o.useEffect(()=>{let k=!1;return Zl(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(T=>{Ga||(Ga=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),k||l(()=>T.GhosttyTerminalView)}).catch(T=>{console.error("[CliTerminal] failed to load terminal renderer",T)}),()=>{k=!0}},[]),c?t.jsx(c,{ref:i,onInput:e,onResize:s,fontSize:r,readOnly:n,className:"w-full h-full rounded-lg overflow-hidden"}):t.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});ri.displayName="CliTerminal";function xr({label:e,value:s,sub:r,icon:n}){return t.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[t.jsx("span",{className:"text-base flex items-center",children:n}),t.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),t.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function qa({value:e,max:s,label:r,color:n="#8b5cf6",detail:a,compact:i=!1}){const c=s>0?Math.min(Math.round(e/s*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-0.5",children:[t.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),t.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-1.5",children:[t.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),t.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function ed({cursorPos:e,viewportRef:s,imgRef:r}){var h;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(h=s.current)==null?void 0:h.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,u=c/l,p=a.width/a.height;let m,f,w,k;u>p?(m=a.width,f=a.width/u,w=0,k=(a.height-f)/2):(f=a.height,m=a.height*u,w=(a.width-m)/2,k=0);const T=a.left-i.left+w+m*e.nx,d=a.top-i.top+k+f*e.ny,b=Math.max(8,Math.min(i.width-8,T)),v=Math.max(8,Math.min(i.height-8,d));return t.jsxs("div",{style:{position:"absolute",left:b-8,top:v-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[t.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function td({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:p,zoom:m,isMobile:f,mobileFillZoom:w,onZoomOut:k,onZoomReset:T,onZoomIn:d,transportType:b,screenshotUsage:v,lastActionStatus:h}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:C=>C.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[t.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[t.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),t.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("div",{onClick:()=>{n(C=>!C),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&t.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:t.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:C=>C.stopPropagation(),onChange:C=>l(C.target.value),onKeyDown:C=>{u(C)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),t.jsx("div",{className:"relative",children:t.jsx("div",{onClick:()=>{i(C=>!C),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⚙️"})})}),t.jsx("div",{className:"w-px h-[18px] bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:p?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:p?"Connected":"WS"})]}),m>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(m*100),"%"]}),b==="direct"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),b==="relay"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),v&&v.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:v.budgetExhausted?"#ef4444":"#c4b5fd",background:v.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:v.budgetExhausted?"TURN blocked":`TURN ${v.dailyUsedMinutes}/${v.dailyBudgetMinutes}m`}),h&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:h})]})]}),a&&t.jsxs("div",{onTouchStart:C=>C.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",m<=(f?w:1)+.01?f?"FILL":"FIT":`${Math.round(m*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:C=>{C.stopPropagation(),k()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),t.jsx("button",{onClick:C=>{C.stopPropagation(),T()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:f?"FILL":"FIT"}),t.jsx("button",{onClick:C=>{C.stopPropagation(),d()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function sd({waitingLabel:e,waitingHint:s,transportType:r}){return t.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[t.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),t.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),t.jsx("div",{className:"text-[11px] text-white/40",children:s}),r==="relay"&&t.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function rd(){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 Ya(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 or(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!rd())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([c,l])=>[c,Ya(l)]))}),r.current=s;return}const i=Object.keys({...a,...s}).filter(c=>!Object.is(a[c],s[c]));i.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:i,snapshot:Object.fromEntries(i.map(c=>[c,Ya(s[c])]))}),r.current=s})}function nd({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:p,setPanY:m,setZoom:f,lastWheelTimeRef:w,onAction:k,setLastActionStatus:T,spawnRippleFromNormalized:d,clampPan:b,isMobile:v,mobileFillZoom:h}){const[C,P]=o.useState(null),y=o.useRef(null),S=o.useRef(null),j=o.useRef(null),g=o.useRef(!1),x=o.useRef(null),K=o.useRef(0),I=o.useRef(null),M=o.useRef(1),L=o.useRef({x:0,y:0}),O=o.useRef(!1),R=o.useRef(n),N=o.useRef(k),U=30,G=550,A=18,D=60,$=400,W=12,X=()=>{if(y.current)return;const ce={nx:.5,ny:.5};y.current=ce,P(ce)};return o.useEffect(()=>{R.current=n,n==="mouse"&&X()},[n]),o.useEffect(()=>{N.current=k},[k]),o.useEffect(()=>{const ce=e.current;if(!ce)return;const Ie=F=>{if(!r.current)return null;const be=r.current.getBoundingClientRect();return!be.width||!be.height?null:{nx:Math.max(0,Math.min(1,(F.clientX-be.left)/be.width)),ny:Math.max(0,Math.min(1,(F.clientY-be.top)/be.height))}},te=(F,be)=>{if(!r.current)return{dnx:0,dny:0};const se=r.current,pe=se.getBoundingClientRect(),J=se.naturalWidth||pe.width,de=se.naturalHeight||pe.height,ne=J/de,ge=pe.width/pe.height;let me,E;return ne>ge?(me=pe.width,E=pe.width/ne):(E=pe.height,me=pe.height*ne),{dnx:F/me,dny:be/E}},ue=(F,be,se)=>{if(se<=1.05)return;const pe=-(F-.5)*100,J=-(be-.5)*100,de=b(pe,J,se);(Math.abs(de.x-l.current)>.1||Math.abs(de.y-u.current)>.1)&&(p(de.x),m(de.y),l.current=de.x,u.current=de.y)},ae=F=>{const be=s.current;if(be&&F.target instanceof Node&&be.contains(F.target))F.preventDefault();else return;if(F.touches.length===1){const se=F.touches[0];S.current={x:se.clientX,y:se.clientY,time:Date.now()},j.current={x:se.clientX,y:se.clientY},O.current||(g.current=!1),x.current=setTimeout(()=>{if(!g.current&&!O.current)if(g.current=!0,R.current==="mouse"){const pe=y.current||{nx:.5,ny:.5};T("Right Click"),d(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{})}else{const pe=Ie(se);pe&&(T("Right Click"),d(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{}))}},500);return}if(F.touches.length===2){x.current&&clearTimeout(x.current),g.current=!0,O.current=!0;const se=F.touches[1].clientX-F.touches[0].clientX,pe=F.touches[1].clientY-F.touches[0].clientY;I.current=Math.sqrt(se*se+pe*pe),M.current=c.current,L.current={x:(F.touches[0].clientX+F.touches[1].clientX)/2,y:(F.touches[0].clientY+F.touches[1].clientY)/2}}},xe=F=>{const be=s.current;if(be&&F.target instanceof Node&&be.contains(F.target)&&F.preventDefault(),F.touches.length===1&&j.current){const se=F.touches[0],pe=se.clientX-j.current.x,J=se.clientY-j.current.y;if(!g.current&&S.current){const de=se.clientX-S.current.x,ne=se.clientY-S.current.y;Math.sqrt(de*de+ne*ne)>8&&(g.current=!0,x.current&&clearTimeout(x.current))}if(g.current)if(R.current==="mouse"){const de=te(pe,J),ne=y.current||{nx:.5,ny:.5},ge=Math.max(0,Math.min(1,ne.nx+de.dnx)),me=Math.max(0,Math.min(1,ne.ny+de.dny));y.current={nx:ge,ny:me},P({nx:ge,ny:me}),T(`Cursor: ${Math.round(ge*100)}%, ${Math.round(me*100)}%`),ue(ge,me,c.current);const E=Date.now();E-w.current>=30&&(w.current=E,N.current("input_mouseMoved",{nx:ge,ny:me}).catch(()=>{}))}else if(c.current>1){const de=s.current;if(de){const ne=de.clientWidth,ge=de.clientHeight,me=l.current+pe/ne*100,E=u.current+J/ge*100,ye=b(me,E,c.current);p(ye.x),m(ye.y),l.current=ye.x,u.current=ye.y}}else{const de=Ie(se);if(de){const ne=Date.now();ne-w.current>=40&&(w.current=ne,T("Scroll"),N.current("input_wheel",{nx:de.nx,ny:de.ny,deltaX:Math.round(-pe*2.5),deltaY:Math.round(-J*2.5)}).catch(()=>{}))}}j.current={x:se.clientX,y:se.clientY};return}if(F.touches.length===2&&I.current!==null){const se=F.touches[1].clientX-F.touches[0].clientX,pe=F.touches[1].clientY-F.touches[0].clientY,de=Math.sqrt(se*se+pe*pe)/I.current,ne=(F.touches[0].clientX+F.touches[1].clientX)/2,ge=(F.touches[0].clientY+F.touches[1].clientY)/2,me=ne-L.current.x,E=ge-L.current.y,ye=Math.abs(de-1)>.03;if(R.current==="mouse"){if(ye){const he=Math.max(i,Math.min(5,M.current*de));f(he),c.current=he}else if(Math.abs(me)>2||Math.abs(E)>2){const he=y.current||{nx:.5,ny:.5},je=Date.now();je-w.current>=30&&(w.current=je,T("Scroll"),N.current("input_wheel",{nx:he.nx,ny:he.ny,deltaX:Math.round(-me*3),deltaY:Math.round(-E*3)}).catch(()=>{}))}}else{const he=Math.max(i,Math.min(5,M.current*de));f(he),c.current=he;const je=s.current;if(je&&he>1){const Q=je.clientWidth,ke=je.clientHeight,He=l.current+me/Q*100,De=u.current+E/ke*100,Ge=b(He,De,he);p(Ge.x),m(Ge.y),l.current=Ge.x,u.current=Ge.y}}L.current={x:ne,y:ge}}},oe=F=>{var be;if(x.current&&clearTimeout(x.current),I.current=null,F.touches.length===1&&O.current){const se=F.touches[0];S.current={x:se.clientX,y:se.clientY,time:Date.now()},j.current={x:se.clientX,y:se.clientY},g.current=!0;return}if(F.touches.length===0){if(O.current){O.current=!1,g.current=!1;return}if(F.changedTouches.length===1){const se=F.changedTouches[0],pe=Date.now(),J=pe-(((be=S.current)==null?void 0:be.time)||0),de=S.current?se.clientX-S.current.x:0,ne=S.current?se.clientY-S.current.y:0,ge=Math.sqrt(de*de+ne*ne);if(R.current==="mouse"){if(J<U||J>G||ge>A){g.current=!1;return}const me=y.current||Ie(se);me&&(T(`Click: ${Math.round(me.nx*100)}%, ${Math.round(me.ny*100)}%`),d(me.nx,me.ny,"left"),N.current("input_click",{...me}).catch(()=>{}))}else{if(g.current){g.current=!1;return}if(J<D||J>$||ge>W){g.current=!1;return}const me=Ie(se);if(!me)return;pe-K.current<300?(T("Double tap"),d(me.nx,me.ny,"double"),N.current("input_click",{...me,clickCount:2}).catch(()=>{}),K.current=0):(T(`Tap: ${Math.round(me.nx*100)}%, ${Math.round(me.ny*100)}%`),d(me.nx,me.ny,"left"),N.current("input_click",{...me}).catch(()=>{}),K.current=pe)}}g.current=!1}};return ce.addEventListener("touchstart",ae,{passive:!1}),ce.addEventListener("touchmove",xe,{passive:!1}),ce.addEventListener("touchend",oe,{passive:!1}),()=>{ce.removeEventListener("touchstart",ae),ce.removeEventListener("touchmove",xe),ce.removeEventListener("touchend",oe),x.current&&clearTimeout(x.current)}},[e,s,r,i,c,l,u,p,m,f,w,T,d,b]),{cursorPos:C,cursorPosRef:y,handleToggleInputMode:()=>{a(ce=>{const Ie=ce==="touch"?"mouse":"touch";return Ie==="mouse"&&X(),Ie})},handleZoomReset:()=>{const ce=v?h:1;f(ce),c.current=ce,p(0),m(0),l.current=0,u.current=0}}}function ni({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[p,m]=o.useState(null),[f,w]=o.useState(""),[,k]=o.useState(!1),[T,d]=o.useState([]),b=o.useRef(0),[v,h]=o.useState(!1),[C,P]=o.useState(!1),y=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[S,j]=o.useState(y?"mouse":"touch"),[g,x]=o.useState(1),K=o.useRef(!1),[I,M]=o.useState(1),[L,O]=o.useState(0),[R,N]=o.useState(0);or("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:S,zoom:I,panX:L,panY:R,isMenuOpen:v,isImeOpen:C});const U=o.useRef(0),G=o.useRef(I),A=o.useRef(L),D=o.useRef(R);o.useEffect(()=>{G.current=I},[I]),o.useEffect(()=>{A.current=L},[L]),o.useEffect(()=>{D.current=R},[R]),o.useEffect(()=>{var J;(J=c.current)==null||J.focus()},[]);const $=r==="connected",W=n,X=$?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",we=$?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!y||K.current||!W)return;const J=u.current,de=l.current;if(!J||!de)return;const ne=()=>{const ge=de.clientWidth,me=de.clientHeight,E=J.naturalWidth,ye=J.naturalHeight;if(!E||!ye||!ge||!me)return;const he=Math.min(ge/E,me/ye),Q=Math.max(ge/E,me/ye)/he;Q>1.01&&(x(Q),M(Q),G.current=Q),K.current=!0};J.complete&&J.naturalWidth?ne():J.addEventListener("load",ne,{once:!0})},[W,y]);const Le=.5;o.useEffect(()=>{I<=Le&&(O(0),N(0))},[I,Le]);const ce=(J,de,ne)=>{if(ne<=Le)return{x:0,y:0};const ge=(ne-1)/(2*ne)*100,me=(ne-1)/(2*ne)*100;return{x:Math.max(-ge,Math.min(ge,J)),y:Math.max(-me,Math.min(me,de))}},Ie=(J,de)=>{if(!u.current)return null;const ne=u.current.getBoundingClientRect();return!ne.width||!ne.height?null:{nx:Math.max(0,Math.min(1,(J-ne.left)/ne.width)),ny:Math.max(0,Math.min(1,(de-ne.top)/ne.height))}},te=(J,de,ne)=>{const ge=l.current;if(!ge)return;const me=ge.getBoundingClientRect(),E=++b.current;d(ye=>[...ye,{id:E,x:J-me.left,y:de-me.top,type:ne}]),setTimeout(()=>d(ye=>ye.filter(he=>he.id!==E)),600)},ue=(J,de,ne)=>{const ge=u.current,me=l.current;if(!ge||!me)return;const E=ge.getBoundingClientRect(),ye=me.getBoundingClientRect(),he=ge.naturalWidth||E.width,je=ge.naturalHeight||E.height,Q=he/je,ke=E.width/E.height;let He,De,Ge,Qe;Q>ke?(He=E.width,De=E.width/Q,Ge=0,Qe=(E.height-De)/2):(De=E.height,He=E.height*Q,Ge=(E.width-He)/2,Qe=0);const Ze=E.left-ye.left+Ge+He*J,ut=E.top-ye.top+Qe+De*de,qe=++b.current;d(ht=>[...ht,{id:qe,x:Ze,y:ut,type:ne}]),setTimeout(()=>d(ht=>ht.filter(mt=>mt.id!==qe)),600)},ae=async J=>{var ne;const de=Ie(J.clientX,J.clientY);if(de){m(`Click: ${Math.round(de.nx*100)}%, ${Math.round(de.ny*100)}%`),te(J.clientX,J.clientY,"left"),(ne=c.current)==null||ne.focus();try{const ge=await e("input_click",{nx:de.nx,ny:de.ny});ge!=null&&ge.success||s(`❌ Click failed: ${ge==null?void 0:ge.error}`)}catch(ge){s(`❌ Click error: ${ge.message||ge}`)}}},xe=async(J,de,ne,ge=0)=>{try{await e("input_key",{type:ne?"char":"keyDown",key:J,code:de,text:ne?J:void 0,unmodifiedText:ne?J:void 0,modifiers:ge})}catch(me){s(`❌ Key error: ${me.message||me}`)}},oe=async J=>{if(J.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(J.key)&&J.preventDefault();let ne=0;J.altKey&&(ne|=1),J.ctrlKey&&(ne|=2),J.metaKey&&(ne|=4),J.shiftKey&&(ne|=8),m(`Key: ${J.key}`),await xe(J.key,J.code,J.key.length===1,ne)},F=async J=>{if(J.key==="Enter"){if(J.nativeEvent.isComposing)return;if(f){const de=f;w(""),m(`IME Sent: ${de}`);try{const ne=await e("input_type",{text:de});ne!=null&&ne.success||s(`❌ IME error: ${ne==null?void 0:ne.error}`)}catch(ne){s(`❌ IME error: ${ne.message}`)}}else m("Key: Enter"),await xe("Enter","Enter",!1)}};o.useEffect(()=>{const J=c.current;if(!J)return;const de=ne=>{var ge;if((ge=u.current)!=null&&ge.contains(ne.target)){ne.preventDefault();const me=Date.now();if(me-U.current<40)return;U.current=me;const E=Ie(ne.clientX,ne.clientY);if(!E)return;m(`Scroll: ${Math.round(ne.deltaY)}`),e("input_wheel",{nx:E.nx,ny:E.ny,deltaX:Math.round(ne.deltaX),deltaY:Math.round(ne.deltaY)}).catch(()=>{})}};return J.addEventListener("wheel",de,{passive:!1}),()=>J.removeEventListener("wheel",de)},[e]);const{cursorPos:be,handleToggleInputMode:se,handleZoomReset:pe}=nd({containerRef:c,viewportRef:l,imgRef:u,inputMode:S,setInputMode:j,minZoom:Le,zoomRef:G,panXRef:A,panYRef:D,setPanX:O,setPanY:N,setZoom:M,lastWheelTimeRef:U,onAction:e,setLastActionStatus:m,spawnRippleFromNormalized:ue,clampPan:ce,isMobile:y,mobileFillZoom:g});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:oe,onContextMenu:J=>J.preventDefault(),onFocus:()=>k(!0),onBlur:()=>k(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[W?t.jsx("img",{ref:u,src:W,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${I}) translate(${L}%, ${R}%)`,transformOrigin:"center center",cursor:S==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ae,onContextMenu:J=>J.preventDefault(),onDragStart:J=>J.preventDefault()}):t.jsx(sd,{waitingLabel:X,waitingHint:we,transportType:i}),S==="mouse"&&W&&t.jsx(ed,{cursorPos:be,viewportRef:l,imgRef:u}),T.map(J=>{const ne={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[J.type];return t.jsxs("div",{style:{position:"absolute",left:J.x,top:J.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ne}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${ne}, 0.9)`,boxShadow:`0 0 12px rgba(${ne}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},J.id)})]}),t.jsx(td,{inputMode:S,onToggleInputMode:se,isImeOpen:C,setIsImeOpen:P,isMenuOpen:v,setIsMenuOpen:h,imeText:f,setImeText:w,handleImeSubmit:F,isConnActive:$,zoom:I,isMobile:y,mobileFillZoom:g,onZoomOut:()=>M(J=>Math.max(.5,J-.25)),onZoomReset:pe,onZoomIn:()=>M(J=>Math.min(5,J+.25)),transportType:i,screenshotUsage:a,lastActionStatus:p}),t.jsx("style",{children:`
|
|
5
|
+
@keyframes slideUp {
|
|
6
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
7
|
+
to { opacity: 1; transform: translateY(0); }
|
|
8
|
+
}
|
|
9
|
+
@keyframes slideUpSidebar {
|
|
10
|
+
from { opacity: 0; transform: translateY(6px); }
|
|
11
|
+
to { opacity: 1; transform: translateY(0); }
|
|
12
|
+
}
|
|
13
|
+
@keyframes click-ripple-ring {
|
|
14
|
+
0% { transform: scale(0.3); opacity: 1; }
|
|
15
|
+
100% { transform: scale(2.2); opacity: 0; }
|
|
16
|
+
}
|
|
17
|
+
@keyframes click-ripple-dot {
|
|
18
|
+
0% { transform: scale(1); opacity: 0.9; }
|
|
19
|
+
50% { transform: scale(1.8); opacity: 0.6; }
|
|
20
|
+
100% { transform: scale(0.5); opacity: 0; }
|
|
21
|
+
}
|
|
22
|
+
@keyframes remote-float {
|
|
23
|
+
0% { transform: translateY(0px); }
|
|
24
|
+
50% { transform: translateY(-7px); }
|
|
25
|
+
100% { transform: translateY(0px); }
|
|
26
|
+
}
|
|
27
|
+
`})]})}function jt(e){return(typeof e=="string"?e.trim():"")||void 0}function Ht(e,s){const r=jt(s);return r?`${e}:${r}`:void 0}function qt(e,s,r){const n=Ht(s,r),a=jt(r);n&&e.push(n),a&&e.push(a)}function Ns(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function ai(e){return jt(e.providerSessionId)||jt(e.sessionId)||jt(e.tabKey)||jt(e.routeId)}function ca(e){return Ns([jt(e.providerSessionId),jt(e.sessionId)])}function as(e){const s=[];return qt(s,"provider",e.providerSessionId),qt(s,"session",e.sessionId),qt(s,"tab",e.tabKey),qt(s,"route",e.routeId),Ns(s)}function ad(e){const s=[];return jt(e.providerSessionId)?(qt(s,"provider",e.providerSessionId),Ns(s)):jt(e.sessionId)?(qt(s,"session",e.sessionId),Ns(s)):jt(e.tabKey)?(qt(s,"tab",e.tabKey),Ns(s)):jt(e.routeId)?(qt(s,"route",e.routeId),Ns(s)):[]}function oi(e){return Ht("provider",e.providerSessionId)||Ht("session",e.sessionId)||Ht("tab",e.tabKey)||Ht("route",e.routeId)||"unknown:"}function ir(e){return ca(e)[0]}function ii(e){const s=jt(e.providerSessionId),r=jt(e.sessionId),n=jt(e.tabKey),a=jt(e.routeId),i=[Ht("provider",s),Ht("session",r),Ht("tab",n),Ht("route",a)].filter(u=>typeof u=="string"),c=as({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=oi({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:ai({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:ir({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function Wr(e,s){const r=ii(e);return ad(s).some(n=>r.lookupKeys.includes(n))}function Zr(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=s,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const p=Math.floor(u/24);return p<7?`${p}d${r}`:new Date(e).toLocaleDateString()}const ci=e=>Zr(e);function od(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden}}function Ws(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:a}}function en(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...od(a)})};for(const n of e)if(n.type!=="adhdev-daemon"){r(n.sessionId,n);for(const a of n.childSessions||[])r(a.id,a)}return s}function Or(e,s){if(e.sessionId){const r=s.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1}}function la(e,s,r){const n=Or(e,s),a=Ws(e),i=as(e).map(T=>{var d;return(d=r==null?void 0:r.notificationStateBySessionId)==null?void 0:d.get(T)}).find(T=>!!T),c=a.isReconnecting,l=a.isConnecting,u=a.isGenerating,p=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||p,f=n.inboxBucket==="working"||u,k=n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:k,requiresAction:m,isWorking:f,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:p,inboxBucket:m?"needs_attention":f?"working":k?"task_complete":"idle"}}function id(e,s,r){return la(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function li({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ws(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),s(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return t.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&t.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[t.jsx(hs,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const p=c(l).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(p),f=/^(reject|deny|delete|remove|abort)/.test(p),w=r===l,k=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:k,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"font-extrabold":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${k&&!w?"opacity-40":"opacity-100"} ${k?"cursor-not-allowed":"cursor-pointer"}`,style:m?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:f?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:w?"⏳ ...":c(l)},u)})})]})]})}var cd=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function ld(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function wt(e,s){if(ld(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":cd.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 di(e){return wt(e)==="generating"}function ot(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function dd(e){if(e<60)return`${Math.round(e)}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),n=s%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),i=r%24;return`${a}d ${i}h`}function fn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function tn(e,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),i=a.split(/[\\/]/).filter(Boolean);return i[i.length-1]||a}function ud(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const s=e.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function md(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function pd(e){return ud(e.trim().replace(/\.local$/i,""))}function fd(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function ui(e,s={}){var a,i;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!md(c));if(r&&r!=="Unknown")return pd(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function At(e,s={}){return fd(e)||ui(e,s)}function mi(e){return!e||!Array.isArray(e.items)?[]:e.items.map(s=>String((s==null?void 0:s.value)||(s==null?void 0:s.shortValue)||"").trim()).filter(Boolean)}function pi(e,s,r={}){const n=String(s).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function xs(e,s){return mi(e).join(" · ")}function nr(e){return e.transport==="pty"}function Cs(e){return e.transport==="acp"}function hd(e,s){var r,n;return(r=s==null?void 0:s.providerLabels)!=null&&r[e]?s.providerLabels[e]:(n=s==null?void 0:s.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?s.providerLabels[e.toLowerCase()]:s!=null&&s.agentName&&s.agentName!==e?s.agentName:ot(e)}function Xa(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=ot(r||"").trim().toLowerCase();return n===a||n===i||n===c}function xd(e){return wt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function bd(e){if(!Array.isArray(e)||e.length<=1)return e;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=s.get(a),c=wt(n.status);if(!i){s.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&s.set(a,{...n,status:c})}return Array.from(s.values())}function gd(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function yd(e){var r,n;const s=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&gd(s.receivedAt)||0}function vd(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function On(e){return Math.max(vd(e),yd(e.activeChat))}function wd(e,s,r,n,a,i){const c=s-e;if(c!==0)return c;const l=r.localeCompare(n);return l!==0?l:a.localeCompare(i)}function da(e,s){return wd(On(e),On(s),At(e,{fallbackId:e.id}),At(s,{fallbackId:s.id}),e.id,s.id)}const fi="adhdev_notification_prefs",Qa={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function jd(){try{const e=localStorage.getItem(fi);if(e){const s=JSON.parse(e);return{...Qa,...s}}}catch{}return{...Qa}}function kd(e){try{localStorage.setItem(fi,JSON.stringify(e))}catch{}}let Ot=jd(),Lr=[];function Sd(){Lr.forEach(e=>e())}function Nd(e){Ot={...Ot,...e},kd(Ot),Sd()}function Cd(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Lr.push(r),()=>{Lr=Lr.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{Nd(r)},[]);return[{...Ot},s]}function Qs(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 Id={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Ad(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function hi(){return"Notification"in window&&Notification.permission==="granted"}let ss=null;async function Td(){if(ss!==null)return ss;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ss=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ss=!!await e.pushManager.getSubscription(),ss):(ss=!1,!1)}catch{return ss=!1,!1}}function Hn(e,s,r){if(hi())try{const n=new Notification(e,{body:s,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Md(e,s={}){const r={...Id,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Td().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,p)=>{const m=Date.now();m-a.current<r.throttleMs||(a.current=m,Hn(l,u,p))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!hi())&&Qs("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,wt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const p=n.current.get(u.id),m=wt(u.status,{activeModal:u.activeModal}),f=u.name||u.id;if(r.onApproval&&Qs("approval")&&m==="waiting_approval"&&p!=="waiting_approval"){const w=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,w.slice(0,120),`approval-${u.id}`)}r.onComplete&&Qs("completion")&&di(p)&&m==="idle"&&c(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&m==="error"&&p!=="error"&&c(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${u.id}`),n.current.set(u.id,m)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Ld=/^(run|approve|accept|yes|allow|always)/,_d=/^(run|approve|accept|yes|allow|always|proceed|save)/,Rd=/^(reject|deny|delete|remove|abort|cancel|no)/;function ua(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Pd(e){const s=ua(e).toLowerCase();return Ld.test(s)?"primary":Rd.test(s)?"danger":"default"}function Dd(e){return _d.test(ua(e).toLowerCase())?"approve":"reject"}function $d(e){return e.map((s,r)=>({label:ua(s),variant:Pd(s),action:Dd(s),button:s,buttonIndex:r}))}function Ed(e,s){const r=e||"Approval requested",n=s!=null&&s.length?s.map(a=>`[${a}]`).join(" "):"[Approve] [Reject]";return`⚡ Approval requested: ${r}
|
|
28
|
+
${n}`}function Kd(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Bd(e,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,s,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,s,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class Wd{constructor(){Ye(this,"dedupMap",new Map);Ye(this,"DEDUP_WINDOW_MS",5e3);Ye(this,"DEDUP_MAX_SIZE",50);Ye(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ye(this,"toastCallbacks",[]);Ye(this,"systemMessageCallbacks",[]);Ye(this,"clearSystemMessageCallbacks",[]);Ye(this,"resolveActionFn",null);Ye(this,"viewRequestRespondFn",null);Ye(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:s,type:r,timestamp:a,duration:5e3,...n})}emitSystemMessage(s,r){for(const n of this.systemMessageCallbacks)n(s,r)}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(s){if(s.daemonId){const a=this.ides.find(i=>i.id===s.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var T,d;const n=this.resolveConversationKey(s),a=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(a),l=`${i}:${s.event}:${c}`;if(this.isDuplicate(l))return;const u=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,p=(u==null?void 0:u.type)||"";let m=ot(p);const f=this.resolveOwningDaemon(s);if(f){const b=At(f,{fallbackId:f.id});b&&(m=!p||p==="adhdev-daemon"?b:`${b}/${m}`)}let w="",k="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";w=`✅ ${m} agent task completed${b}`,k="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(w=`⚡ ${m} approval needed`,k="warning",n&&!((T=s.modalButtons)!=null&&T.length)&&this.emitSystemMessage(n,{role:"system",timestamp:a,content:Ed(s.modalMessage,s.modalButtons),_localId:`sys_approval_${a}`}),(d=s.modalButtons)!=null&&d.length&&this.resolveActionFn){const b=this.resolveActionRouteTarget(s);if(!b)return;const v=this.resolveActionFn,h=$d(s.modalButtons).map(y=>({label:y.label,variant:y.variant,onClick:()=>{v(b,"resolve_action",{action:y.action,button:y.button,buttonIndex:y.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),C=Kd(m,s.modalMessage,w),P=Date.now();this.emitToast({id:P,message:C,type:k,timestamp:P,targetKey:n||b,actions:h,duration:15e3}),w=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";w=`⚠️ ${m} agent is taking a long time${b}`,k="warning",Qs("browser")&&!document.hasFocus()&&Hn(`⚠️ ${m} — Long Running`,`Agent has been generating for over ${b.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const b=s.requesterName||"A team member",v=s.requestId,h=s.orgId;if(w=`👁️ ${b} wants to view your session`,k="warning",v&&h&&this.viewRequestRespondFn){const C=Date.now(),P=Bd(h,v,this.viewRequestRespondFn,(y,S)=>console.error(`[EventManager] ${y} view request failed:`,S));this.emitToast({id:C,message:w,type:k,timestamp:C,actions:P,duration:3e4}),w=""}Qs("browser")&&!document.hasFocus()&&Hn("👁️ View Request",`${b} wants to view your session`,`view-request-${v}`)}else s.event==="team:view_request_approved"?(w="✅ View request approved",k="success"):s.event==="team:view_request_rejected"&&(w=`❌ ${s.targetName||"Team member"} declined your view request`,k="warning");if(w){const b=Date.now();this.emitToast({id:b,message:w,type:k,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const it=new Wd,Ja=new Map;function _s(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function xi(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Od(e){return!_s(e)||!_s(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function br(e){return!_s(e)||!_s(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function Us(e){if(!(!_s(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function gr(e){return _s(e)&&e.success===!1}function Hd(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";it.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";it.showToast(n.notification.body,a)}}}function Ud(e,s){return e&&xi(e.currentValue)?e.currentValue:s}function _r(e,s){return e.options||s[e.id]||[]}function hn(e,s){return{value:s}}function Fd(e,s,r){var a;return r?((a=_r(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const zd={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Vd({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=Mt(),u=`${e}:${s||n}`,p=zd[n]||"#94a3b8",[m,f]=o.useState({}),w=o.useRef(0),k={};for(const R of i||[])R.defaultValue!==void 0&&(k[R.id]=R.defaultValue);const T={...k,...c||{},...Date.now()<w.current?m:{}};o.useEffect(()=>{c&&Date.now()>w.current&&f({})},[c]);const[d,b]=o.useState(Ja.get(u)||{}),[v,h]=o.useState(null),[C,P]=o.useState(null),y=o.useCallback(async(R,N={})=>{const U={...N,...s&&{targetSessionId:s}};return await l(e,R,U)},[e,s,l]),S=o.useCallback(async(R,N={})=>{const U=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await y("invoke_provider_script",{...U,scriptName:R,...N})},[y,n,r,s]),j=o.useCallback((R,N,U)=>{const G=Ud(U,N);f(A=>({...A,[R.id]:G})),Hd(U==null?void 0:U.effects)},[]),g=o.useCallback((R,N)=>{f(U=>{const G={...U};return N===void 0?delete G[R.id]:G[R.id]=N,G}),w.current=0},[]);if(!i||i.length===0)return null;const x=i.filter(R=>R.placement==="bar"&&R.hidden!==!0).sort((R,N)=>(R.order??50)-(N.order??50));if(x.length===0)return null;const K=async R=>{if(v===R.id){h(null);return}if(_r(R,d).length>0){h(R.id);return}if(R.dynamic&&R.listScript){P(R.id);try{const U=await S(R.listScript,{}),G=Od(U);if(!G){const D=Us(U);D&&it.showToast(D,"warning");return}const A=G.options;if(b(D=>{const $={...D,[R.id]:A};return Ja.set(u,$),$}),xi(G.currentValue)){const D=G.currentValue;f($=>({...$,[R.id]:D}))}h(R.id)}catch(U){const G=U instanceof Error?U.message:`Could not load ${R.label}`;it.showToast(G,"warning")}finally{P(null)}}},I=async(R,N)=>{h(null);const U=(c==null?void 0:c[R.id])??k[R.id];f(G=>({...G,[R.id]:N})),w.current=Date.now()+5e3;try{if(!R.setScript)return;const G=await S(R.setScript,hn(R,N)),A=br(G);if(A&&!A.ok||gr(G))throw new Error((A==null?void 0:A.error)||Us(G)||`Could not update ${R.label}`);j(R,N,A)}catch(G){g(R,U);const A=G instanceof Error?G.message:`Could not update ${R.label}`;it.showToast(A,"warning")}},M=async R=>{const N=_r(R,d).map(W=>W.value);if(N.length===0)return;const U=String(T[R.id]||""),A=(N.indexOf(U)+1)%N.length,D=N[A];if(typeof D!="string")return;const $=(c==null?void 0:c[R.id])??k[R.id];f(W=>({...W,[R.id]:D})),w.current=Date.now()+5e3;try{if(!R.setScript)return;const W=await S(R.setScript,hn(R,D)),X=br(W);if(X&&!X.ok||gr(W))throw new Error((X==null?void 0:X.error)||Us(W)||`Could not update ${R.label}`);j(R,D,X)}catch(W){g(R,$);const X=W instanceof Error?W.message:`Could not update ${R.label}`;it.showToast(X,"warning")}},L=async R=>{const U=!T[R.id],G=(c==null?void 0:c[R.id])??k[R.id];f(A=>({...A,[R.id]:U})),w.current=Date.now()+5e3;try{if(!R.setScript)return;const A=await S(R.setScript,hn(R,U)),D=br(A);if(D&&!D.ok||gr(A))throw new Error((D==null?void 0:D.error)||Us(A)||`Could not update ${R.label}`);j(R,U,D)}catch(A){g(R,G);const D=A instanceof Error?A.message:`Could not update ${R.label}`;it.showToast(D,"warning")}},O=async R=>{if(!R.invokeScript)return;if(R.confirmMessage){const U=[R.confirmTitle,R.confirmMessage,R.confirmLabel].filter(A=>typeof A=="string"&&A.trim().length>0);if(!window.confirm(U.join(`
|
|
29
|
+
|
|
30
|
+
`)))return}const N=(c==null?void 0:c[R.id])??k[R.id];try{const U=await S(R.invokeScript),G=br(U);if(G&&!G.ok||gr(U))throw new Error((G==null?void 0:G.error)||Us(U)||`Could not run ${R.label}`);G&&j(R,N??!0,G)}catch(U){g(R,N);const G=U instanceof Error?U.message:`Could not run ${R.label}`;it.showToast(G,"warning")}};return t.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 flex-wrap text-[10px] border-t border-border-subtle bg-surface-primary font-[var(--font)]",children:[t.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:p},children:a}),t.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),x.map(R=>{const N=String(T[R.id]||""),U=Fd(R,d,N),G=v===R.id,A=C===R.id,D=_r(R,d);switch(R.type){case"select":return t.jsxs("div",{className:"relative",children:[t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap max-w-40 overflow-hidden text-ellipsis",style:{borderColor:G?`${p}55`:"transparent",border:"1px solid",color:N?"var(--text-primary)":"var(--text-muted)"},onClick:()=>K(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),A?"...":U||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),G&&D.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>h(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] bg-[var(--surface-primary)] border border-border-subtle rounded-lg mb-1 max-h-[220px] overflow-y-auto min-w-40 shadow-[0_-4px_16px_rgba(0,0,0,0.3)]",children:[t.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:R.label.toUpperCase()}),D.map($=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:$.value===N?`${p}18`:"transparent",color:$.value===N?p:"var(--text-secondary)",fontWeight:$.value===N?600:400,borderLeft:$.value===N?`2px solid ${p}`:"2px solid transparent"},title:$.description||$.label,onMouseEnter:W=>{W.currentTarget.style.background=`${p}12`},onMouseLeave:W=>{W.currentTarget.style.background=$.value===N?`${p}18`:"transparent"},onClick:()=>I(R,$.value),children:$.label},$.value))]})]})]},R.id);case"cycle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap",style:{border:"1px solid transparent",color:N?"var(--text-primary)":"var(--text-muted)"},onClick:()=>M(R),title:`Click to cycle: ${D.map($=>$.label).join(" → ")}`,children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),U||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},R.id);case"toggle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all whitespace-nowrap",style:{border:"1px solid",borderColor:N?`${p}44`:"transparent",background:N?`${p}14`:"var(--surface-tertiary)",color:N?p:"var(--text-muted)"},onClick:()=>L(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.label]},R.id);case"action":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all hover:bg-[var(--surface-tertiary-hover)] whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>O(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.resultDisplay==="inline"&&N?`${R.label}: ${N}`:R.label]},R.id);case"display":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:N?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),N?`${R.label}: ${N}`:R.label]},R.id);default:return null}})]})}const Gd=o.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:a,isActive:i=!0}){const c=o.useRef(null),[l,u]=o.useState("");o.useEffect(()=>{u("")},[s]),o.useEffect(()=>{var m;i&&((m=c.current)==null||m.focus())},[s,i]);const p=()=>{const m=l.trim();!m||n||(u(""),a(m))};return t.jsx("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:i?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:i?72:0,opacity:i?1:0,transform:i?"translateY(0)":"translateY(10px)",padding:i?"10px 12px":"0 12px",pointerEvents:i?"auto":"none"},"aria-hidden":!i,children:t.jsxs("div",{className:"flex gap-2.5 items-center",title:i?`Send message to ${r}`:void 0,children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:c,type:"text",placeholder:`Send message to ${r}...`,value:l,onChange:m=>u(m.target.value),onPaste:m=>{const f=m.clipboardData.getData("text");f&&u(w=>w+f),m.preventDefault()},onKeyDown:m=>{if(m.key==="Enter"){if(m.nativeEvent.isComposing){m.preventDefault();return}m.preventDefault(),p()}},onBlur:m=>{if(window.innerWidth<768){const f=m.relatedTarget;if((f==null?void 0:f.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:p,disabled:!l.trim()||n,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${l.trim()&&!n?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:l.trim()&&!n?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:l.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})}),et=e=>e.transport==="pty",Rs=(e,s)=>et(e)?e.mode||"terminal":"chat",bi=(e,s)=>et(e)&&Rs(e)==="terminal",Xe=e=>e.transport==="acp";function Yt(e){return e.streamSource!=="agent-stream"}function Jt(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function gi(e){return e.machineName||""}function cr(e){return Jt(e)}function $t(e){return e.agentType||""}function Hr(e){return e.hostIdeType||""}function ma(e){return e.displayPrimary||e.agentName||"Agent"}function yi(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function qd(e){return e.lastMessagePreview||e.displaySecondary||""}function vi(e){return[e.displaySecondary,gi(e)].filter(Boolean)}function Ps(e){return e.agentName||ot($t(e))}function Yd(e){var s,r;if(!Yt(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return ot(Hr(e)||$t(e))}function wi(e){return Yt(e)?e.sessionId:e.nativeSessionId}function Za(e){return Yt(e)?"native":e.tabKey}function Xd(e){return e.sessionId}function Qd(e,s){if(s)return Yt(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Jd(e,s){const r=$t(e),n=Yt(e),a=et(e)||Xe(e),i=n?a?Ps(e)||(s==null?void 0:s.cliName)||ot(Hr(e)||r):s!=null&&s.type?ot(s.type):ot(Hr(e)||r):Ps(e);return{isNativeConversation:n,isCli:et(e),isAcp:Xe(e),isCliTerminal:bi(e),providerType:r,displayLabel:i,targetEntry:Qd(e,s)}}function Zd(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function os(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||Zd(s==null?void 0:s.receivedAt)||0}function Un(e,s=0){return os(e)||e.lastUpdated||s||0}function ji(e){return os(e)||e.lastUpdated||0}function ki(e,s,r=ji){const n=r(s)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(s.machineName||"");if(a!==0)return a;const i=e.displayPrimary.localeCompare(s.displayPrimary);if(i!==0)return i;const c=e.displaySecondary.localeCompare(s.displaySecondary);return c!==0?c:e.tabKey.localeCompare(s.tabKey)}function Fn(e){var r;const s=wt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function eu(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!Fn(e)&&!e.title.trim()}function tu(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(Fn(r))-Number(Fn(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:ki(s,r)})[0]||null}function Kt(e,s){const r=e.filter(c=>c.routeId===s);if(r.length===0)return null;const n=r.find(c=>c.streamSource==="native")||null,a=r.filter(c=>c.streamSource==="agent-stream"),i=tu(a);return n?i&&eu(n)?i:n:i||r[0]||null}function Xt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function pa(e){return ir(e)||e.tabKey||e.routeId||null}function Si(e){const s=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(s)return s;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Kt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?pa(a):null}function Ni({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Ks(),c=Jt(e),l=gi(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",p=e.streamSource==="agent-stream"&&!!e.agentName,m=!p&&(e.transport==="pty"||e.transport==="acp"),f=Ps(e),w=Yd(e),k=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),T=o.useCallback(()=>{if(r){r();return}const d=pa(e);d&&i(Xt(d))},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[u&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:T,title:w,children:[t.jsx(Tt,{size:12}),t.jsx("span",{children:w})]}):t.jsxs("span",{className:"conversation-meta-chip",title:w,children:[t.jsx(Tt,{size:12}),t.jsx("span",{children:w})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(rr,{size:12}),t.jsx("span",{children:f})]}),m&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(rr,{size:12}),t.jsx("span",{children:f})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:l,children:[t.jsx(Ut,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(Ut,{size:12}),t.jsx("span",{children:l})]}))]})}function xn(e,s){return`${e}:${s}`}function su(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function yr(e,s){su()&&console.debug(`[subscription-manager] ${e}`,s)}class ru{constructor(){Ye(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=xn(n.topic,n.key),c=this.active.get(i);let l=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const m={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,m),yr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((p=s.sendData)==null?void 0:p.call(s,r,n))??!1}const u=()=>{var w;const m=this.active.get(i);if(!m||(m.handlers.delete(a),m.handlers.size>0))return;this.active.delete(i);const f={type:"unsubscribe",topic:n.topic,key:n.key};yr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(w=s.sendData)==null||w.call(s,r,f)};return u.initialSendAccepted=l,u}publish(s){const r=xn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Ts.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(a=>{a(s),Ts.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}updateParams(s,r,n){const a=xn(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;yr("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(n=>({daemonId:n.daemonId,topic:n.request.topic,key:n.request.key}))});for(const n of this.active.values())(r=s.sendData)==null||r.call(s,n.daemonId,n.request)}resubscribeForDaemon(s,r){var a;const n=Array.from(this.active.values()).filter(i=>i.daemonId===s);yr("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}}const Qt=new ru;function nu(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function au(e){const s=[],r=new Map;for(const n of e)if(n.parentId){const a=r.get(n.parentId)||[];a.push(n),r.set(n.parentId,a)}else s.push(n);return{topLevel:s,childrenByParent:r}}function Ur(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:p,childrenByParent:m}=au(u),f=nu(i,n),w=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,k=p.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),T=p.filter(b=>b.kind==="agent"&&b.transport==="pty"),d=p.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...w&&{machine:w,platform:w.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},cdpConnected:k.some(b=>!!b.cdpConnected)});for(const b of k){const v=f.get(b.id),h=Ys(b,v),C=(m.get(b.id)||[]).map(P=>Ys(P,f.get(P.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:b.id,workspace:h.workspace,terminals:0,childSessions:C,agents:C.map(P=>({id:P.id,name:P.providerName||P.providerType,type:P.providerType,status:P.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l})}for(const b of T){const v=f.get(b.id),h=Ys(b,v);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:b.id,cliName:h.providerName||h.providerType,mode:h.mode||(v==null?void 0:v.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isCli:!0})}for(const b of d){const v=f.get(b.id),h=Ys(b,v);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(v==null?void 0:v.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:b.id,cliName:h.providerName||h.providerType,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const bn=new Map,gn=new Map,yn=new Set,Js=new Map,ou=1200;function iu(e){if(!e||typeof e!="object")return null;const s=e,r=s.status;if(r&&typeof r=="object")return r;const n=s.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return s}function eo(e,s){const r=Js.get(e);!r||r.size===0||(Js.delete(e),r.forEach(n=>n(s)))}function cu(e,s){return new Promise(r=>{const n=Js.get(e)||new Set;Js.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Js.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function lr(){const{sendCommand:e,sendData:s}=Mt(),{injectEntries:r,getIdes:n}=Br();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=gn.get(a)||0;if(!(i!=null&&i.force)&&yn.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=bn.get(a);if(u)return u;const p=(async()=>{if(s&&!yn.has(a)&&(yn.add(a),Qt.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},d=>{const b=n(),v=b.find(C=>C.id===a),h=Ur(d.status,{daemonId:a,existingDaemon:v,existingEntries:b,timestamp:d.timestamp});h.length>0&&r(h),gn.set(a,Date.now()),eo(a,!0)}),!(i!=null&&i.force)&&await cu(a,ou)))return;const m=await e(a,"get_status_metadata"),f=iu(m);if(!f)return;const w=n(),k=w.find(d=>d.id===a),T=Ur(f,{daemonId:a,existingDaemon:k,existingEntries:w,timestamp:f.timestamp||Date.now()});T.length>0&&r(T,{authoritativeDaemonIds:[a]}),gn.set(a,Date.now()),eo(a,!0)})().finally(()=>{bn.delete(a)});return bn.set(a,p),p},[n,r,e,s])}function zt(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function fa(e,s){if(!e||!s)return!1;if(e===s||e.id&&s.id&&String(e.id)===String(s.id)||e._localId&&s._localId&&String(e._localId)===String(s._localId))return!0;const r=String(e.role||"").toLowerCase(),n=String(s.role||"").toLowerCase();if(r!==n)return!1;const a=Ls(e.content),i=Ls(s.content);if(!a||a!==i)return!1;const c=zt(e),l=zt(s);return c&&l?Math.abs(c-l)<=15e3:!!e._localId!=!!s._localId}function to(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),zt(e)&&(s+=1),s}function Ds(e){return Ls(e==null?void 0:e.content)}function zn(e,s){return!e||!s||e.length<=s.length||s.length<80?!1:e.startsWith(s)||e.includes(s)}function lu(e,s){const r=Ds(e),n=Ds(s);return!r||!n||r===n?null:zn(r,n)?e:zn(n,r)?s:null}function du(e,s){const r=lu(e,s);if(r)return r;const n=to(e),a=to(s);return a!==n?a>n?s:e:Ds(s).length>=Ds(e).length?s:e}function is(e){const s=[];for(const r of e){const n=s.findIndex(a=>fa(a,r));if(n>=0){s.splice(n,1,du(s[n],r));continue}s.push(r)}return s}function uu(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:is([...r,...n])}function so(e){return[...e].sort((s,r)=>{const n=zt(s),a=zt(r);return n&&a&&n!==a?n-a:0})}function ro(e,s){const r=e.filter(n=>String((n==null?void 0:n.role)||"").toLowerCase()==="user").slice();return s.filter(n=>{const a=r.findIndex(i=>fa(i,n));return a>=0?(r.splice(a,1),!1):!0})}function mu(e,s){return e.filter(r=>{const n=Ds(r),a=String((r==null?void 0:r.role)||"").toLowerCase(),i=zt(r);return!s.some(c=>{if(fa(r,c))return!0;const l=String((c==null?void 0:c.role)||"").toLowerCase();if(!n||!a||a!==l)return!1;const u=Ds(c);if(!zn(u,n)&&u!==n)return!1;const p=zt(c);return i&&p?Math.abs(i-p)<=15e3:!0})})}const pu=60,fu=200;function hu(e={}){return e.isCliLike?fu:pu}function xu(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)s^=n.charCodeAt(a),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function bu(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function gu(e){return e?xu([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),bu(e.content)]):""}const dr=60,no=new Map;function Ci(e,s){return`${e}::${s}`}function Vn(e=dr){return{liveMessages:[],cursor:Ai([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Ii(e){return gu(e)}function Ai(e,s=dr){return{knownMessageCount:e.length,lastMessageSignature:Ii(e[e.length-1]),tailLimit:s}}function vr(e,s){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function yu(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return is([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return is([...e.slice(0,n),...r])}case"full":{const n=Math.max(Number(s.totalMessages||0),r.length);if(n>r.length&&e.length>r.length){const a=Math.max(0,n-r.length);return is([...e.slice(0,a),...r])}return r}default:return r}}class vu{constructor(s){Ye(this,"manager");Ye(this,"sendData");Ye(this,"daemonId");Ye(this,"sessionId");Ye(this,"historySessionId");Ye(this,"subscriptionKey");Ye(this,"snapshot");Ye(this,"transportSubscription",null);Ye(this,"listeners",new Set);Ye(this,"retainCount",0);Ye(this,"loadHistoryPromise",null);this.manager=s.manager||Qt,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=Vn(Math.max(0,s.tailLimit??dr))}updateOptions(s){s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId)}getSnapshot(){return this.snapshot}hydrateLiveMessages(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=is([...r,...this.snapshot.liveMessages]);if(n.length<r.length)return;const a=Ai(n,this.snapshot.cursor.tailLimit);vr(this.snapshot.liveMessages)===vr(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a})}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}retain(){this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),this.retainCount===0&&this.disconnect()}async loadHistoryPage(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await s(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}},s=>{this.handleUpdate(s)}))}disconnect(){var s;(s=this.transportSubscription)==null||s.call(this),this.transportSubscription=null}dispose(){this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){const r=yu(this.snapshot.liveMessages,s),n={knownMessageCount:Math.max(r.length,Number(s.totalMessages||0)),lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:Ii(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};vr(this.snapshot.liveMessages)===vr(r)&&this.snapshot.cursor.knownMessageCount===n.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===n.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:r,cursor:n},this.manager.updateParams("session.chat_tail",this.subscriptionKey,{knownMessageCount:n.knownMessageCount,lastMessageSignature:n.lastMessageSignature}),this.emit())}}function Ti(e){const s=Ci(e.daemonId,e.sessionId),r=no.get(s);if(r)return r.updateOptions(e),r;const n=new vu(e);return no.set(s,n),n}function wu(e,s){return{...e,loadHistoryPage:s}}function ju(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function ku(e){const s=new Set,r=[];for(const n of e){const a=cr(n),i=n.sessionId||"";if(!a||!i)continue;const c=Ci(a,i);if(s.has(c))continue;s.add(c);const l=ir(n);r.push({daemonId:a,sessionId:i,historySessionId:l||i,subscriptionKey:`daemon:${a}:session:${i}`})}return r.sort(ju),{descriptors:r,signature:r.map(n=>`${n.subscriptionKey}|${n.historySessionId}`).join("||")}}function Su(e,s){const{sendData:r,sendCommand:n}=Mt(),a=(s==null?void 0:s.enabled)!==!1,i=cr(e),c=e.sessionId||"",l=ir(e)||c,u=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??dr),m=o.useMemo(()=>!a||!i||!c?null:Ti({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:p}),[i,a,l,r,c,u,p]),[f,w]=o.useState(()=>(m==null?void 0:m.getSnapshot())||Vn(p));o.useEffect(()=>{if(!m){w(Vn(p));return}m.hydrateLiveMessages(e.messages),m.retain(),w(m.getSnapshot());const T=m.subscribe(d=>{w(d)});return()=>{T(),m.release()}},[e.messages,m,p]);const k=o.useCallback(async()=>{!m||!i||!c||await m.loadHistoryPage(async()=>{const T=e.agentType,d=await n(i,"chat_history",{agentType:T,offset:m.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),b=d&&typeof d=="object"&&"result"in d?d.result||{}:d||{};return{messages:Array.isArray(b.messages)?b.messages:[],hasMore:b.hasMore===!0}})},[e.agentType,m,i,l,n,c]);return o.useMemo(()=>wu(f,k),[k,f])}function Nu(e,s){const{sendData:r}=Mt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,dr),i=o.useMemo(()=>ku(e),[e]);o.useEffect(()=>{if(!r||i.descriptors.length===0)return;const c=i.descriptors.map(l=>Ti({...l,sendData:r,tailLimit:a}));return c.forEach(l=>l.retain()),()=>{c.forEach(l=>l.release())}},[i.signature,n,r,a])}function Cu(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Iu(e){return Cu(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Au=60;function Gn({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:a,isFocusingAgent:i,actionLogs:c,userName:l,showMetaChips:u=!1,scrollToBottomRequestNonce:p,isInputActive:m=!0}){var A,D;const f=o.useRef(new Map),w=lr();or("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const k=at.useMemo(()=>Ws(e),[e.status,e.connectionState]),T=o.useMemo(()=>Jd(e,s),[e,s]),d=hu({isCliLike:T.isCli||T.isAcp}),b=Su(e,{enabled:!!e.sessionId}),[v,h]=o.useState(d),C=e.tabKey,P=b.historyMessages,y=b.hasMoreHistory,S=b.historyError,j=uu(b.liveMessages,e.messages);o.useEffect(()=>{h(d)},[d,C]);const g=Math.max(0,j.length-v),x=ma(e),K=cr(e),I=Iu(e),[M,L]=o.useState(!1);o.useEffect(()=>{const $=T.targetEntry;K&&(!$||$.providerControls===void 0||$.controlValues===void 0)&&w(K,{minFreshMs:3e4}).catch(()=>{})},[K,T.isAcp,(A=T.targetEntry)==null?void 0:A.providerControls,(D=T.targetEntry)==null?void 0:D.controlValues,w]);const O=o.useCallback(async()=>{if(!M){if(j.length>v){h($=>Math.min(j.length,$+Au));return}L(!0);try{await b.loadHistoryPage()}finally{L(!1)}}},[b,M,j.length,v]),{allMessages:R,receivedAtMap:N}=o.useMemo(()=>{const $=g>0?j.slice(-v):j;if(P.length===0){const Le=so(is($)),ce={};return Le.forEach((Ie,te)=>{const ue=`${e.tabKey}:${Ss(Ie,te)}`;let ae=zt(Ie)||f.current.get(ue)||0;ae||(ae=Date.now(),f.current.set(ue,ae)),ce[Ss(Ie,te)]=ae}),{allMessages:Le,receivedAtMap:ce}}const W=mu(P,$),X=so(is([...W,...$])),we={};return X.forEach((Le,ce)=>{const Ie=`${e.tabKey}:${Ss(Le,ce)}`;let te=zt(Le)||f.current.get(Ie)||0;te||(te=Date.now(),f.current.set(Ie,te)),we[Ss(Le,ce)]=te}),{allMessages:X,receivedAtMap:we}},[e.tabKey,g,P,j,v]),U=o.useMemo(()=>c.filter($=>$.routeId===e.tabKey).sort(($,W)=>$.timestamp-W.timestamp),[c,e.tabKey]),G=o.useMemo(()=>{if(j.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((k.isGenerating||e.status==="streaming")&&L(!1),e.status==="not_monitored"&&I)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(rr,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:a,disabled:i,className:"btn btn-primary",children:i?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ms,{size:14})," Open ",x," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&I)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Jo,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:a,disabled:i,className:"btn btn-primary",children:i?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ms,{size:14})," Open ",x," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!M)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,I,a,i,M,j.length,x,k.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[u&&t.jsx(Ni,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Xl,{messages:R,actionLogs:U,agentName:Ps(e)||x||"Agent",userName:l,isCliMode:T.isCli||T.isAcp,isWorking:k.isGenerating,contextKey:e.tabKey,receivedAtMap:N,onLoadMore:O,isLoadingMore:M,hasMoreHistory:y,hiddenLiveCount:g,loadError:S??void 0,emptyState:G,scrollToBottomRequestNonce:p}),m&&!T.isCliTerminal&&(()=>{var $,W;return t.jsx(Vd,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:T.providerType,displayLabel:T.displayLabel,controls:($=T.targetEntry)==null?void 0:$.providerControls,controlValues:(W=T.targetEntry)==null?void 0:W.controlValues})})(),!T.isCliTerminal&&t.jsx(Gd,{contextKey:e.tabKey,panelLabel:x,isSending:n,onSend:r,isActive:m})]})}let Mi=fs;function Li(){return Mi()}class Tu{constructor(){Ye(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(a=>a(...r))}}let _i=new Tu;class Mu{sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,a){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let dt=new Mu;function Lu(e){e.dashboardWS&&(_i=e.dashboardWS),e.connectionManager&&(dt=e.connectionManager),e.useDaemonsHook&&(Mi=e.useDaemonsHook)}function ct(e){return ma(e)}function bs(e){return vi(e).join(" · ")}function Ri(e){if(e.lastMessagePreview)return e.lastMessagePreview;const s=[...e.messages].reverse().find(n=>!(n!=null&&n._localId))||e.messages[e.messages.length-1],r=Ls(s==null?void 0:s.content);return r||(e.title?e.title:bs(e)||"No messages yet")}function Pi(e,s){const{isReconnecting:r,isConnecting:n}=Ws(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function _u(e,s){const r=["Chat",...vi(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function cs(e){return Pi(e)||bs(e)}function Ru(e){return`${ct(e)} · ${Ri(e)}`}function Pu(e){const s=Hr(e),r=s?ot(s):Ps(e);return`${ct(e)} — ${r||"Agent"}`}function Du(e){return Ps(e)||"CLI"}function Di(e){return yi(e)}function $i(e){return e?`Remote · ${ct(e)||e.workspaceName||"Session"}`:"Remote"}function $u({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,isVisible:i=!0}){var D;const{ides:c}=fs(),l=o.useRef(null),{sendCommand:u,sendData:p}=Mt(),[m,f]=o.useState(""),[w,k]=o.useState(!1),[T,d]=o.useState(1),b=o.useRef(!1),v=o.useRef(0),h=o.useRef(!1),C=o.useRef(""),P=o.useRef(null),y=o.useRef(!1),S=o.useRef(null),j=e.tabKey,g=e.sessionId||"",x=e.daemonId||((D=e.routeId)==null?void 0:D.split(":")[0])||e.routeId||"",K=c.find($=>$.id===x&&$.type==="adhdev-daemon"),I=(K==null?void 0:K.terminalSizingMode)==="fit"?"fit":"measured",M=.6,L=1.15,O=()=>{if(typeof window>"u")return 1;const $=window.innerWidth||0;return $<=360?.68:$<=390?.74:$<=430?.82:$<=480?.9:1},R=()=>{var $,W;v.current=0,h.current=!1,C.current="",P.current=null,y.current=!1,S.current!==null&&(cancelAnimationFrame(S.current),S.current=null),k(!1),(W=($=r.current)==null?void 0:$.reset)==null||W.call($)},N=()=>{var $,W;v.current=0,h.current=!1,C.current="",P.current=null,y.current=!1,S.current!==null&&(cancelAnimationFrame(S.current),S.current=null),k(!0),(W=($=r.current)==null?void 0:$.reset)==null||W.call($)},U=()=>{var W;if(S.current=null,!i)return;const $=C.current;$&&(C.current="",(W=r.current)==null||W.write($))},G=$=>{$&&(C.current+=$,i&&S.current===null&&(S.current=requestAnimationFrame(U)))},A=($,W=0,X,we)=>{var Le,ce,Ie,te,ue;W>0&&v.current>=W||W===0&&h.current||(v.current=W,k(!0),typeof X=="number"&&typeof we=="number"&&X>0&&we>0&&((ce=(Le=r.current)==null?void 0:Le.resize)==null||ce.call(Le,X,we)),(te=(Ie=r.current)==null?void 0:Ie.reset)==null||te.call(Ie),$&&((ue=r.current)==null||ue.write($)))};return o.useEffect(()=>{R()},[g]),o.useEffect(()=>{var W;if(!g)return;const $=((W=dt.onRuntimeEvent)==null?void 0:W.call(dt,g,X=>{if(!(!X||X.sessionId!==g)){if(X.type==="runtime_snapshot"){if(!i){P.current={text:X.text||"",seq:X.seq||0,cols:X.cols,rows:X.rows};return}A(X.text||"",X.seq||0,X.cols,X.rows);return}if(X.type==="session_output"){h.current=!0,typeof X.seq=="number"&&(v.current=Math.max(v.current,X.seq)),w||k(!0),typeof X.data=="string"&&G(X.data);return}if(X.type==="session_cleared"){if(!i){y.current=!0,C.current="",P.current=null;return}N()}}}))||(()=>{});return()=>{$()}},[x,g,r,i,w]),o.useEffect(()=>{var W,X,we;if(!g)return;x&&((W=dt.getState)==null?void 0:W.call(dt,x))==="connected"&&(k(!0),(X=dt.requestRuntimeSnapshot)==null||X.call(dt,x,g).catch(()=>{}));const $=(we=dt.onStateChange)==null?void 0:we.call(dt,(Le,ce)=>{var Ie;Le!==x||ce!=="connected"||(k(!0),(Ie=dt.requestRuntimeSnapshot)==null||Ie.call(dt,x,g).catch(()=>{}))});return()=>{$==null||$()}},[x,g,r]),o.useEffect(()=>{s&&R()},[s,j,r]),o.useEffect(()=>{f("")},[e.tabKey]),o.useEffect(()=>{const $=()=>{b.current||d(O())};return $(),window.addEventListener("resize",$),()=>window.removeEventListener("resize",$)},[]),o.useEffect(()=>{var W;if(!i){(W=l.current)==null||W.blur();return}y.current&&(y.current=!1,N());const $=P.current;$&&(P.current=null,A($.text,$.seq,$.cols,$.rows)),C.current&&S.current===null&&(S.current=requestAnimationFrame(U)),requestAnimationFrame(()=>{var X;(X=r.current)==null||X.bumpResize()})},[i]),o.useEffect(()=>()=>{S.current!==null&&(cancelAnimationFrame(S.current),S.current=null)},[]),o.useEffect(()=>{const $=W=>{var we;const X=W.detail;X!=null&&X.sessionId&&X.sessionId!==g||w&&((we=r.current)==null||we.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",$),()=>{window.removeEventListener("adhdev:fit-cli-terminal",$)}},[w,g,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{b.current=!0,d($=>Math.max(M,Number(($-.1).toFixed(2))))},title:"Shrink terminal viewport",children:"-"}),t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{b.current=!0,d($=>Math.min(L,Number(($+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-auto rounded-lg",children:t.jsx("div",{style:{width:`${100/T}%`,height:`${100/T}%`,transform:`scale(${T})`,transformOrigin:"top left"},children:t.jsx(ri,{ref:r,readOnly:!w||!i,sizingMode:I,onInput:$=>{w&&(p!=null&&p(x,{type:"pty_input",sessionId:g,targetSessionId:g,data:$})||u(x,"pty_input",{targetSessionId:g,data:$}).catch(console.error))}})})}),!w&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),t.jsx("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:t.jsxs("div",{className:"flex gap-2.5 items-center",children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:l,type:"text",placeholder:`Send message to ${ct(e)}...`,value:m,disabled:!w||!i||a,onChange:$=>f($.target.value),onPaste:$=>{const W=$.clipboardData.getData("text");W&&f(X=>X+W),$.preventDefault()},onKeyDown:$=>{if($.key!=="Enter")return;if($.nativeEvent.isComposing){$.preventDefault();return}$.preventDefault();const W=m.trim();!w||!W||a||(f(""),n(W))},className:"w-full h-9 rounded-[18px] px-4 bg-bg-secondary text-[13px] text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{const $=m.trim();!w||!$||a||(f(""),n($))},disabled:!w||!i||!m.trim()||a,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:m.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function Eu({wsStatus:e,showReconnected:s,loginUrl:r}){const n=e==="disconnected"||e==="reconnecting"||e==="offline"||e==="auth_failed",a=e==="auth_failed"?"red":e==="offline"?"orange":"accent",i={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},c={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},l={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"};return t.jsxs(t.Fragment,{children:[n&&t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5 justify-center",style:{background:i[a],borderBottom:c[a],color:l[a]},children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),e==="offline"&&"Network offline — waiting for connection...",e==="disconnected"&&"Reconnecting to server...",e==="reconnecting"&&"Reconnecting to server...",e==="auth_failed"&&(r?t.jsxs(t.Fragment,{children:["Session expired."," ",t.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — please restart the server.")]}),s&&e==="connected"&&t.jsxs("div",{className:"py-2 px-4 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-b border-green-500/15 animate-[fadeIn_0.3s_ease]",children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})]})}function Ku({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!s||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",u=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[t.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[t.jsxs("span",{children:[l," is using `xterm` fallback."]}),t.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),t.jsx("button",{type:"button",onClick:u,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function ha({mode:e,onChange:s,compact:r=!1}){const n=r?14:15;return t.jsx("button",{type:"button",onClick:()=>s(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?t.jsx(Qr,{size:n}):t.jsx(Ft,{size:n})})}function ao({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function oo({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Zr(e.updatedAt),l=!e.readAt;return t.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[s?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",s]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?t.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),t.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function Bu({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetCliViewMode:p,onHideConversation:m,hiddenConversations:f=[],onShowConversation:w,onShowAllHidden:k,onResetPanelsToMain:T,inboxOpen:d,onInboxOpenChange:b,hiddenOpen:v,onHiddenOpenChange:h,onOpenNewSession:C,actionShortcuts:P,notifications:y,notificationUnreadCount:S,onOpenNotification:j,onMarkNotificationRead:g,onMarkNotificationUnread:x,onDeleteNotification:K}){const{ides:I,p2pStates:M={}}=fs(),L=!!e&&et(e)&&!Xe(e),O=!!e&&Xe(e),R=u||(e?bi(e)?"terminal":"chat":null),[N,U]=o.useState(!1),G=o.useRef(null),A=o.useRef(null),D=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",$=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",W=I.filter(F=>F.type==="adhdev-daemon"),X=Object.values(M),we=X.filter(F=>F==="connected").length,Le=X.filter(F=>F==="connecting"||F==="new"||F==="checking").length,Ie=r!=="connected"||W.length===0?null:Le>0&&we===0?"P2P connecting...":we>0&&s===0?"Waiting for IDE...":null,te=o.useMemo(()=>y.filter(F=>!F.readAt),[y]),ue=o.useMemo(()=>y.filter(F=>!!F.readAt),[y]),ae=o.useMemo(()=>te.slice(0,9),[te]),xe=S;o.useEffect(()=>{if(!d)return;const F=be=>{var se;(se=G.current)!=null&&se.contains(be.target)||b(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[d,b]),o.useEffect(()=>{if(!v)return;const F=be=>{var se;(se=A.current)!=null&&se.contains(be.target)||h(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[v,h]),o.useEffect(()=>{if(!v&&!d)return;const F=be=>{if(!be.altKey)return;const se=be.code.match(/^Digit([1-9])$/);if(!se)return;const pe=Number(se[1])-1,J=v?f[pe]:void 0,de=d?ae[pe]:void 0;if(!(!J&&!de)){if(be.preventDefault(),be.stopPropagation(),J){w==null||w(J),h(!1);return}de&&(j(de),b(!1))}};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[f,v,d,ae,h,b,j,w]);const oe=F=>{if(!F)return;const be=a.find(se=>se.tabKey===F);be&&(m==null||m(be))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(Ft,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?ct(e):"Dashboard"}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:D,boxShadow:$}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:D,boxShadow:$}}),Ie&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",Ie]}),C&&t.jsx("button",{type:"button",onClick:C,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(Al,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(L||O||!Xe(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:bs(e)||ct(e),children:ct(e)}),(L||O)&&l&&t.jsxs(t.Fragment,{children:[L&&p&&R&&t.jsx(ha,{mode:R,onChange:p,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:O?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(Nt,{size:14})})]}),!Xe(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(aa,{size:14})}),!L&&!Xe(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Tt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:G,children:[t.jsxs("div",{className:`dashboard-header-hidden${N?" is-drop-target":""}`,ref:A,onDragEnter:F=>{F.dataTransfer.types.includes("text/tab-key")&&(F.preventDefault(),U(!0))},onDragOver:F=>{F.dataTransfer.types.includes("text/tab-key")&&(F.preventDefault(),F.dataTransfer.dropEffect="move",U(!0))},onDragLeave:F=>{F.currentTarget.contains(F.relatedTarget)||U(!1)},onDrop:F=>{const be=F.dataTransfer.getData("text/tab-key");F.preventDefault(),U(!1),oe(be)},children:[t.jsxs("button",{type:"button",onClick:()=>h(!v),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${P!=null&&P.toggleHiddenTabs?` (${P.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(Zo,{size:16}),f.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:f.length})]}),v&&t.jsxs("div",{className:"dashboard-header-hidden-popover",children:[t.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),t.jsx(ao,{value:P==null?void 0:P.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[T&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:T,children:"Reset panels"}),f.length>0&&k&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{k(),h(!1)},children:"Restore all"})]})]}),e&&m&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(ao,{value:P==null?void 0:P.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:ct(e)})]}),f.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:f.map(F=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{w==null||w(F),h(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:ct(F)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[f.indexOf(F)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",f.indexOf(F)+1]}):null,bs(F)]})]},F.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>b(!d),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(Jr,{size:16}),xe>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:xe})]}),d&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[te.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),te.map(F=>t.jsx(oo,{notification:F,shortcutIndex:ae.indexOf(F)>=0?ae.indexOf(F)+1:void 0,onOpen:()=>j(F),onMarkRead:()=>g(F.id),onMarkUnread:()=>x(F.id),onDelete:()=>K(F.id)},F.id))]}),ue.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ue.map(F=>t.jsx(oo,{notification:F,onOpen:()=>j(F),onMarkRead:()=>g(F.id),onMarkUnread:()=>x(F.id),onDelete:()=>K(F.id)},F.id))]}),y.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function yt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Wu(e,s){return String(e||"")!==String(s||"")}function Ou(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
|
|
31
|
+
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!mi(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
32
|
+
`).includes(a)))}function Hu(e,s="recent"){const r=e.slice();return r.sort((n,a)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(s==="messages"){const i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function Ei(e,s={}){return Hu(Ou(e,s),s.sortMode||"recent")}function Fr(e){return e?"Resume saved history":"Start fresh"}function xa(e){return e?"Resuming saved history…":"Starting fresh…"}function Uu(){return"Start fresh"}function Ki(e,s=!1){return e==="cli"?Fr(s):e==="ide"?"Start IDE":"Start ACP session"}function Bi(e,s=!1){return e==="cli"?xa(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function Fu(){return"Recover hosted runtime"}function zu(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Vu(){return"Open saved history"}function Gu(){return"Saved History"}function ba(){return"Use saved history when you want continuity in the same provider conversation."}function qu(){return"No saved history found yet."}function Yu(){return"Refresh saved history"}function Xu(){return"Refreshing saved history…"}function ls(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function ds(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function $s(e){return e==="start-fresh"?"Start fresh":"Restart"}function Es(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function ga(e){return`Resume saved history with ${e}?`}function ya(){return"Review or change the target workspace before resuming saved history."}function Qu(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 va({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:p,onNewChat:m,onSwitchSession:f,onRefreshHistory:w,onResumeSavedSession:k}){var g;const T=s.find(x=>x.id===e.routeId),d=(T==null?void 0:T.chats)||[],b=(g=T==null?void 0:T.activeChat)==null?void 0:g.id,v=et(e)&&!Xe(e),[h,C]=o.useState(()=>yt()),P=l||h,y=x=>{if(u){u(x);return}C(x)},S=o.useMemo(()=>Ei(a,{textQuery:P.textQuery,workspaceQuery:P.workspaceQuery,modelQuery:P.modelQuery,resumableOnly:P.resumableOnly,sortMode:P.sortMode}),[P.modelQuery,P.resumableOnly,P.sortMode,P.textQuery,P.workspaceQuery,a]),j=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick:p,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[t.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:v?Gu():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Pu(e)}),v&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:ba()})]}),t.jsx("button",{onClick:p,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(Nt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!v&&t.jsx("button",{onClick:m,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),v?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:P.textQuery,onChange:x=>y({...P,textQuery:x.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:P.workspaceQuery,onChange:x=>y({...P,workspaceQuery:x.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:P.modelQuery,onChange:x=>y({...P,modelQuery:x.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsxs("select",{value:P.sortMode,onChange:x=>y({...P,sortMode:x.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:P.resumableOnly,onChange:x=>y({...P,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),S.map(x=>{const K=e.providerSessionId===x.providerSessionId,I=K||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{I||!k||k(x)},disabled:I,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${K?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${I?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${K?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:x.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:x.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Qu(x.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:x.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[x.workspace||"Workspace unknown",xs(x.summaryMetadata)?` · ${xs(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:K?"ACTIVE":x.canResume?c===x.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},x.id)})]}):d.map(x=>t.jsxs("div",{onClick:()=>{f(e.routeId,x.id),p()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===x.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${b===x.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:x.title||"Untitled Session"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[x.id.substring(0,12),"..."]}),b===x.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},x.id)),(v&&!i&&S.length===0||!v&&d.length===0)&&t.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[t.jsx("div",{className:"text-3xl mb-3 opacity-60",children:t.jsx(_l,{size:32})}),t.jsx("div",{className:"text-[13px]",children:v?a.length>0?"No saved history matches these filters.":qu():"No recent chat sessions found."})]}),v&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:Xu()})})]}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:t.jsx("button",{onClick:w,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bs,{size:13})," ",v?Yu():"Refresh History"]})})})]})]});return typeof document>"u"?j:sr.createPortal(j,document.body)}const io={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 Wi({toasts:e,onDismiss:s,onClickToast:r}){return t.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=io[n.type]||io.info;return t.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[t.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),t.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(Nt,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>t.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:l=>{l.stopPropagation(),i.onClick(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const Ju=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Zu(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function em(e){return e.sessionId||e.instanceId||e.agentType}function vn(e,s){return e||s}function co(e,s){const r=new Set,n=[];for(const a of s)if(a)for(const i of e[a]||[]){const c=i._localId||`${i.role}:${i.timestamp}:${i.content}`;r.has(c)||(r.add(c),n.push(i))}return n.sort((a,i)=>a.timestamp-i.timestamp)}function Oi(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=At(r,{fallbackId:r.id}));return s}function Hi(e,s={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=s.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function wa(e,s,r={}){return tm(e,s,Hi(e,r))}function tm(e,s,r={}){var f,w,k,T,d,b;const n=[],a=r.machineName,i=r.connectionState,c=Zu(e),l=hd(e.type,{agentName:e.cliName}),u=et(e)||Xe(e)?l:ot(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var h,C;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||ot(v.providerType),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((h=v.activeChat)==null?void 0:h.messages)||[],activeModal:((C=v.activeChat)==null?void 0:C.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,surfaceHidden:v.surfaceHidden}}):[],m=Ju(e);if(m){const v=e.sessionId||e.instanceId,h=l,C=(f=e.activeChat)==null?void 0:f.activeModal,P=C&&Array.isArray(C.buttons)&&C.buttons.length>0,y=wt((w=e.activeChat)==null?void 0:w.status,{activeModal:(k=e.activeChat)==null?void 0:k.activeModal})||wt((d=(T=e.agents)==null?void 0:T[0])==null?void 0:d.status)||"idle",S=e.activeChat||{title:"",messages:[]};let j=S.title&&String(S.title).trim()?String(S.title).trim():"";const g=(b=e.activeChat)==null?void 0:b.id,x=e.chats;if(g&&Array.isArray(x)&&x.length>0){const R=x.find(N=>N.id===g||N.id&&String(N.id)===String(g));R!=null&&R.title&&String(R.title).trim()&&(j=String(R.title).trim())}const K=(et(e)||Xe(e),e.type),I=(et(e)||Xe(e))&&Xa(j,h,K)?"":j,M=S.messages||[],L=co(s,[e.id,v]),O=ro(M,L);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:et(e)?e.mode||"terminal":"chat",agentName:h,agentType:K,status:y,title:I,messages:[...M,...O],resume:e.resume,hostIdeType:!et(e)&&!Xe(e)?e.type:void 0,workspaceName:c,displayPrimary:I||c||(et(e)?e.mode==="chat"?h:"Terminal":h),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:P?C.buttons:void 0,modalMessage:P?C.message:void 0,streamSource:"native",tabKey:vn(v,e.id),machineName:a,connectionState:i})}if(m&&(et(e)||Xe(e)))return n;for(const v of p){const h=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,C=xd(v),P=em(v),y=`${e.id}:${P}`,S=v.title&&String(v.title).trim()||"",j=Xa(S,v.agentName,v.agentType)?"":S,g=v.messages||[],x=co(s,[y,v.sessionId,v.instanceId]),K=ro(g,x);(v.transport==="cdp-webview"||v.sessionId||v.providerSessionId||g.length>0||K.length>0||h||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(C))&&n.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:C,title:j,messages:[...g,...K],hostIdeType:e.type,workspaceName:c,displayPrimary:j||c||v.agentName||u,displaySecondary:`${u} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,modalButtons:h?v.activeModal.buttons:void 0,modalMessage:h?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:vn(v.sessionId||v.instanceId,y),machineName:a,connectionState:i})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:vn(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function sm(e){const s=e.split(":");return s.length>=3&&(s[1]==="ide"||s[1]==="cli"||s[1]==="acp")?{daemonId:s[0],targetSessionId:s.slice(2).join(":")||void 0}:{daemonId:e}}function rm(e,s){const r=sm(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Ui=[{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:"🏄"}],Fi=[{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:"🧩"}],zi=[{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:"🟠"}],nm=Ui,am=Fi,om=zi;function gs(...e){return tl(sl(e))}function im({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:gs("dashboard-header",i),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&t.jsx("div",{className:"flex gap-2",children:a})]})}function Vi({icon:e,title:s,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(im,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:gs("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Dt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:gs("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Gi({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:gs("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const cm={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"},lm={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function dm({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:gs("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",cm[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:lm[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const um={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"},mm={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function pm({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:gs("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",um[e],r),children:[t.jsx("span",{className:gs("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",mm[e])}),n]})}const qn="adhdev:themechange";function fm(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function js(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ks(e){return e==="system"?fm():e}function qi(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Rr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(qn,{detail:{preference:e,theme:s}}))}function hm(){const e=js(),s=ks(e);qi(s),Rr(e,s)}function ja(){const[e,s]=o.useState(js),[r,n]=o.useState(()=>ks(js()));o.useEffect(()=>{qi(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const p=u.matches?"light":"dark";n(p),Rr("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const p=u.detail||{},m=p.preference,f=p.theme;s(m==="dark"||m==="light"||m==="system"?m:js()),n(f==="dark"||f==="light"?f:ks(js()))},l=u=>{if(u.key!=="theme")return;const p=js(),m=ks(p);s(p),n(m)};return window.addEventListener(qn,c),window.addEventListener("storage",l),()=>{window.removeEventListener(qn,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=ks(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Rr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=ks(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Rr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const lo={dark:"Dark",light:"Light",system:"System"};function xm({collapsed:e}){const{preference:s,cycleTheme:r}=ja(),n=s==="dark"?t.jsx(Pl,{size:16}):s==="light"?t.jsx(Rl,{size:16}):t.jsx(Dl,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${lo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:lo[s]})]})}function ns({label:e,description:s,checked:r,disabled:n,onChange:a,extra:i}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,t.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[t.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),t.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function bm({onPrefChange:e}){const[s,r]=Cd(),n=(a,i)=>{r({[a]:i}),e==null||e(a,i)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(ns,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Jr,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:a=>n("globalEnabled",a)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(ns,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:a=>n("browserNotifications",a)}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(ns,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx($l,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:a=>n("completionAlert",a)}),t.jsx(ns,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(El,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:a=>n("approvalAlert",a)}),t.jsx(ns,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(rr,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:a=>n("disconnectAlert",a)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function zr(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function gm(e,s){const r=zr(e),n=zr(s);if(!r||!n)return e.localeCompare(s);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function Yi(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Zs(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||gm(r,s)>=0)return!1;const n=zr(r),a=zr(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function ym(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function wn(e,s){return e instanceof Error?e.message:s}function vm({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?t.jsx(Gi,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:s||"Install ADHDev on a machine and sign in to connect it here."}):t.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>t.jsx(jm,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function uo({title:e,message:s,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return sr.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),t.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function wm(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...nm,...am,...om].find(a=>a.id===s||s.includes(a.id)||a.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function jm({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var O,R;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,m]=o.useState(null),[f,w]=o.useState("idle"),[k,T]=o.useState(""),d=e.version||null,b=((O=e.machine)==null?void 0:O.platform)||((R=e.system)==null?void 0:R.platform)||"",v=At(e,{fallbackId:e.id}),h=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",C=s.filter(N=>N.daemonId===e.id&&N.transport==="cdp-page"),P=s.filter(N=>N.daemonId===e.id&&N.transport==="pty"),y=s.filter(N=>N.daemonId===e.id&&N.transport==="acp"),S=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const N=ym(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(wn(N,"Connection lost during upgrade"))}}},g=async()=>{if(m(null),!!n){w("loading");try{await n(e.id),w("done"),T("Machine disconnected.")}catch(N){w("error"),T(wn(N,"Failed to disconnect"))}}},x=async()=>{if(m(null),!!a){w("loading");try{await a(e.id),w("done"),T("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(N){w("error"),T(wn(N,"Failed to revoke token"))}}},K="0.8.72",I=Yi(e,K),M=Zs(e,K),L=C.length+P.length+y.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-xl",children:h}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:v}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),d&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${I?"":"bg-bg-secondary"}`,style:I?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!I&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&I&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${K}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${M?"↑ Update now":`↑ Update${` to v${K}`}`}`}),n&&t.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(pm,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[S&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${S.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${S.state==="connecting"||S.state==="new"?"animate-pulse":""}`,style:S.state==="connecting"||S.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",S.state==="connected"?"connected":S.state==="connecting"||S.state==="new"?"connecting...":S.state||"off"]}),S.peers!==void 0&&S.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",S.peers," peer",S.peers!==1?"s":"",")"]})]}),S&&L>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),L>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(N=>{const U=wm(N.type),G=N.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:U.icon}),t.jsx("span",{children:U.name}),G!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${G?"bg-green-400":"animate-pulse"}`,style:G?void 0:{background:"var(--status-warning)"},title:G?"CDP connected":"CDP connecting..."})]},N.id)}),P.map(N=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:N.cliName||"CLI"})]},N.id)),y.map(N=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:N.cliName||"ACP"})]},N.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||k)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-red-400":i==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:k||l})]}),p==="disconnect"&&t.jsx(uo,{title:"🔌 Disconnect Machine",message:`Disconnect "${v}" from ADHDev?
|
|
33
|
+
|
|
34
|
+
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
35
|
+
|
|
36
|
+
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:g,onCancel:()=>m(null)}),p==="revoke"&&t.jsx(uo,{title:"⚠️ Remove Machine",message:`Remove "${v}" from your dashboard?
|
|
37
|
+
|
|
38
|
+
This will:
|
|
39
|
+
• Immediately disconnect the machine
|
|
40
|
+
• Delete the machine registration
|
|
41
|
+
• Require restarting ADHDev on that machine
|
|
42
|
+
|
|
43
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>m(null)})]})}const km=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Sm(){const{preference:e,setPreference:s}=ja();return t.jsx("div",{className:"flex gap-2",children:km.map(r=>t.jsxs("button",{onClick:()=>s(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[t.jsx("span",{children:r.icon}),r.label]},r.id))})}function Nm(e){const s=e.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function Cm(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function jn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function mo(e){const{r:s,g:r,b:n}=Cm(e);return .2126*jn(s)+.7152*jn(r)+.0722*jn(n)}function po(e,s){const r=mo(e),n=mo(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Xi(e){const s=Nm(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return po(s,r)>=po(s,n)?r:n}const Yn={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},Xn={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},Im=[{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"}}}],Qi="adhdev-chat-theme",Ji="adhdev-chat-theme-custom";function Pr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Qi)||"ember"}catch{return"ember"}}function Et(e){try{const s=localStorage.getItem(Ji);if(s){const r=JSON.parse(s);return{...e==="dark"?Yn:Xn,...r[e]}}}catch{}return e==="dark"?Yn:Xn}function wr(e,s){try{localStorage.setItem(Ji,JSON.stringify({dark:e,light:s}))}catch{}}function Rt(e,s){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${s})`}function Vr(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),a=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const Am={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function er(e,s){var a;const r=(a=Am[e])==null?void 0:a[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Vr(r,24)),n.style.setProperty("--accent-on-primary",Xi(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Vr(r,18)})`),n.style.setProperty("--border-accent",Rt(r,.35)),n.style.setProperty("--nav-active-bg",Rt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Rt(r,.06)}`)}function us(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Rt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Rt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Rt(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",Rt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Rt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Vr(e.accentColor,30)),s.style.setProperty("--accent-on-primary",Xi(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Vr(e.accentColor,40)})`),s.style.setProperty("--border-accent",Rt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Rt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Rt(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${Rt(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function ka(){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 Tm(e){try{localStorage.setItem(Qi,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ms()?"dark":"light";us(Et(s))}else ka(),er(e,ms()?"dark":"light")}function Mm(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Pr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ms()?"dark":"light";us(Et(s))}else ka(),er(e,ms()?"dark":"light")}function ms(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function vt({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Fs({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function Lm({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Et(r));o.useEffect(()=>{a(Et(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const p={...u,[c]:l},f=Et(r==="dark"?"light":"dark");return r==="dark"?wr(p,f):wr(f,p),us(p),s(p),p})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(Fs,{title:"App Background",children:[t.jsx(vt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(vt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(vt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(Fs,{title:"App Text",children:[t.jsx(vt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(vt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(vt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(Fs,{title:"Borders & Accent",children:[t.jsx(vt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(vt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(vt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(Fs,{title:"Chat Bubbles",children:[t.jsx(vt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(vt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(vt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(vt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(Fs,{title:"Chat Layout",children:[t.jsx(vt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(vt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(vt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const c=e?Yn:Xn,u=Et(e?"light":"dark");e?wr(c,u):wr(u,c),a(c),us(c),s(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function _m(){const[e,s]=o.useState(Pr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Et("dark"));o.useEffect(()=>{n(ms());const u=new MutationObserver(()=>{const f=ms();n(f);const w=Pr();w==="custom"?us(Et(f?"dark":"light")):er(w,f?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=ms();n(f);const w=Pr();w==="custom"?us(Et(f?"dark":"light")):er(w,f?"dark":"light")};return p.addEventListener("change",m),()=>{u.disconnect(),p.removeEventListener("change",m)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?us(Et(r?"dark":"light")):(ka(),er(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Et(r?"dark":"light"))},[r]);const c=u=>{s(u),Tm(u)},l=[...Im,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const p=e===u.id,m=r?u.preview.dark:u.preview.light,f=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:p?"var(--bg-glass-hover)":"var(--bg-glass)",border:p?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:p?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[p&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&t.jsx(Lm,{dark:r,onColorsChange:u=>i(u)})]})}const Zi="adhdev_mobileDashboardMode_v1";function ec(){try{return localStorage.getItem(Zi)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Rm(e){try{localStorage.setItem(Zi,e)}catch{}}function Pm(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(ec()==="chat")},[]),t.jsx(ns,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.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=>{s(r),Rm(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function Dm(e,s,r){return{...e||{},id:s,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r.timestamp,platform:r.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...r.machine}}}function $m(e,s){const{sendData:r}=Mt(),{injectEntries:n,getIdes:a}=Br(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>Qt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const m=a().find(w=>w.id===u),f=Dm(m,u,p);n([f])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const Em=4e3;function tc(e,s){const{sendData:r}=Mt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=Qt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},p=>{l&&(clearTimeout(l),l=null),a(p.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Em):c(!1),()=>{l&&clearTimeout(l),u()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function Km(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function sc(e){const{sendData:s}=Mt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=Km(e);if(!a||!e.sessionId||!s){n({});return}const i=Qt.subscribe({sendData:s},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Ts.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return()=>{i()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const rc="adhdev_hiddenTabs";function Bm(){try{const e=localStorage.getItem(rc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function vs(e){try{localStorage.setItem(rc,JSON.stringify([...e]))}catch{}}function Wm(){const[e,s]=o.useState(Bm),r=o.useCallback(p=>{s(m=>{const f=new Set(m);return f.has(p)?f.delete(p):f.add(p),vs(f),f})},[]),n=o.useCallback(p=>{s(m=>{if(m.has(p))return m;const f=new Set(m);return f.add(p),vs(f),f})},[]),a=o.useCallback(p=>{s(m=>{if(!m.has(p))return m;const f=new Set(m);return f.delete(p),vs(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return vs(m),m})},[]),c=o.useCallback((p,m)=>{s(f=>{const w=new Set(f);for(const k of m)w.add(k);return vs(w),w})},[]),l=o.useCallback((p,m)=>{s(f=>{const w=new Set(f);for(const k of m)w.delete(k);return vs(w),w})},[]),u=o.useCallback(p=>e.has(p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function fo(e,s){const r=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!r||e.transport!=="pty")return e;const n=s[r];return!n||e.mode===n?e:{...e,mode:n}}function Om(e,s){if(!Array.isArray(e)||e.length===0||!s||Object.keys(s).length===0)return e;let r=!1;const n=e.map(a=>{const i=fo(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>fo(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function nc(e,s){if(!s)return null;for(const r of e){if(r.sessionId===s&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===s&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function Hm(e,s){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,i]of Object.entries(e))nc(s,a)===i&&(delete n[a],r=!0);return r?n:e}function Um({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{Ad()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Di(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Md(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),p={};for(const[m,f]of Object.entries(l))u-f<5e3&&(p[m]=f);return Object.keys(p).length===Object.keys(l).length?l:p})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(p=>p.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function Fm(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const a=r.get(n.id);if(!a){r.set(n.id,n);continue}const i=(a.workspace?1:0)+(a.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>i||(n.timestamp||0)>(a.timestamp||0))&&r.set(n.id,n)}return Array.from(r.values())}function kn(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function zm(e){let s=2166136261;for(let r=0;r<e.length;r+=1)s^=e.charCodeAt(r),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function ho(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?zm(Ls(r.content)):"";return[e.id||"",e.title||"",e.status||"",s.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function Vm(e){const s=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastUpdated||""),ho(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),ho(r.activeChat)].join(":"))].join("|")}function Gm(e,s){const r=Date.now();return e.map(n=>{const a=s[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function qm(e,s){const r=[],n=e.sessionId||e.instanceId;r.push({key:e.id,ref:s[e.id]}),n&&r.push({key:n,ref:s[n]});for(const a of e.childSessions||[]){const i=a.id||a.providerType,c=`${e.id}:${i}`;r.push({key:c,ref:s[c]}),r.push({key:a.id,ref:s[a.id]})}return r}function Ym(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r].key!==s[r].key||e[r].ref!==s[r].ref)return!1;return!0}function Xm(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of as({routeId:n.routeId}))r.set(i,a);for(const i of as({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of as({tabKey:n.tabKey}))r.set(i,n)}return r}function Qm(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Jm(e){const s=Qm(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=Ls(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Zm({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>Fm(e),[e]),c=o.useMemo(()=>Oi(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),m=o.useRef(new Map),f=o.useRef(new Map),w=o.useMemo(()=>{const y=new Map,S=[];for(const K of i){const{connectionState:I="new",machineName:M}=Hi(K,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),L=qm(K,r),O=Vm(K),R=m.current.get(K.id);if(R&&R.ide===K&&R.sourceSignature===O&&R.connectionState===I&&R.machineName===M&&Ym(R.localRefs,L)){y.set(K.id,R),S.push(...R.conversations);continue}const N=wa(K,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),U={ide:K,sourceSignature:O,connectionState:I,machineName:M,localRefs:L,conversations:N};y.set(K.id,U),S.push(...N)}m.current=y;const j=new Map,g=K=>{const I=Jm(K),M=f.current.get(K.tabKey);if(M&&M.signature===I)return j.set(K.tabKey,M),M.timestamp;const L={signature:I,timestamp:ji(K)||(M==null?void 0:M.timestamp)||0};return j.set(K.tabKey,L),L.timestamp},x=[...S].sort((K,I)=>ki(K,I,g));return f.current=j,x},[i,r,s,c]),k=o.useMemo(()=>{const y=Gm(w,n);return kn(l.current,y)?l.current:(l.current=y,y)},[w,n]),T=o.useMemo(()=>{const y=new Map,S=Array.from(new Set(k.map(j=>j.routeId)));for(const j of S){const g=Kt(k,j);g&&y.set(j,g)}return y},[k]),d=o.useMemo(()=>{const y=new Map;for(const S of k){const j=T.get(S.routeId),g=S.streamSource==="native"&&j?j:S;for(const x of as({providerSessionId:S.providerSessionId,sessionId:S.sessionId}))y.set(x,g)}return y},[k,T]),b=o.useMemo(()=>Xm(k,T),[k,T]),v=o.useCallback(y=>{if(y)return d.get(y)},[d]),h=o.useCallback(y=>{if(y)return b.get(y)},[b]),C=o.useMemo(()=>{const y=k.filter(S=>!a.has(S.tabKey));return kn(u.current,y)?u.current:(u.current=y,y)},[k,a]),P=o.useMemo(()=>{const y=C.map(S=>S.tabKey);return kn(p.current,y)?p.current:(p.current=y,y)},[C]);return{chatIdes:i,conversations:k,visibleConversations:C,visibleTabKeys:P,resolveConversationBySessionId:v,resolveConversationByTarget:h}}function ep({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),i=o.useMemo(()=>{var l;return!e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),c=o.useCallback(()=>{s&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function tp({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{it.setIdes(e)},[e]),o.useEffect(()=>{it.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=it.onToast(u=>{r(m=>m.some(w=>w.message===u.message&&u.timestamp-w.timestamp<3e3)?m:[...m.slice(-4),{id:u.id,message:u.message,type:u.type,timestamp:u.timestamp,targetKey:u.targetKey,actions:u.actions}]);const p=u.duration||5e3;setTimeout(()=>r(m=>m.filter(f=>f.id!==u.id)),p)}),c=it.onSystemMessage((u,p)=>{var k,T;const m=a(u),f=(k=p._localId)==null?void 0:k.startsWith("sys_approval_"),w=!!(m&&(m.status==="waiting_approval"||(T=m.modalButtons)!=null&&T.length||m.modalMessage));f&&w||n(d=>({...d,[u]:[...d[u]||[],p]}))}),l=it.onClearSystemMessage((u,p)=>{n(m=>{var f;return(f=m[u])!=null&&f.length?{...m,[u]:m[u].filter(w=>{var k;return!(w.role==="system"&&((k=w._localId)!=null&&k.startsWith(p)))})}:m})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=_i.on("status_event",c=>{it.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var b;const u=l.data;if((u==null?void 0:u.type)!=="notification_action"||typeof u.action!="string"||!u.action.startsWith("approval_")||!(u.daemonId||u.targetSessionId||u.targetKey))return;const p=u.targetSessionId||u.targetKey||u.daemonId,m=a(p),f=(m==null?void 0:m.routeId)||u.daemonId;if(!f)return;const w=Number(u.buttonIndex),k=u.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[w])||"Approve",T=String(k).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(T);s(f,"resolve_action",{action:d?"approve":"reject",button:k,...Number.isFinite(w)&&{buttonIndex:w},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(v=>console.error("[SW Action] approval failed:",v))};return(c=navigator.serviceWorker)==null||c.addEventListener("message",i),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",i)}},[a,s])}const sp="adhdev_dashboardLayout_v1",rp="adhdev_dashboardDockview_v1",np="adhdev_dashboardDockviewHiddenRestore_v1",zs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Sa(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function ac(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function oc(e){return`${sp}:${e}`}function ap(e){const s=oc(e);return Sa(s,null)}function op(e,s){try{const r=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,n=oc(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function ic(e){return`${rp}:${e}`}function ip(e){const s=ic(e);return Sa(s,null)}function cp(e,s){try{const r=ic(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function cc(e){return`${np}:${e}`}function lp(e){const s=cc(e);return Sa(s,{})}function dp(e,s){try{const r=cc(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function up(){return{groupAssignments:[...zs.groupAssignments],focusedGroup:zs.focusedGroup,groupActiveTabIds:{...zs.groupActiveTabIds},groupTabOrders:{...zs.groupTabOrders},groupSizes:[...zs.groupSizes]}}function mp(){const[e]=o.useState(()=>ac(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[p,m]=o.useState([]),[f,w]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[k,T]=o.useState(!1),d=o.useCallback(()=>{if(k)return;const b=ap(e)??up();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),m(b.groupSizes),T(!0)},[k,e]);return o.useEffect(()=>{k&&op(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[k,e,s,n,i,l,p]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),v=h=>w(h.matches);return b.addEventListener("change",v),()=>b.removeEventListener("change",v)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:p,setGroupSizes:m,isMobile:f,hasHydratedStoredLayout:k,hydrateStoredLayout:d}}function pp(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=ca(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function fp({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:p,activeConv:m,isRefreshingHistory:f,ides:w,handleRefreshHistory:k}){const T=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),v=o.useRef(!1);o.useEffect(()=>{if(!e||T.current||s.length===0)return;if(!a){i();return}const h=r(e);if(!h)return;const C=n.get(h.tabKey)??0;c(P=>({...P,[C]:h.tabKey})),l(C),T.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),u(P=>{const y=new URLSearchParams(P);return y.delete("activeTab"),y},{replace:!0})},[e,s,r,n,a,i,c,l,u]),o.useEffect(()=>{if(!(d.current||a)&&s.length!==0){if(!e){i(),d.current=!0;return}if(T.current){d.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(d.current||a)&&(i(),d.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!p){v.current=!1;return}if(!m||v.current||f)return;const h=w.find(C=>C.id===m.routeId);h&&(!h.chats||h.chats.length===0||pp(h.chats,m))&&(v.current=!0,k())},[p,m,f,w,k]),o.useEffect(()=>{if(!m)return;let h=null,C=0,P=-1,y=0;const S=()=>{h=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(j.length===0){C<18&&(C+=1,h=requestAnimationFrame(S));return}let g=0;for(const x of j)x.scrollTop=x.scrollHeight,g+=x.scrollHeight;g===P?y+=1:(y=0,P=g),C+=1,!(y>=2||C>=18)&&(h=requestAnimationFrame(S))};return h=requestAnimationFrame(S),()=>{h!=null&&cancelAnimationFrame(h)}},[m==null?void 0:m.tabKey])}function hp({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,p]=o.useState(null),[m,f]=o.useState(null),w=o.useMemo(()=>{if(e||!n)return null;const v=l(n);return v&&!et(v)&&!Xe(v)?v:null},[e,n,l]),k=o.useMemo(()=>{const v=u==null?void 0:u.routeId;if(!v)return null;const h=u!=null&&u.tabKey?i.find(C=>C.tabKey===u.tabKey):a?i.find(C=>C.tabKey===a):null;return(h==null?void 0:h.routeId)===v?h:Kt(i,v)},[i,u,a]),T=o.useMemo(()=>{if(k)return c.find(v=>v.id===k.routeId)},[c,k]);o.useEffect(()=>{w&&(p({routeId:w.routeId,tabKey:Za(w)}),f(w),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,w]);const d=o.useCallback(v=>{v&&(p({routeId:v.routeId,tabKey:Za(v)}),f(v))},[]),b=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:k,remoteDialogIdeEntry:T,remoteDialogActiveConv:m,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:b}}function Is(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:et(e)||Xe(e)?{agentType:$t(e)}:e.streamSource==="agent-stream"?{agentType:$t(e)}:s}function ar(e){return e?cr(e):""}function Vs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Sn(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=ca(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function xo({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=o.useState(!1),[p,m]=o.useState(!1),f=o.useCallback(async d=>{try{await e("standalone","launch_ide",{ideType:d,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[e]),w=o.useCallback(async(d,b)=>{try{const v=d||(s==null?void 0:s.daemonId)||"",h=await e(v,"switch_chat",{id:b,sessionId:b,...Is(s)}),C=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||C==="switched"||C==="switched-by-title")return;C===!1||C==="not_found"?Vs(a,"⚠️ Session tab not found — try refreshing history"):typeof C=="string"&&C.startsWith("error:")?Vs(a,`⚠️ Switch error: ${C}`):Vs(a,"⚠️ Session switch failed")}catch(v){console.error("Switch failed",v),Vs(a,`❌ Switch failed: ${v.message||"connection error"}`)}},[s,e,a]),k=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const d=ar(s);await e(d,"new_chat",{...Is(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{u(!1)}}},[s,l,e,c,i]),T=o.useCallback(async()=>{var d,b;if(!(!s||p)){m(!0);try{const v=ar(s),h=async()=>e(v,"list_chats",{forceExpand:!0,...Is(s)});let C=await h(),P=(C==null?void 0:C.chats)||((d=C==null?void 0:C.result)==null?void 0:d.chats);Sn(P,s)&&(await new Promise(y=>setTimeout(y,450)),C=await h(),P=(C==null?void 0:C.chats)||((b=C==null?void 0:C.result)==null?void 0:b.chats)),C!=null&&C.success&&Array.isArray(P)&&(n(s.routeId,P),Sn(P,s)&&!Sn(r,s)&&Vs(a,"⚠️ History dialog did not fully open — try once more"))}catch(v){console.error("Refresh history failed",v)}finally{m(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:f,handleSwitchSession:w,handleNewChat:k,handleRefreshHistory:T}}function xp(e,s){if(e.size!==s.size)return!1;for(const[r,n]of e)if(s.get(r)!==n)return!1;return!0}function bp(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function bo(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(a=>s[Number(a)]===e[Number(a)])}function jr(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function go(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function gp(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(a=>a<e)??s[0];return r[n]??0}function yp(e,s,r){if(s.length<=1)return[];const n=s.map(c=>e[c]).filter(c=>Number.isFinite(c)),a=n.length===s.length?n:Array(r).fill(100/r),i=a.reduce((c,l)=>c+l,0);return i>0?a.map(c=>c/i*100):Array(r).fill(100/r)}function yo(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=Number(n);r[i>=s?i+1:i]=a}return r}function vo(e){return Array(e).fill(100/e)}function vp({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:p}){const m=o.useRef(null),f=o.useMemo(()=>jr(e,p),[e,p]),w=f.assignments,k=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),T=k>1,d=o.useCallback((y,S)=>{s(j=>{const g=new Map(jr(j,p).assignments);return S===0?g.delete(y):g.set(y,S),g}),n(j=>({...j,[S]:y})),r(S)},[s,p,n,r]),b=o.useCallback(y=>{s(S=>{const j=jr(S,p).assignments,g=new Map;for(const[x,K]of j)K!==y&&(K>y?g.set(x,K-1):g.set(x,K));return g}),c(S=>{if(S.length<=1)return[];const j=[...S];j.splice(y,1);const g=j.reduce((x,K)=>x+K,0);return g>0?j.map(x=>x/g*100):[]}),r(0)},[s,p,c,r]),v=o.useCallback((y,S)=>{S.preventDefault();const j=m.current;if(!j)return;const g=S.clientX,x=j.offsetWidth,K=i.length===k?[...i]:vo(k),I=L=>{const R=(L.clientX-g)/x*100,N=[...K];N[y]=Math.max(15,K[y]+R),N[y+1]=Math.max(15,K[y+1]-R),c(N)},M=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",M)},[i,k,c]),h=o.useCallback((y,S,j)=>{if(k>=4)return;const g=j==="left"?S:S+1;s(x=>{const K=jr(x,p).assignments,I=new Map;for(const M of u){const L=K.get(M.tabKey)??0,O=L>=g?L+1:L;O>0&&I.set(M.tabKey,O)}return g>0&&I.set(y,g),I}),c(x=>{const K=x.length===k?[...x]:vo(k),I=K[S]??100/k,M=Math.max(15,I/2),L=Math.max(15,I/2),O=[...K];O[S]=M,O.splice(g,0,L);const R=O.reduce((N,U)=>N+U,0);return O.map(N=>N/R*100)}),n(x=>{const K=yo(x,g);return K[g]=y,K}),a(x=>{const K=yo(x,g);return K[g]=[y],K}),r(g)},[k,s,p,u,c,n,a,r]);o.useEffect(()=>{xp(e,w)||s(w)},[e,w,s]),o.useEffect(()=>{const{mapping:y,usedGroups:S}=f;n(j=>{const g=go(j,y);return bo(j,g)?j:g}),a(j=>{const g=go(j,y);return bo(j,g)?j:g}),r(j=>{const g=l?0:gp(j,S,y);return j===g?j:g}),c(j=>{const g=l?[]:yp(j,S,f.groupCount);return bp(j,g)?j:g})},[f,l,n,a,r,c]);const C=o.useMemo(()=>{const y=Array.from({length:k},()=>[]);for(const S of u){const j=w.get(S.tabKey)??0,g=Math.min(j,k-1);y[g].push(S)}return y},[u,w,k]),P=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:w,numGroups:k,isSplitMode:T,groupedConvs:C,moveTabToGroup:d,closeGroup:b,handleResizeStart:v,splitTabRelative:h,clearAllSplits:P}}function wp({ides:e,sendDaemonCommand:s}){const r="0.8.72",n=o.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Yi(m,r)).sort((m,f)=>Number(Zs(f,r))-Number(Zs(m,r))),[r,e]),a=o.useMemo(()=>n.some(m=>Zs(m,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async m=>{var f,w;u(k=>({...k,[m]:"upgrading"}));try{const k=await s(m,"daemon_upgrade",{});(f=k==null?void 0:k.result)!=null&&f.upgraded||(w=k==null?void 0:k.result)!=null&&w.success?u(T=>({...T,[m]:"done"})):u(T=>({...T,[m]:"error"}))}catch{u(k=>({...k,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const Qn="adhdev_dashboard_notifications_v1",Na=80;function Dr(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Gr(e){return{...e,createdAt:Dr(e.createdAt),updatedAt:Dr(e.updatedAt,e.createdAt),lastEventAt:Dr(e.lastEventAt,e.updatedAt||e.createdAt)}}function jp(e){const s=oi(e);return s==="unknown:"?e.id:s}function kp(e){return[e.type,ai(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Sp(e,s){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?s.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=(i==null?void 0:i.inboxBucket)||"idle",l=c==="needs_attention"?"needs_attention":c==="task_complete"&&(i!=null&&i.unread)?"task_complete":null;if(!l)continue;const u=Dr(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),p=kp({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(Gr({id:p,dedupKey:p,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:yi(a),preview:qd(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return n.sort((a,i)=>i.updatedAt-a.updatedAt)}function Np(e,s,r=Na){const n=new Map;for(const i of e)i.deletedAt||n.set(i.id,Gr(i));for(const i of s){const c=Gr(i),l=n.get(c.id);if(!l){n.set(c.id,c);continue}n.set(c.id,{...l,...c,createdAt:l.createdAt,readAt:l.readAt,deletedAt:l.deletedAt})}const a=new Map;for(const i of Array.from(n.values())){if(i.deletedAt)continue;const c=jp(i),l=a.get(c);if(!l){a.set(c,i);continue}(i.updatedAt>l.updatedAt||i.updatedAt===l.updatedAt&&i.createdAt>l.createdAt)&&a.set(c,i)}return Array.from(a.values()).sort((i,c)=>{const l=c.updatedAt-i.updatedAt;return l!==0?l:c.createdAt-i.createdAt}).slice(0,Math.max(0,r))}function Cp(e,s,r=Date.now()){return e.map(n=>n.id===s?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function Ip(e,s){return e.map(r=>{if(r.id!==s)return r;const n={...r};return delete n.readAt,n})}function Ap(e,s,r=Date.now()){return e.map(n=>Wr(n,s)?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function Tp(e,s){return e.filter(r=>r.id!==s)}function Mp(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function Lp(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=as(r);if(n.length===0)continue;const a=r.readAt?0:1;for(const i of n){const c=s.get(i);if(!c){s.set(i,{unreadCount:a,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(i,{unreadCount:c.unreadCount+a,latestNotificationAt:Math.max(c.latestNotificationAt,r.updatedAt),latestRecordId:c.latestNotificationAt>=r.updatedAt?c.latestRecordId:r.id})}}return s}function _p(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(Qn),s=e?JSON.parse(e):[];return Array.isArray(s)?s.map(r=>Gr(r)).filter(r=>!r.deletedAt):[]}catch{return[]}}function Rp(e){if(!(typeof window>"u"))try{const s=e.filter(r=>!r.deletedAt).slice(0,Na);if(s.length===0){window.localStorage.removeItem(Qn);return}window.localStorage.setItem(Qn,JSON.stringify(s))}catch{}}function Pp(e,s){return e===s?!0:e.length!==s.length?!1:e.every((r,n)=>{const a=s[n];return a?r.id===a.id&&r.updatedAt===a.updatedAt&&r.createdAt===a.createdAt&&r.readAt===a.readAt&&r.preview===a.preview&&r.title===a.title&&r.deletedAt===a.deletedAt:!1})}function Dp(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=Na}=e,a=o.useMemo(()=>Sp(s,r),[s,r]),[i,c]=o.useState(()=>_p());o.useEffect(()=>{c(k=>{const T=Np(k,a,n);return Pp(k,T)?k:T})},[a,n]),o.useEffect(()=>{Rp(i)},[i]);const l=o.useMemo(()=>Mp(i),[i]),u=o.useMemo(()=>Lp(i),[i]),p=o.useCallback((k,T)=>{c(d=>Cp(d,k,T))},[]),m=o.useCallback(k=>{c(T=>Ip(T,k))},[]),f=o.useCallback((k,T)=>{c(d=>Ap(d,k,T))},[]),w=o.useCallback(k=>{c(T=>Tp(T,k))},[]);return{notifications:i,unreadCount:l,notificationStateBySessionId:u,markRead:p,markUnread:m,markTargetRead:f,deleteNotification:w}}function lc(){return"select_session"}function $p(){return"open_panel"}function Ep(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function Kp(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function wo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ca(e){return e instanceof Error?e.message:String(e||"")}function jo(e){const s=Ca(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function ko(e,s){const r=Ca(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function sn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),p=o.useRef(!1),m=o.useRef(null),f=o.useCallback(async d=>{if(!s)return;const b=d.trim();if(!b||p.current)return;const v=Date.now(),h={tabKey:s.tabKey,message:b,timestamp:v};if(Ep(m.current,h))return;p.current=!0,u(!0),m.current=h;const C=`${v}-${Math.random().toString(36).slice(2,8)}`,P={role:"user",content:b,timestamp:v,_localId:C},y=!(et(s)||Xe(s));y&&r(S=>({...S,[h.tabKey]:[...S[h.tabKey]||[],P]}));try{const S=ar(s);if(!S)return;const j=await e(S,"send_chat",{message:b,...Is(s)}),g=wo(j);if(y&&(g!=null&&g.deduplicated||(g==null?void 0:g.sent)===!1)){r(x=>({...x,[h.tabKey]:(x[h.tabKey]||[]).filter(K=>K._localId!==C)}));return}if((g==null?void 0:g.success)===!1)throw new Error((g==null?void 0:g.error)||"Send failed");setTimeout(()=>{const x=Date.now()-6e4;r(K=>{const I=K[h.tabKey];if(!I)return K;const M=I.filter(L=>L.timestamp>x);return M.length===I.length?K:{...K,[h.tabKey]:M}})},6e4)}catch(S){const j=Ca(S);j.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",j):console.error("Send failed",S),m.current=Kp(m.current,h),y&&r(g=>({...g,[h.tabKey]:(g[h.tabKey]||[]).filter(x=>x._localId!==C)})),n(g=>[...g,{routeId:h.tabKey,text:`❌ **Send failed** — ${j||"Unknown error"}`,timestamp:Date.now()}])}finally{p.current=!1,u(!1)}},[s,e,n,r]),w=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(d){console.error("Relaunch failed",d)}},[s,e]),k=o.useCallback(async d=>{if(s)try{const v=(s.modalButtons||[]).indexOf(d),h=d.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),C=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(h),P=ar(s);if(!P)return;const y=await e(P,"resolve_action",{button:d,action:C?"approve":"reject",...v>=0&&{buttonIndex:v},...Is(s)}),S=wo(y);S.success||n(j=>[...j,{routeId:s.tabKey,text:ko(d,S==null?void 0:S.error),timestamp:Date.now()}])}catch(b){jo(b)||console.error("[ModalButton] Error:",b),n(v=>[...v,{routeId:s.tabKey,text:jo(b)?ko(d,b):`❌ **${d}** error`,timestamp:Date.now()}])}},[s,e,n]),T=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,$p(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(d){console.error("Focus agent failed",d)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,isFocusingAgent:i,handleSendChat:f,handleRelaunch:w,handleModalButton:k,handleFocusAgent:T}}const Ia=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,handleFocusAgent:m,isFocusingAgent:f,actionLogs:w,userName:k,scrollToBottomRequestNonce:T,isInputActive:d=!0}){const b=sc(s),v=b.status||b.modalMessage||b.modalButtons?{...s,...b.status?{status:b.status}:{},...b.modalMessage!==void 0?{modalMessage:b.modalMessage}:{},...b.modalButtons!==void 0?{modalButtons:b.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(li,{activeConv:v,onModalButton:c}),v.transport!=="pty"&&v.transport!=="acp"&&v.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[t.jsx("span",{className:"text-sm",children:t.jsx(hs,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,v.transport==="pty"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx($u,{activeConv:v,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(Gn,{activeConv:v,ideEntry:a,handleSendChat:u,isSendingChat:p,handleFocusAgent:m,isFocusingAgent:f,actionLogs:w,userName:k,scrollToBottomRequestNonce:T,isInputActive:d})})]}):t.jsx(Gn,{activeConv:v,ideEntry:a,handleSendChat:u,isSendingChat:p,handleFocusAgent:m,isFocusingAgent:f,actionLogs:w,userName:k,scrollToBottomRequestNonce:T,isInputActive:d})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function Bp({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,isFocusingAgent:l,onBack:u,onOpenNativeConversation:p,onOpenMachine:m,onOpenHistory:f,onOpenRemote:w,onHideConversation:k,onStopCli:T,cliViewMode:d,onSetCliViewMode:b,handleSendChat:v,handleFocusAgent:h,handleModalButton:C,handleRelaunch:P}){const y=o.useRef(null),S=et(e)&&!s,j=S&&d==="terminal",g=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${g} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:u,type:"button","aria-label":"Back",children:t.jsx(ra,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ct(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(Ni,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>p(e),onOpenMachine:()=>m(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[S&&d&&t.jsx(ha,{mode:d,onChange:b,compact:!0}),S&&T&&t.jsx("button",{onClick:()=>{T(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(Nt,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:t.jsx(aa,{size:14})}),!s&&!S&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:t.jsx(Tt,{size:14})}),k&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",title:"Close chat",children:t.jsx(Nt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(Ia,{activeConv:e,clearToken:0,isCliTerminal:j,ideEntry:n,terminalRef:y,handleModalButton:C,handleRelaunch:P,handleSendChat:v,isSendingChat:c,handleFocusAgent:h,isFocusingAgent:l,actionLogs:a,userName:i})})]})}const Nn={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 Wp(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function dc(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(Wp())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Nn[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return t.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("windows"),children:"🪟 Windows"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:Nn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Nn[c].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function uc({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Tt},{key:"chats",label:"Chats",icon:Ft}];return t.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:t.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:i})=>{const c=e===n;return t.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>s(n),type:"button","aria-pressed":c,children:[t.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:t.jsx(i,{size:15})}),t.jsx("span",{children:a})]},n)})})})}function kr({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function ws({children:e,className:s=""}){return t.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:e})}function Gs({icon:e,title:s,subtitle:r,children:n}){return t.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[t.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Sr({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:p}=Ws(e.conversation),m=ct(e.conversation),f=bs(e.conversation),w=Pi(e.conversation,{requiresAction:s==="needs_attention"}),k=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",T=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",d=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",v=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",C="text-[color:var(--status-warning)]";return t.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${k}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${T}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${d}`,children:m}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${h}`,children:ci(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[f,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${C} animate-pulse`,children:"Reconnecting…"})]}):p?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):w==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:C,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${v}`,children:e.preview})]}),a&&!l&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),l&&t.jsx("span",{className:"absolute top-4 right-4 rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Done"}),i&&t.jsx("span",{className:"absolute top-4 right-4 rounded-full bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:"Live"})]},e.conversation.tabKey)}function So({size:e=32,label:s}){return t.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[t.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}}),s&&t.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function Op({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:p,onShowAllHidden:m,onOpenNewSession:f,onOpenMachine:w,onOpenSettings:k,onSectionChange:T,wsStatus:d="connected",isStandalone:b=!1}){const v=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",h=c.length>0,C=s.length>0||r.length>0||n.length>0||a.length>0,P=e==="machines"?"Machines":"Chats",y=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",S=b?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${y}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:P}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[t.jsx(Jr,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:k,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:t.jsx(Xr,{size:18})})]})]})}),t.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${S}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:v?t.jsx(Gs,{icon:t.jsx(So,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:d==="offline"?"Your device appears to be offline. Waiting for network…":d==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(Gs,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:b?"Waiting for your daemon":"Connect your machines",subtitle:b?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":"Install ADHDev on a machine, sign in, and it will show up here.",children:!b&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(dc,{})})}):t.jsx(ws,{children:c.map((j,g)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${g>0?"border-t border-border-subtle/70":""}`,onClick:()=>w(j.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(j.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(kr,{title:"Needs attention",className:"mb-0"}),t.jsx(ws,{children:s.map((j,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(Sr,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(kr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(ws,{children:r.map((j,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(Sr,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(kr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(ws,{children:n.map((j,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(Sr,{item:j,type:"working",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(kr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(ws,{children:a.map((j,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(Sr,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):C?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):v?t.jsx(Gs,{icon:t.jsx(So,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(Gs,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Ft,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(Gs,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),t.jsx(ws,{className:"bg-bg-secondary/25",children:i.map((j,g)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${g>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(j),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(ct(j))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:ct(j)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:bs(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.tabKey))})]})]}),e==="chats"&&f&&t.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:f,"aria-label":"Start new session",children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),t.jsx(uc,{section:e,onSectionChange:T})]})}function Hp(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 mc(e){const s=[e.workspace||"Workspace unknown"],r=xs(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=Hp(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function rn(...e){const s=new Set,r=[],n=a=>{const i=typeof a=="string"?a.trim():"";if(!i)return;const c=i.toLowerCase();s.has(c)||(s.add(c),r.push(i))};for(const a of e){if(Array.isArray(a)){for(const i of a)n(i);continue}n(a)}return r}function Up(e){const s=e.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function nn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Up(r);if(n)return n}return"C:\\"}for(const r of s){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function Fp(e){const s=e.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.split(/[\\/]/);return/^[A-Za-z]:$/.test(n[0]||"")?n.length<=2?`${n[0]}\\`:n.slice(0,-1).join("\\"):n.length<=2?r:n.slice(0,-1).join(r)||r}function zp(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function an(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=zp(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const i=typeof(a==null?void 0:a.path)=="string"?a.path:r,c=i.includes("\\")?"\\":"/",l=(p,m)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${m}`:p==="/"||p==="\\"?`${c}${m}`:`${p.replace(/[\\/]+$/,"")}${c}${m}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:l(i,p.name)})).sort((p,m)=>p.name.localeCompare(m.name)):[];return{path:i,directories:u}}function on({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:p}){const[m,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const w=Fp(r),k=m.trim();return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:t.jsx(Nt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!w||a||u(w)},disabled:!w||a,children:[t.jsx(ra,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:m,onChange:T=>f(T.target.value),onKeyDown:T=>{T.key!=="Enter"||!k||a||(T.preventDefault(),u(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||a||u(k)},disabled:!k||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(T=>t.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(T.path),children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Ms,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:T.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:T.path})]})]},T.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(k||r),disabled:!k&&!r||a,children:c})]})]})})}function Aa({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:p,argsValue:m,onArgsChange:f,showModelInput:w,modelValue:k,onModelChange:T,historyProviderNode:d,onConfirm:b,onCancel:v}){const h=n==null?void 0:n.find(C=>C.key===a);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:v,"aria-label":"Close launch confirmation",children:t.jsx(Nt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:a||"",onChange:C=>i(C.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(C=>t.jsx("option",{value:C.key,children:C.label},C.key))}),(h==null?void 0:h.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),d,r.map(C=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:C.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),w&&T&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:k||"",onChange:C=>T(C.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&f&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:m||"",onChange:C=>f(C.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:v,disabled:u,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:u,children:[t.jsx(oa,{size:14}),u?l:c]})]})]})})}function No(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ps(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of s.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===s.defaultWorkspaceId?"⭐ ":""}${No(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:No(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(p=>p.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Vp(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Gp(e){return[Vp(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function qp(e){return e.lastLaunchedAt?Zr(e.lastLaunchedAt):""}function pc(e){return{metaText:Gp(e),updatedLabel:qp(e)}}function Cn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function Yp({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var mt,tt,xt,pt;const c=lr(),[l,u]=o.useState(!1),p=(((mt=e.detectedIdes)==null?void 0:mt.length)||0)>0,m=o.useMemo(()=>(e.workspaces||[]).map(le=>({id:le.id,path:le.path,label:le.label})),[e]),f=e.defaultWorkspaceId||null,[w,k]=o.useState(f||((tt=m[0])==null?void 0:tt.id)||""),[T,d]=o.useState(""),[b,v]=o.useState(""),[h,C]=o.useState([]),[P,y]=o.useState(!1),[S,j]=o.useState(""),[g,x]=o.useState(!1),[K,I]=o.useState(Cn(p,s.length,r.length)),M=o.useRef(null),[L,O]=o.useState(null),R=o.useRef("__home__"),[N,U]=o.useState("__home__"),[G,A]=o.useState(""),[D,$]=o.useState(""),[W,X]=o.useState(""),[we,Le]=o.useState([]),[ce,Ie]=o.useState(()=>yt().textQuery),[te,ue]=o.useState(()=>yt().workspaceQuery),[ae,xe]=o.useState(()=>yt().modelQuery),[oe,F]=o.useState(()=>yt().resumableOnly),[be,se]=o.useState(()=>yt().sortMode),[pe,J]=o.useState(!1),[de,ne]=o.useState(!1),ge=o.useRef(null),me=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const E=w==="__custom__"?T.trim():((xt=m.find(le=>le.id===w))==null?void 0:xt.path)||"",ye=w==="__custom__"&&!!E&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),he=w!=="__custom__"&&((pt=m.find(le=>le.id===w))==null?void 0:pt.path)||"",je=o.useMemo(()=>(e.recentLaunches||[]).map(le=>le.workspace),[e]),Q=o.useCallback(async le=>{y(!0),j("");try{const Ve=await a(le);v(Ve.path),d(Ve.path),C(Ve.directories)}catch(Ve){j(Ve instanceof Error?Ve.message:"Could not load folder")}finally{y(!1)}},[a]),ke=o.useCallback(()=>{var Ve;k("__custom__"),x(!0);const le=nn(e.platform,rn(T.trim(),he,je,e.defaultWorkspacePath,(Ve=m.find(lt=>lt.id===f))==null?void 0:Ve.path,m.map(lt=>lt.path)));Q(le)},[T,f,Q,je,he,e.platform,m]),He=o.useCallback(le=>{if(le!=null&&le.workspaceId){k(le.workspaceId),d("");return}if(le!=null&&le.workspacePath){k("__custom__"),d(le.workspacePath);return}k(""),d("")},[]),De=o.useCallback(le=>{if(k(le),le==="__custom__"){ke();return}d("")},[ke]),Ge=o.useCallback(le=>{k("__custom__"),d(le)},[]),Qe=o.useCallback((le,Ve)=>{M.current=Ve,R.current=le.selectedWorkspaceKey||"__home__",U(le.selectedWorkspaceKey||"__home__"),A(le.initialArgs||""),$(le.initialModel||""),X(""),Le([]);const lt=le.providerType?`${e.id}:${le.providerType}`:null;if(Wu(me.current,lt)){const Je=yt();Ie(Je.textQuery),ue(Je.workspaceQuery),xe(Je.modelQuery),F(Je.resumableOnly),se(Je.sortMode)}me.current=lt,O(le),le.providerType&&i&&(J(!0),i(le.providerType).then(Je=>Le(Je||[])).catch(Je=>console.warn("Failed to load saved sessions",Je)).finally(()=>J(!1)))},[i,e.id]),Ze=o.useMemo(()=>Ei(we,{textQuery:ce,workspaceQuery:te,modelQuery:ae,resumableOnly:oe,sortMode:be}),[ae,oe,we,be,ce,te]);o.useEffect(()=>{W&&(Ze.some(le=>le.providerSessionId===W)||X(""))},[Ze,W]);const ut=o.useCallback(()=>{M.current&&(ne(!0),M.current().finally(()=>{M.current=null,ne(!1),O(null)}))},[]),qe=o.useCallback(()=>{M.current=null,O(null)},[]),ht=o.useCallback(le=>{R.current=le,U(le)},[]);return o.useEffect(()=>{var le;ge.current!==e.id&&(ge.current=e.id,k(f||((le=m[0])==null?void 0:le.id)||"__custom__"),d(""),v(""),C([]),j(""),x(!1),Ie(yt().textQuery),ue(yt().workspaceQuery),xe(yt().modelQuery),F(yt().resumableOnly),se(yt().sortMode),me.current=null,I(Cn(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,m]),o.useEffect(()=>{var le;w!=="__custom__"&&(w&&m.some(Ve=>Ve.id===w)||k(f||((le=m[0])==null?void 0:le.id)||"__custom__"))},[f,w,m]),o.useEffect(()=>{K==="ide"&&p||K==="cli"&&s.length>0||K==="acp"&&r.length>0||I(Cn(p,s.length,r.length))},[K,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:f,workspaceChoice:w,customWorkspacePath:T,browseCurrentPath:b,browseDirectories:h,browseBusy:P,browseError:S,browseDialogOpen:g,activeLauncherKind:K,launchConfirm:L,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:N,launchConfirmArgs:G,launchConfirmModel:D,launchConfirmResumeId:W,launchConfirmSavedSessions:we,launchConfirmTextFilter:ce,launchConfirmWorkspaceFilter:te,launchConfirmModelFilter:ae,launchConfirmResumableOnly:oe,launchConfirmSortMode:be,filteredLaunchConfirmSavedSessions:Ze,launchConfirmSessionsLoading:pe,launchConfirmBusy:de,resolvedWorkspacePath:E,canCreateMissingWorkspace:ye,openBrowseDialog:ke,loadBrowsePath:Q,handleWorkspaceChoiceChange:De,chooseCustomWorkspacePath:Ge,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:I,openLaunchConfirm:Qe,handleConfirmLaunch:ut,closeLaunchConfirm:qe,setWorkspaceSelectionFromOption:He,setLaunchConfirmWorkspaceKeyAndSync:ht,setLaunchConfirmArgs:A,setLaunchConfirmModel:$,setLaunchConfirmResumeId:X,setLaunchConfirmTextFilter:Ie,setLaunchConfirmWorkspaceFilter:ue,setLaunchConfirmModelFilter:xe,setLaunchConfirmResumableOnly:F,setLaunchConfirmSortMode:se}}function Xp({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:p,showBottomNav:m,onBack:f,onSectionChange:w,onOpenConversation:k,onOpenRecent:T,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:v,onAddWorkspace:h,onBrowseDirectory:C,onLaunchWorkspaceProvider:P,onListSavedSessions:y}){const S=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",j=r.slice(0,4),g=s.slice(0,3),x=Yp({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:y}),K=o.useMemo(()=>j.map(N=>{const{metaText:U,updatedLabel:G}=pc(N);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:U,updatedLabel:G,onClick:()=>{const{options:A,selectedKey:D}=ps({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:N.workspace});x.openLaunchConfirm({title:N.kind==="ide"?ls("restart-ide",N.label):N.providerSessionId?ga(N.label):ls("start-fresh",N.label),description:N.kind==="ide"?ds("restart-ide"):N.providerSessionId?ya():ds("start-fresh"),confirmLabel:N.kind==="ide"?$s("restart-ide"):N.providerSessionId?Fr(!0):$s("start-fresh"),busyLabel:N.kind==="ide"?Es("restart-ide"):N.providerSessionId?xa(!0):Es("start-fresh"),workspaceOptions:A,selectedWorkspaceKey:D,details:[{label:"Mode",value:S(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const $=A.find(W=>W.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption($),await T({...N,workspace:($==null?void 0:$.workspacePath)??null})})}}}),[x,T,j]),I=o.useMemo(()=>g.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:ct(N.conversation),secondary:_u(N.conversation,{timestampLabel:N.timestamp?ci(N.timestamp):null}),unread:N.unread,onClick:()=>k(N.conversation)})),[k,g]),M=x.showAllRecent?K:K.slice(0,4),L=K.length>0,O=I.length>0,R=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${R} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:f,type:"button","aria-label":"Back",children:t.jsx(ra,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:At(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[O&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:I.map(N=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${N.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:N.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:N.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))})]}),L&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(N=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:N.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:N.primary}),N.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:N.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))}),K.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>x.setShowAllRecent(N=>!N),children:x.showAllRecent?"Show fewer":`Show ${K.length-4} more`})})]}),(x.hasIdeOptions||n.length>0||a.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:x.workspaceChoice,onChange:N=>x.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:x.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[x.workspaceRows.map(N=>t.jsxs("option",{value:N.id,children:[N.id===x.defaultWorkspaceId?"⭐ ":"",tn(N.path,N.label)||N.path]},N.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),x.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Ms,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:x.resolvedWorkspacePath||x.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:x.openBrowseDialog,children:"Select workspace…"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{x.resolvedWorkspacePath&&h(x.resolvedWorkspacePath)},disabled:!x.resolvedWorkspacePath||x.browseBusy,children:"Save as workspace"})]})]}),x.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[x.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>x.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>x.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>x.setActiveLauncherKind("acp"),children:"ACP"})]}),x.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:x.activeLauncherKind==="ide"?"Choose an IDE":x.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:x.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(N=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:U,selectedKey:G}=ps({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${N.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:U,selectedWorkspaceKey:G,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:N.name}]},async()=>{const A=U.find(D=>D.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(A),v(N.type,{workspacePath:(A==null?void 0:A.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:N.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},N.type)):(x.activeLauncherKind==="cli"?n:a).map(N=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const U=x.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:A}=ps({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${N.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${U.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:A,details:[{label:"Mode",value:U.toUpperCase()},{label:"Provider",value:N.displayName}],showArgsInput:!0,showModelInput:U==="acp",initialArgs:"",initialModel:"",providerType:N.type},async()=>{const D=G.find($=>$.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),P(U,N.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:x.launchConfirmArgs,model:x.launchConfirmModel,resumeSessionId:x.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[N.icon?`${N.icon} `:"",N.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},N.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,x.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>h(x.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:b,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:d,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),x.browseDialogOpen&&t.jsx(on,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:x.browseCurrentPath,directories:x.browseDirectories,busy:x.browseBusy,error:x.browseError,confirmLabel:"Use this folder",onClose:()=>x.setBrowseDialogOpen(!1),onNavigate:N=>{x.loadBrowsePath(N)},onConfirm:N=>{x.chooseCustomWorkspacePath(N),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx(Aa,{title:x.launchConfirm.title,description:x.launchConfirm.description,details:x.launchConfirm.details,workspaceOptions:x.launchConfirm.workspaceOptions,selectedWorkspaceKey:x.launchConfirmWorkspaceKey,onWorkspaceChange:x.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:x.launchConfirm.providerType?Fr(!!x.launchConfirmResumeId):x.launchConfirm.confirmLabel,busyLabel:x.launchConfirm.providerType?void 0:x.launchConfirm.busyLabel,busy:x.launchConfirmBusy,showArgsInput:x.launchConfirm.showArgsInput,argsValue:x.launchConfirmArgs,onArgsChange:x.setLaunchConfirmArgs,showModelInput:x.launchConfirm.showModelInput,modelValue:x.launchConfirmModel,onModelChange:x.setLaunchConfirmModel,historyProviderNode:x.launchConfirm.providerType&&(x.launchConfirmSessionsLoading||x.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),x.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:ba()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:N=>x.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:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmWorkspaceFilter,onChange:N=>x.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:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmModelFilter,onChange:N=>x.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:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsxs("select",{value:x.launchConfirmSortMode,onChange:N=>x.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:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:x.launchConfirmResumableOnly,onChange:N=>x.setLaunchConfirmResumableOnly(N.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:N=>x.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:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:Uu()}),x.filteredLaunchConfirmSavedSessions.map(N=>t.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":"(workspace missing)"]},N.providerSessionId))]}),!x.launchConfirmSessionsLoading&&x.launchConfirmSavedSessions.length>0&&x.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),x.launchConfirmResumeId&&(()=>{const N=x.filteredLaunchConfirmSavedSessions.find(G=>G.providerSessionId===x.launchConfirmResumeId);if(!N)return null;const U=mc(N);return t.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:U.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:U.providerSessionId}),t.jsx("div",{className:"mt-1",children:U.metaLine}),U.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:U.updatedLabel}),U.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:U.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),m&&t.jsx(uc,{section:p,onSectionChange:w})]})}function fc(e){var r;const s=((r=e.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function Qp(e,s){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:xs(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,p,m;const a=nr(n)?"cli":Cs(n)?"acp":"ide",i=xs(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(nr(n)?n.cliName||n.type:Cs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Cs(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((m=(p=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:p.call(u,-1))==null?void 0:m.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Jp(e,s){const r=new Map;for(const n of s){const a=Jt(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((f,w)=>w.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=On(n),u=a.filter(f=>f.unread||f.requiresAction).length,p=fc(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:At(n,{fallbackId:n.id}),subtitle:m.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?Ru(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 Nr(e,s){var r;if(!(typeof window>"u"))try{if(!(!!((r=import.meta.env)!=null&&r.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,s)}catch{}}function Zp({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:m,onRequestedMachineConsumed:f,requestedMobileSection:w,onRequestedMobileSectionConsumed:k,setSelectedTabKey:T,setScreen:d,setSelectedMachineId:b,setSection:v,setMachineBackTarget:h,resetMachineAction:C,markNotificationTargetRead:P}){const y=o.useRef(null),S=o.useCallback(j=>{if(!(j!=null&&j.sessionId))return;const g=Or(j,c),x=Math.max(Date.now(),os(j),g.lastUpdated||0);Nr("mark_read:start",{tabKey:j.tabKey,sessionId:j.sessionId,displayPrimary:ct(j),inboxBucket:g.inboxBucket,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,activityAt:os(j),readAt:x}),P({sessionId:j.sessionId,providerSessionId:j.providerSessionId,tabKey:j.tabKey,routeId:j.routeId}),l(Jt(j)||j.routeId,"mark_session_seen",{sessionId:j.sessionId,seenAt:x}).then(K=>{Nr("mark_read:result",{tabKey:j.tabKey,sessionId:j.sessionId,result:K})}).catch(K=>{Nr("mark_read:error",{tabKey:j.tabKey,sessionId:j.sessionId,error:K instanceof Error?K.message:String(K)})})},[c,l]);return o.useEffect(()=>{var g;if(!n){d("inbox"),T(((g=e[0])==null?void 0:g.tabKey)||null),y.current=null;return}if(i!=="chat"){y.current=null;return}const j=`${n.tabKey}:${n.sessionId||""}`;y.current!==j&&(y.current=j,S(n))},[e,S,i,n,d,T]),o.useEffect(()=>{if(!u)return;const j=e.find(g=>g.tabKey===u);j&&(T(j.tabKey),d("chat"),p==null||p())},[e,p,u,d,T]),o.useEffect(()=>{if(!m)return;const j=s.find(g=>g.id===m);j&&(b(j.id),C(),v("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,m,C,h,d,v,b]),o.useEffect(()=>{w&&(v(w),d("inbox"),k==null||k())},[k,w,d,v]),o.useEffect(()=>{const j=r.filter(g=>g.inboxBucket==="task_complete"||g.unread);j.length!==0&&Nr("inbox_state",{screen:i,selectedTabKey:a,items:j.map(g=>{const x=Or(g.conversation,c);return{liveState:x,tabKey:g.conversation.tabKey,sessionId:g.conversation.sessionId,displayPrimary:ct(g.conversation),serverBucket:x.inboxBucket,computedBucket:g.inboxBucket,serverUnread:x.unread,computedUnread:g.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:os(g.conversation)}})})},[r,c,i,a]),{markConversationRead:S}}function ef(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Co(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function tf(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function sf({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,p]=o.useState(null),m=o.useCallback(()=>{i("idle"),l(""),p(null)},[]),f=o.useCallback(async(h,C,P)=>{var y;try{i("loading"),l(`Launching ${C}…`);const S={ideType:C,enableCdp:!0};(y=P==null?void 0:P.workspacePath)!=null&&y.trim()&&(S.workspace=P.workspacePath.trim()),await e(h,"launch_ide",S),i("done"),l(`${C} launch requested`)}catch(S){i("error"),l(S instanceof Error?S.message:"Launch IDE failed"),console.error("Launch IDE failed",S)}},[e]),w=o.useCallback(async(h,C,P)=>{if(C.trim())try{i("loading"),l(P!=null&&P.createIfMissing?"Creating folder…":"Saving workspace…");const y=await e(h,"workspace_add",{path:C.trim(),createIfMissing:(P==null?void 0:P.createIfMissing)===!0});if(y!=null&&y.success){i("done"),l(P!=null&&P.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((y==null?void 0:y.error)||"Could not save workspace")}catch(y){i("error"),l(y instanceof Error?y.message:"Could not save workspace")}},[e]),k=o.useCallback(async h=>{var C,P,y,S,j,g;try{i("loading"),l("Starting daemon upgrade…");const x=await e(h,"daemon_upgrade",{});if((C=x==null?void 0:x.result)!=null&&C.alreadyLatest){i("done"),l(`Already on v${((P=x==null?void 0:x.result)==null?void 0:P.version)||"latest"}.`);return}if((y=x==null?void 0:x.result)!=null&&y.upgraded||(S=x==null?void 0:x.result)!=null&&S.success){i("done"),l(`Upgrade to v${((j=x==null?void 0:x.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((g=x==null?void 0:x.result)==null?void 0:g.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),T=o.useCallback(async(h,C,P,y)=>{var g,x,K;const S=Date.now(),j={machineId:h,kind:C,providerType:P,workspaceId:(y==null?void 0:y.workspaceId)||null,workspacePath:(y==null?void 0:y.workspacePath)||null,resumeSessionId:(y==null?void 0:y.resumeSessionId)||null,startedAt:S};try{i("loading"),l(`Launching ${P}…`),p(j);const I={cliType:P};(g=y==null?void 0:y.workspacePath)!=null&&g.trim()?I.dir=y.workspacePath.trim():y!=null&&y.workspaceId&&(I.workspaceId=y.workspaceId),y!=null&&y.resumeSessionId&&(I.resumeSessionId=y.resumeSessionId),(x=y==null?void 0:y.args)!=null&&x.trim()&&(I.cliArgs=y.args.trim().split(/\s+/).filter(Boolean)),(K=y==null?void 0:y.model)!=null&&K.trim()&&(I.initialModel=y.model.trim());const M=await e(h,"launch_cli",I),L=(M==null?void 0:M.result)||M,O=(L==null?void 0:L.sessionId)||(L==null?void 0:L.id);if(M!=null&&M.success&&O){p(null),i("done"),l(`${P} launched`),s(Xt(O));return}if(M!=null&&M.success){i("loading"),l(`${P} launch requested — waiting for session…`);return}p(null),i("error"),l((M==null?void 0:M.error)||(L==null?void 0:L.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(I){if(tf(I)){i("loading"),l(`${P} launch requested — waiting for session…`);return}p(null),i("error"),l(I instanceof Error?I.message:`Could not launch ${C.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(h,C)=>{try{const P=await e(h,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),y=(P==null?void 0:P.result)??P;return Array.isArray(y==null?void 0:y.sessions)?y.sessions:[]}catch(P){return console.error("Failed to list saved sessions on mobile:",P),[]}},[e]),b=o.useCallback(async(h,C)=>an(e,h,C),[e]);o.useEffect(()=>{if(!u)return;const h=Co(u.workspacePath),C=r.find(y=>{var I,M,L,O;if(!y||y.type==="adhdev-daemon"||ef(y.daemonId||y.id)!==u.machineId||(y.transport==="acp"?"acp":y.transport==="pty"?"cli":null)!==u.kind||String(y.agentType||y.type||"")!==u.providerType)return!1;const x=String(y.providerSessionId||"");if(u.resumeSessionId&&x)return x===u.resumeSessionId;if(h){const R=Co(y.workspace||y.runtimeWorkspaceLabel);return R?R===h:!1}return Number(y.lastUpdated||y._lastUpdate||y.timestamp||((O=(L=(M=(I=y.activeChat)==null?void 0:I.messages)==null?void 0:M.at)==null?void 0:L.call(M,-1))==null?void 0:O.timestamp)||0)>=u.startedAt-5e3});if(!C)return;const P=Si({entrySessionId:C.sessionId,entryInstanceId:C.instanceId,entryRouteId:C.id,conversations:n});P&&(p(null),i("done"),l(`${u.providerType} launched`),s(Xt(P)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{p(C=>!C||C.startedAt!==u.startedAt?C:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[u]);const v=o.useCallback(async(h,C)=>{if(C.kind==="ide"&&C.providerType){await f(h,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await T(h,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[f,T]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:w,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:T,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:v}}function rf({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const m=o.useCallback(v=>{i(v.tabKey),c("chat"),n(v)},[n,c,i]),f=o.useCallback(v=>{const h=e.find(C=>C.routeId===v.routeId&&C.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),w=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),k=o.useCallback((v,h="inbox")=>{l(v),a(),u("machines"),p(h),c("machine")},[a,p,c,u,l]),T=o.useCallback(v=>{const h=Jt(v);h&&k(h,"chat")},[k]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),b=o.useCallback(v=>{u(v),c("inbox")},[c,u]);return{openConversation:m,openNativeConversation:f,backFromConversation:w,openMachine:k,openConversationMachine:T,backFromMachine:d,changeMachineSection:b}}function nf(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function af(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function Cr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function of({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:w,requestedMobileSection:k,onRequestedMobileSectionConsumed:T,onOpenHistory:d,onOpenRemote:b,onStopCli:v,wsStatus:h,isConnected:C,onShowHiddenConversation:P,onShowAllHiddenConversations:y,onHideConversation:S,onOpenNewSession:j,notificationStateBySessionId:g,onMarkNotificationTargetRead:x}){const[K,I]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[M,L]=o.useState(()=>e[0]?"chat":"inbox"),[O,R]=o.useState("chats"),[N,U]=o.useState(null),[G,A]=o.useState("inbox"),D=Ks(),$="0.8.72",W=o.useMemo(()=>e.find(Q=>Q.tabKey===K)||e[0]||null,[e,K]),X=o.useMemo(()=>W?r.find(Q=>Q.id===W.routeId):void 0,[r,W]),we=o.useMemo(()=>!W||Xe(W)||!et(W)?null:Rs(W),[W]),Le=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(da),[r]),ce=o.useMemo(()=>Le.find(Q=>Q.id===N)||null,[Le,N]),Ie=o.useMemo(()=>en(r),[r]),te=sn({sendDaemonCommand:a,activeConv:W||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),ue=sf({sendDaemonCommand:a,navigate:D,ides:r,conversations:e}),ae=o.useMemo(()=>e.map(Q=>{const ke=M==="chat"&&(W==null?void 0:W.tabKey)===Q.tabKey,He=la(Q,Ie,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ke,notificationStateBySessionId:g}),De=os(Q),Ge=Ri(Q);return{conversation:Q,timestamp:De,preview:Ge,unread:He.unread,requiresAction:He.requiresAction,isWorking:He.isWorking,inboxBucket:He.inboxBucket}}),[e,Ie,g,M,W]),{markConversationRead:xe}=Zp({conversations:e,machineEntries:Le,items:ae,selectedConversation:W,selectedTabKey:K,screen:M,liveSessionInboxState:Ie,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:w,requestedMobileSection:k,onRequestedMobileSectionConsumed:T,setSelectedTabKey:I,setScreen:L,setSelectedMachineId:U,setSection:R,setMachineBackTarget:A,resetMachineAction:ue.resetMachineAction,markNotificationTargetRead:x}),oe=rf({conversations:e,selectedConversation:W,machineBackTarget:G,markConversationRead:xe,resetMachineAction:ue.resetMachineAction,setSelectedTabKey:I,setScreen:L,setSelectedMachineId:U,setSection:R,setMachineBackTarget:A}),F=o.useMemo(()=>Cr(ae.filter(Q=>Q.requiresAction)),[ae]),be=o.useMemo(()=>Cr(ae.filter(Q=>Q.unread&&!Q.requiresAction)),[ae]),se=o.useMemo(()=>Cr(ae.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking)),[ae]),pe=o.useMemo(()=>Cr(ae.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[ae]),J=o.useMemo(()=>ce?ae.filter(Q=>Jt(Q.conversation)===ce.id):[],[ae,ce]),de=o.useMemo(()=>Qp(ce,r),[r,ce]),ne=(ce==null?void 0:ce.version)||null,ge=!!ce&&!!ne&&!0&&ne!==$,me=o.useMemo(()=>(ce==null?void 0:ce.availableProviders)||[],[ce]),E=o.useMemo(()=>me.filter(Q=>Q.category==="cli"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[me]),ye=o.useMemo(()=>me.filter(Q=>Q.category==="acp"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[me]),he=o.useMemo(()=>Jp(Le,ae),[ae,Le]),je=o.useCallback(async Q=>{ce&&await ue.handleOpenRecent(ce.id,Q)},[ue,ce]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&W?t.jsx(Bp,{selectedConversation:W,isAcp:Xe(W),isStandalone:l,selectedIdeEntry:X,actionLogs:n,userName:u,isSendingChat:te.isSendingChat,isFocusingAgent:te.isFocusingAgent,handleModalButton:te.handleModalButton,handleRelaunch:te.handleRelaunch,onBack:oe.backFromConversation,onOpenNativeConversation:oe.openNativeConversation,onOpenMachine:oe.openConversationMachine,onHideConversation:S,onOpenHistory:d,onOpenRemote:b,onStopCli:v,cliViewMode:we,onSetCliViewMode:async Q=>{if(W&&we!==Q)try{await a(Jt(W)||W.routeId,"set_cli_view_mode",{targetSessionId:W.sessionId,cliType:$t(W),mode:Q})}catch(ke){af(ke)?console.warn("Skipped CLI view mode switch:",ke instanceof Error?ke.message:String(ke)):console.error("Failed to switch CLI view mode:",ke)}},handleSendChat:te.handleSendChat,handleFocusAgent:te.handleFocusAgent}):M==="machine"&&ce?t.jsx(Xp,{selectedMachineEntry:ce,selectedMachineConversations:J,selectedMachineRecentLaunches:de,cliProviders:E,acpProviders:ye,selectedMachineNeedsUpgrade:ge,appVersion:$,machineAction:ue.machineAction,isStandalone:l,section:O,showBottomNav:G==="inbox",onBack:oe.backFromMachine,onSectionChange:oe.changeMachineSection,onOpenConversation:oe.openConversation,onOpenRecent:je,onOpenMachineDetails:()=>D(`/machines/${ce.id}`),onMachineUpgrade:()=>ue.handleMachineUpgrade(ce.id),onLaunchDetectedIde:(Q,ke)=>ue.handleLaunchDetectedIde(ce.id,Q,ke),onAddWorkspace:(Q,ke)=>ue.handleAddWorkspace(ce.id,Q,ke),onBrowseDirectory:Q=>ue.handleBrowseDirectory(ce.id,Q),onLaunchWorkspaceProvider:(Q,ke,He)=>ue.handleLaunchWorkspaceProvider(ce.id,Q,ke,He),onListSavedSessions:Q=>ue.handleListSavedSessions(ce.id,Q)}):t.jsx(Op,{section:O,attentionItems:F,unreadItems:be,workingItems:se,completedItems:pe,hiddenConversations:s,machineCards:he,getAvatarText:nf,onOpenConversation:oe.openConversation,onShowConversation:P,onShowAllHidden:y,onOpenNewSession:j,onOpenMachine:oe.openMachine,onOpenSettings:()=>D("/settings"),onSectionChange:R,wsStatus:h,isConnected:C,isStandalone:l})})}function In(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function cf({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useCallback(()=>{c.current=0,u(!1),m(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const w=o.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),k=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!In(s,r)){m("merge");return}const v=b.currentTarget.getBoundingClientRect(),h=b.clientX-v.left,C=v.width/3;h<C?m("split-left"):h>C*2?m("split-right"):m("merge")},[s,r]),T=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),m(null))},[]),d=o.useCallback(b=>{c.current=0,u(!1);const v=b.dataTransfer.getData("text/tab-key"),h=v?e.some(P=>P.tabKey===v):!1,C=p;if(m(null),i(),!!v){if(b.preventDefault(),C==="split-left"&&In(s,r)){r==null||r(v,"split-left");return}if(C==="split-right"&&In(s,r)){r==null||r(v,"split-right");return}if(h){a(v);return}n==null||n(v)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:f,handleDragEnter:w,handleDragOver:k,handleDragLeave:T,handleDrop:d}}function lf(e,s){const r=new Set(s.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=s.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function df({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[p,m]=o.useState(null),f=o.useRef(null),w=o.useRef(null),k=o.useRef(n),T=o.useRef(a);o.useEffect(()=>{k.current=n},[n]),o.useEffect(()=>{T.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(j=>{const g=lf(j,e);return g.length===j.length&&g.every((x,K)=>x===j[K])?j:g})},[e]);const d=o.useMemo(()=>{const j=p??l;if(j.length===0)return e;const g=new Map(j.map((x,K)=>[x,K]));return[...e].sort((x,K)=>{const I=g.get(x.tabKey)??999,M=g.get(K.tabKey)??999;return I-M})},[e,p,l]);o.useEffect(()=>{var g,x;if(d.length===0){i!==null&&(c(null),(g=k.current)==null||g.call(k,null));return}if(i&&d.some(K=>K.tabKey===i))return;const j=d[0].tabKey;j!==i&&(c(j),(x=k.current)==null||x.call(k,j))},[d,i]);const b=o.useMemo(()=>d.find(j=>j.tabKey===i),[d,i]),v=o.useCallback(j=>{var g;c(j),(g=k.current)==null||g.call(k,j)},[]),h=o.useCallback((j,g,x)=>{u(K=>{var O;const I=K.filter(R=>R!==j),M=I.indexOf(g);if(M<0)return K;const L=x==="left"?M:M+1;return I.splice(L,0,j),(O=T.current)==null||O.call(T,I),I}),m(null)},[]),C=o.useCallback((j,g,x)=>{const I=(l.length>0?l:e.map(O=>O.tabKey)).filter(O=>O!==j),M=I.indexOf(g);if(M<0)return;const L=x==="left"?M:M+1;I.splice(L,0,j),f.current=I,m(I)},[l,e]),P=o.useCallback(()=>{var g;const j=f.current;j&&(u(j),(g=T.current)==null||g.call(T,j))},[]),y=o.useCallback(()=>{f.current=null,m(null)},[]),S=o.useCallback(j=>{u(g=>{var K;const x=g.filter(I=>I!==j);return x.push(j),(K=T.current)==null||K.call(T,x),x})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:f,draggingTabRef:w,selectTab:v,handleTabReorder:h,updatePreviewOrder:C,commitPreviewOrder:P,clearPreviewOrder:y,moveTabToEnd:S,setDraggingTabKey:j=>{w.current=j}}}function uf({dropAction:e,canSplit:s}){return t.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[t.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:s?1:.45},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),t.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),t.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:s?1:.45},children:t.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function Ta({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1}){if(a)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const i=!r&&!n,c=r?"Waiting for your daemon":n?"No conversations yet":"Connect your machines",l=r?"Start the ADHDev daemon to connect this dashboard. Once it is online, you can open an IDE or launch CLI and ACP sessions.":n?"Your machines are connected. Open a machine, choose a workspace, then launch an IDE, CLI, or ACP session.":"Install ADHDev on a machine, sign in, and it will show up here.";return e===0&&!s?t.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[t.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),t.jsxs("div",{className:"text-center max-w-lg",children:[t.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:c}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:l}),i&&t.jsx(dc,{}),i&&t.jsx("div",{className:"mt-8",children:t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):t.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const hc="adhdev-tab-shortcuts";function xc(){try{return JSON.parse(localStorage.getItem(hc)||"{}")}catch{return{}}}function bc({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>xc()),[l,u]=o.useState(null),p=o.useCallback(f=>{const w=[];return f.metaKey&&w.push(a?"⌘":"Meta"),f.ctrlKey&&w.push("Ctrl"),f.altKey&&w.push(a?"⌥":"Alt"),f.shiftKey&&w.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(w.push(f.key.length===1?f.key.toUpperCase():f.key),w.join("+"))},[a]),m=o.useCallback(f=>{c(f);try{localStorage.setItem(hc,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=w=>{if(w.preventDefault(),w.stopPropagation(),w.key==="Escape"){u(null);return}const k=p(w);if(!k)return;const T={...i};for(const[d,b]of Object.entries(T))b===k&&delete T[d];T[l]=k,m(T),u(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,m,p]),o.useEffect(()=>{if(!e)return;const f=w=>{if(!(!w.ctrlKey&&!w.metaKey&&!w.altKey)){for(const[k,T]of Object.entries(i))if(s.includes(k)&&p(w)===T){w.preventDefault(),r(),n(k);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:m}}const mf=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:p,onConversationActivated:m,onPreviewReorder:f,onReorderTab:w,onCommitPreviewOrder:k,onClearPreviewOrder:T,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:v,onOpenContextMenu:h,longPressTimer:C,isGroupActive:P}){const y=Ws(s),S=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",j=y.isReconnecting,g=o.useCallback(U=>{l.current=s.tabKey,b(s.tabKey),U.dataTransfer.setData("text/tab-key",s.tabKey),U.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),x=o.useCallback(()=>{l.current=null,b(null),k(),T(),d()},[l,b,k,T,d]),K=o.useCallback(U=>{const G=l.current;if(!(!G||G===s.tabKey)&&U.dataTransfer.types.includes("text/tab-key")){U.preventDefault(),U.stopPropagation();const A=U.currentTarget.getBoundingClientRect(),D=U.clientX<A.left+A.width/2?"left":"right";f(G,s.tabKey,D)}},[s.tabKey,l,f]),I=o.useCallback(U=>{U.preventDefault(),U.stopPropagation();const G=U.dataTransfer.getData("text/tab-key");if(G&&G!==s.tabKey){const A=U.currentTarget.getBoundingClientRect(),D=U.clientX<A.left+A.width/2?"left":"right";c.includes(G)?w(G,s.tabKey,D):v&&v(G)}T()},[s.tabKey,c,w,v,T]),M=o.useCallback(U=>{U.stopPropagation(),u(),p(s.tabKey),m(s)},[s,m,u,p]),L=o.useCallback(U=>{U.preventDefault(),h(U.clientX,U.clientY,s.tabKey)},[s.tabKey,h]),O=o.useCallback(U=>{const G=U.touches[0];C.current=setTimeout(()=>{h(G.clientX,G.clientY,s.tabKey)},600)},[s.tabKey,C,h]),R=o.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),N=["adhdev-dockview-tab",S,r&&"is-active",P&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:N,draggable:!0,onDragStart:g,onDragEnd:x,onDragOver:K,onDrop:I,onClick:M,onContextMenu:L,onTouchStart:O,onTouchEnd:R,onTouchMove:R,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?t.jsx("div",{className:"tab-spinner"}):y.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:ct(s),children:ct(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:cs(s)}):y.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[cs(s),t.jsx("span",{className:"connecting-dots"})]}):cs(s)})]}),i&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function pf({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:w,onDragTabKeyChange:k,onReceiveTab:T,onHideTab:d,isGroupActive:b,allowTabShortcuts:v=!0}){const[h,C]=o.useState(null),P=o.useRef(null),y=o.useRef(null),S=o.useMemo(()=>e.map(L=>L.tabKey),[e]);or("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:j,tabShortcuts:g,shortcutListening:x,setShortcutListening:K,saveShortcuts:I}=bc({enabled:v,sortedTabKeys:e.map(L=>L.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const L=O=>{const R=document.querySelector("[data-pane-context-menu]");R&&R.contains(O.target)||C(null)};return window.addEventListener("mousedown",L,!0),()=>window.removeEventListener("mousedown",L,!0)},[h]),o.useEffect(()=>{const L=y.current;if(!L)return;const O=R=>{Math.abs(R.deltaY)<=Math.abs(R.deltaX)||(R.preventDefault(),L.scrollLeft+=R.deltaY)};return L.addEventListener("wheel",O,{passive:!1}),()=>L.removeEventListener("wheel",O)},[]);const M=o.useCallback((L,O,R)=>{C({x:L,y:O,tabKey:R})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:y,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(L=>t.jsx(mf,{conv:L,isActive:s===L.tabKey,isDraggedTab:a.current===L.tabKey,isTaskCompleteUnread:n.has(L.tabKey),shortcut:v?g[L.tabKey]:void 0,conversationKeys:S,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:w,onDragTabKeyChange:k,onReceiveTab:T,onOpenContextMenu:M,longPressTimer:P,isGroupActive:b},L.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&t.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:h.x,top:h.y},children:[v&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onClick:L=>{L.stopPropagation(),K(h.tabKey),C(null)},children:["⌨ ",g[h.tabKey]?`Change shortcut (${g[h.tabKey]})`:"Set shortcut"]}),g[h.tabKey]&&t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const L={...g};delete L[h.tabKey],I(L),C(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[v&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onClick:()=>{d(h.tabKey),C(null)},children:"🚫 Hide from Dashboard"})]})]}),v&&x&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>K(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:L=>L.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function ff({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:p,groupIndex:m,onFocus:f,isSplitMode:w,numGroups:k,onMoveTab:T,onReceiveTab:d,style:b,onActiveTabChange:v,initialActiveTabId:h,initialTabOrder:C,onTabOrderChange:P,onHideTab:y,isFocused:S,allowTabShortcuts:j=!0}){const{sendCommand:g}=Mt(),x=o.useRef(null),{activeTabId:K,activeConv:I,sortedConversations:M,draggingTabRef:L,selectTab:O,handleTabReorder:R,updatePreviewOrder:N,commitPreviewOrder:U,clearPreviewOrder:G,moveTabToEnd:A,setDraggingTabKey:D}=df({conversations:e,initialActiveTabId:h,initialTabOrder:C,onActiveTabChange:v,onTabOrderChange:P}),$=sn({sendDaemonCommand:a,activeConv:I,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:W,dropAction:X,resetDragState:we,handleDragEnter:Le,handleDragOver:ce,handleDragLeave:Ie,handleDrop:te}=cf({conversations:e,numGroups:k,onMoveTab:T,onReceiveTab:d,onOwnTabDrop:A,onClearPreviewOrder:G}),ue=I&&!Xe(I)&&Rs(I)==="terminal",ae=o.useMemo(()=>I?s.find(se=>se.id===I.routeId):void 0,[s,I]),xe=o.useMemo(()=>I?n.filter(se=>se.routeId===I.tabKey):[],[n,I]),oe=o.useMemo(()=>en(s),[s]),F=o.useMemo(()=>new Set(M.filter(se=>id(se,oe,{isOpenConversation:se.tabKey===K})).map(se=>se.tabKey)),[K,oe,M]);or("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:K,dragOver:W});const be=o.useCallback(se=>{se.streamSource==="agent-stream"&&se.agentType&&g(se.routeId,lc(),{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.sessionId}}).catch(()=>{})},[g]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...b,outline:W?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(pf,{conversations:M,activeTabId:K,groupIndex:m,numGroups:k,unreadTabKeys:F,draggingTabRef:L,onFocus:f,onSelectTab:O,onConversationActivated:be,onPreviewReorder:N,onReorderTab:R,onCommitPreviewOrder:U,onClearPreviewOrder:G,onDragStateReset:we,onDragTabKeyChange:D,onMoveTab:T,onReceiveTab:d,onHideTab:y,isGroupActive:S??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Le,onDragOver:ce,onDragLeave:Ie,onDrop:te,children:[W&&t.jsx(uf,{dropAction:X,canSplit:!!(k<4&&T)}),I?t.jsx(Ia,{activeConv:I,clearToken:r[I.tabKey]||0,isCliTerminal:!!ue,ideEntry:ae,terminalRef:x,handleModalButton:$.handleModalButton,handleRelaunch:$.handleRelaunch,handleSendChat:$.handleSendChat,isSendingChat:$.isSendingChat,handleFocusAgent:$.handleFocusAgent,isFocusingAgent:$.isFocusingAgent,actionLogs:xe,userName:p,isInputActive:!w||!!S}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(Ta,{conversationsCount:e.length,isSplitMode:w,isStandalone:l,hasRegisteredMachines:u})})]})]})}function hf({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:w,userName:k,focusedGroup:T,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:v,closeGroup:h,handleResizeStart:C,groupActiveTabIds:P,setGroupActiveTabIds:y,groupTabOrders:S,setGroupTabOrders:j,toggleHiddenTab:g,allowTabShortcuts:x=!0}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((K,I)=>{const M=s&&n.length===r?`${n[I]}%`:void 0;return t.jsxs(at.Fragment,{children:[s&&I>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:L=>C(I-1,L),onDoubleClick:()=>h(I),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(ff,{style:s?{flexBasis:M??`${100/r}%`,flexGrow:M?0:1,flexShrink:M?0:1}:void 0,conversations:K,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:w,userName:k,groupIndex:I,isFocused:s&&T===I,onFocus:()=>d(I),isSplitMode:s,numGroups:r,onMoveTab:(L,O)=>{O==="left"&&I>0?b(L,I-1):O==="right"&&I<r-1?b(L,I+1):O==="split-left"&&r<4?v(L,I,"left"):O==="split-right"&&r<4&&v(L,I,"right")},onReceiveTab:L=>b(L,I),onActiveTabChange:L=>y(O=>(O[I]??null)===(L??null)?O:{...O,[I]:L}),initialActiveTabId:P[I],initialTabOrder:S[I],onTabOrderChange:L=>j(O=>{const R=O[I]||[];return R.length===L.length&&R.every((N,U)=>N===L[U])?O:{...O,[I]:L}}),onHideTab:g,allowTabShortcuts:x})]},I)})})}function gc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?dt.onScreenshot("ide-page",(m,f)=>{if(m!==e)return;const w=new FileReader;w.onload=()=>i(w.result),w.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var m;return e?((m=dt.onStatus)==null?void 0:m.call(dt,(f,w)=>{f===e&&w!=null&&w.screenshotUsage&&l(w.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?dt.get(e):null;if(!(!p||r!=="connected"))return n!=="chat"&&s?p.startScreenshots(s):p.stopScreenshots(s),()=>{p.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(p,m)=>{const f=e?dt.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(p,m,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const yc="adhdev-dashboard-action-shortcuts",xf=1200,bf={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function gf(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function nt(e,s){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function vc(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:nt("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:nt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:nt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:nt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:nt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:nt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:nt("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:nt("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:nt("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:nt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:nt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:nt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:nt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:nt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:nt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:nt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:nt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:nt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:nt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:nt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:nt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:nt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:nt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:nt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:nt("toggleCliView",e)}]}function Jn(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function qr(e){const s=Object.fromEntries(vc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(yc)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(bf))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function wc(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function yf({enabled:e=!0,onTrigger:s}){const r=gf(),[n,a]=o.useState(()=>qr(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),p=o.useRef({parts:[],timer:null}),m=o.useCallback(d=>{const b=[];return d.metaKey&&b.push(r?"⌘":"Meta"),d.ctrlKey&&b.push("Ctrl"),d.altKey&&b.push(r?"⌥":"Alt"),d.shiftKey&&d.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(d.key)?null:(b.push(wc(d.key)),b.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(yc,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=qr(r),b=Object.entries(n),v=Object.entries(d);b.length===v.length&&b.every(([h,C])=>d[h]===C)||f(d)},[n,r,f]);const w=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),k=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},xf))},[]);o.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),u([]);return}const v=m(b);if(!v)return;const C=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(v);if(l.length===0&&C){u([v]);return}const y=[...l,v].slice(0,2).join(" "),S={...n};for(const[j,g]of Object.entries(S))g===y&&delete S[j];S[i]=y,f(S),c(null),u([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,m,f,i,l]),o.useEffect(()=>{if(!e||i)return;const d=b=>{if(b.defaultPrevented)return;const v=m(b);if(!v)return;const h=b.metaKey||b.ctrlKey||b.altKey;if(Jn(b.target)&&!h)return;const C=p.current.parts,P=h?[v]:[...C.slice(-1),v].slice(-2),y=P.join(" "),S=P[P.length-1],j=Object.entries(n).filter(([,M])=>!!M),g=j.find(([,M])=>M===y);if(g){b.preventDefault(),w(),s(g[0]);return}if(j.some(([,M])=>M.startsWith(`${y} `))){b.preventDefault(),p.current.parts=P,k();return}const K=j.find(([,M])=>M===S);if(K){b.preventDefault(),w(),s(K[0]);return}if(j.some(([,M])=>M.startsWith(`${S} `))){b.preventDefault(),p.current.parts=[S],k();return}w()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,k,e,m,s,w,i]),o.useEffect(()=>()=>w(),[w]);const T=o.useMemo(()=>vc(r),[r]);return{isMac:r,actionDefinitions:T,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:f}}function vf({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):s?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut"}),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 wf(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function Io({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!wf(n):!0}const jc=o.createContext(null);function cn(){const e=o.useContext(jc);if(!e)throw new Error("DashboardDockviewContext missing");return e}function $r(e){return ct(e)||e.tabKey}function jf(e){return`remote:${e}`}function Gt(e){return e.startsWith("remote:")}function Ao(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function An(e){var r,n,a,i,c;const s=e==null?void 0:e.defaultView;if(s)try{s.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(a=e==null?void 0:e.documentElement)==null?void 0:a.focus)==null||i.call(a),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var l,u;try{s.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Ir(e,s){e.classList.remove(Kn.className,Bn.className),e.classList.add(s==="light"?Kn.className:Bn.className)}function To(e){return e?Array.from(new Set(e.groups.map(s=>{var r,n;return(n=(r=s.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(s=>!!s&&s!==window))):[]}function kf(e){const[,s]=o.useState(0);o.useEffect(()=>{const r=()=>s(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function Sf(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const p of l){const m=e.addPanel({id:p.tabKey,component:"conversation",title:$r(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=m.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function Mo(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])Gt(n.id)||r.has(n.id)||e.removePanel(n);for(const n of s){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==$r(n)&&a.api.setTitle($r(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:$r(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 Lo(e,s,r){var u,p;const n=r?jf(r):null;for(const m of[...e.panels])Gt(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Kt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=$i(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((p=e.panels.find(m=>!Gt(m.id)))==null?void 0:p.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function Nf({params:e,api:s}){var f;const r=cn(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=sn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const w=[s.onDidActiveChange(k=>i(k.isActive)),s.onDidActiveGroupChange(k=>{if(!s.isActive&&!k.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const k of w)k.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(w=>w.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(w=>w.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(Ta,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const m=!Xe(c)&&Rs(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(Ia,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:m,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((f=r.scrollToBottomRequest)==null?void 0:f.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function Cf({params:e}){var u;const s=cn(),r=o.useMemo(()=>Kt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>s.ides.find(p=>p.id===e.routeId),[s.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=gc({doId:a,targetSessionId:r?wi(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:t.jsx(ni,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:i,screenshotUsage:c,transportType:r.transport,onAction:l})}):t.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function If(){const e=cn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(Ta,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Af(e){var k,T;kf(e);const s=cn(),r=o.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Kt([...s.conversationsByTabKey.values()],e.params.routeId),b=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,v=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${v?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(d==null?void 0:d.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:d!=null&&d.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:d.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((T=e.api.group.activePanel)==null?void 0:T.id)===e.api.id,i=e.api.isGroupActive,c=la(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,m=c.isWaiting,f=c.unread,w=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:ct(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:d=>{var b;d.preventDefault(),r(d),s.openTabContextMenu({x:d.clientX,y:d.clientY,tabKey:n.tabKey,sourceDocument:((b=d.target)==null?void 0:b.ownerDocument)??document})},children:[f&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:p?t.jsx("div",{className:"tab-spinner"}):m?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:ct(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:cs(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:cs(n)}):t.jsx("span",{children:cs(n)})})]}),w&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function Tf({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:p,userName:m,toggleHiddenTab:f,actionShortcuts:w,registerActionHandlers:k,onActiveTabChange:T,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:v,scrollToBottomRequest:h,notificationStateBySessionId:C}){var Be,Re,ft;const{theme:P}=ja(),{sendCommand:y}=Mt(),S=o.useRef(null),j=o.useRef(null),g=o.useRef(!1),x=o.useRef(!1),K=o.useRef(!1),I=o.useRef(null),M=o.useRef([]),[L,O]=o.useState(null),[R,N]=o.useState(!1),[U,G]=o.useState(!1),[A,D]=o.useState(0),$=o.useRef(null),W=o.useMemo(()=>ac(typeof window<"u"?window.innerWidth:1280),[]),X=o.useRef(typeof window>"u"?{}:lp(W)),we=o.useMemo(()=>new Map(e.map(B=>[B.tabKey,B])),[e]),Le=o.useMemo(()=>en(r),[r]),ce=o.useMemo(()=>{const B=S.current;return B?B.groups.some(H=>{try{const z=H.model.location.type;return z!=="floating"&&z!=="popout"?!1:H.panels.some(V=>we.has(V.id))}catch{return!1}}):!1},[we,A,e]),Ie=o.useCallback(()=>{var B;(B=S.current)==null||B.focus()},[]),te=o.useCallback(B=>{const H=document,z=B.document;for(const Se of H.querySelectorAll('link[rel="stylesheet"]')){const Ue=z.createElement("link");Ue.rel="stylesheet",Ue.href=Se.href,Se.crossOrigin&&(Ue.crossOrigin=Se.crossOrigin),z.head.appendChild(Ue)}for(const Se of H.querySelectorAll("style")){const Ue=z.createElement("style");Ue.textContent=Se.textContent,z.head.appendChild(Ue)}const V=[];for(const Se of H.styleSheets)try{for(const Ue of Se.cssRules)Ue instanceof CSSStyleRule&&(Ue.selectorText===":root"||Ue.selectorText==="html")&&V.push(Ue.cssText)}catch{}if(V.length>0){const Se=z.createElement("style");Se.textContent=V.join(`
|
|
44
|
+
`),z.head.appendChild(Se)}const ee=H.documentElement.getAttribute("data-theme");ee&&z.documentElement.setAttribute("data-theme",ee),z.documentElement.style.colorScheme=ee==="light"?"light":"dark",z.body.className=H.body.className;const ve=H.documentElement.getAttribute("style");ve&&z.documentElement.setAttribute("style",ve);const Ne=z.getElementById("dv-popout-window");Ne instanceof HTMLElement&&(Ne.classList.add("adhdev-dockview"),Ir(Ne,P))},[P]),ue=o.useCallback(()=>{var H;const B=S.current;if(B)for(const z of B.groups)try{const V=(H=z.element)==null?void 0:H.ownerDocument;if(!V||V===document)continue;const ee=V.getElementById("dv-popout-window");ee instanceof HTMLElement&&(ee.classList.add("adhdev-dockview"),Ir(ee,P));const ve=document.documentElement.getAttribute("data-theme");ve&&V.documentElement.setAttribute("data-theme",ve),V.documentElement.style.colorScheme=ve==="light"?"light":"dark",V.body.className=document.body.className;const Ne=document.documentElement.getAttribute("style");Ne?V.documentElement.setAttribute("style",Ne):V.documentElement.removeAttribute("style")}catch{}},[P]),ae=o.useCallback(()=>{var H;const B=S.current;if(B)for(const z of B.groups)try{const V=(H=z.element)==null?void 0:H.ownerDocument;if(!V||V===document)continue;const ee=V.getElementById("dv-popout-window");if(!(ee instanceof HTMLElement))continue;ee.classList.add("adhdev-dockview"),Ir(ee,P),ee.classList.toggle("is-showing-dockview-overlay",U),ee.classList.toggle("is-dragging-dockview",R)}catch{}},[R,U,P]),xe=o.useCallback(B=>{const H=S.current;if(!H)return;const z=H.getPanel(B);z&&H.addPopoutGroup(z,{popoutUrl:"/popout.html",onDidOpen:({window:V})=>{te(V),ge();const ee=we.get(B);V.document.title=ee?`${ct(ee)} — ADHDev`:"ADHDev — Popout"}})},[we,te]),oe=o.useCallback(B=>{const H=S.current,z=H==null?void 0:H.getPanel(B);if(!H||!z)return;const V=H.groups.filter(ee=>{var ve;try{return((ve=ee.element)==null?void 0:ve.ownerDocument)===document}catch{return!0}});V.length>0?z.api.moveTo({group:V[0],position:"center"}):z.api.moveTo({position:"center"}),z.api.setActive()},[]),F=o.useCallback(B=>{var V;const H=S.current;if(!H)return!1;const z=H.getPanel(B);if(!z)return!1;try{return((V=z.group.element)==null?void 0:V.ownerDocument)!==document}catch{return!1}},[]),be=o.useCallback(B=>{F(B)&&oe(B),f(B)},[F,oe,f]),se=o.useCallback(B=>{const H=S.current,z=H==null?void 0:H.getPanel(B);!H||!z||H.addFloatingGroup(z,{width:600,height:500})},[]),pe=o.useCallback(B=>{var z;const H=(z=S.current)==null?void 0:z.getPanel(B);if(!H)return!1;try{return H.group.model.location.type==="floating"}catch{return!1}},[]),J=o.useCallback(()=>{var H,z;const B=(z=(H=S.current)==null?void 0:H.activePanel)==null?void 0:z.id;return!B||Gt(B)?null:we.has(B)?B:null},[we]),de=o.useCallback(B=>{const H=S.current,z=H==null?void 0:H.getPanel(B);if(!H||!z)return;const V=H.groups.filter(ee=>{try{return ee.model.location.type==="grid"}catch{return!0}});V.length>0?z.api.moveTo({group:V[0],position:"center"}):z.api.moveTo({position:"center"}),z.api.setActive()},[]),ne=o.useCallback(()=>{var ve;const B=S.current;if(!B)return;const z=B.groups.filter(Ne=>{var Se;try{return((Se=Ne.element)==null?void 0:Se.ownerDocument)===document&&Ne.model.location.type==="grid"}catch{return!1}})[0]||null,V=[...B.panels];for(const Ne of V){const Se=(ve=Ne.group.element)==null?void 0:ve.ownerDocument,Ue=Ne.group.model.location.type;Se===document&&Ue==="grid"||(z&&z.id!==Ne.group.id?Ne.api.moveTo({group:z,position:"center"}):Ne.api.moveTo({position:"center"}))}const ee=B.activePanel;ee&&(ee.group.model.openPanel(ee),ee.api.setActive()),An(document)},[]),ge=o.useCallback(()=>{var H,z;const B=S.current;if(B)for(const V of B.groups){const ee=(H=V.element)==null?void 0:H.ownerDocument;if(!ee||ee===document)continue;const ve=ee.getElementById("dv-popout-window");if(!(ve instanceof HTMLElement))continue;let Ne=null,Se=ee.title||"ADHDev",Ue="Popout workspace";const We=V.activePanel;if(We)if(Ne=We.id,Gt(We.id)){const Fe=((z=We.params)==null?void 0:z.routeId)||We.id.slice(7),_=Kt([...we.values()],Fe);Se=$i(_),Ue=_!=null&&_.machineName?`Remote view · ${_.machineName}`:"Remote view"}else{const Fe=we.get(We.id);Se=Fe?ct(Fe):We.title||We.id,Ue=Fe?cs(Fe):"Dockview panel"}ee.title=`${Se} — ADHDev`;let Ce=ee.getElementById("adhdev-popout-header");Ce instanceof HTMLElement||(Ce=ee.createElement("div"),Ce.id="adhdev-popout-header",ee.body.appendChild(Ce)),Ce.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(";")),Ce.innerHTML=`
|
|
45
|
+
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
46
|
+
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
47
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ao(Se)}</div>
|
|
48
|
+
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Ao(Ue)}</div>
|
|
49
|
+
</div>
|
|
50
|
+
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
51
|
+
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
52
|
+
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
53
|
+
</div>
|
|
54
|
+
`,ve.style.top="52px",ve.style.height="calc(100% - 52px)";const Z=Ce.querySelector("[data-adhdev-popout-focus]");Z&&(Z.onclick=()=>{window.focus()});const $e=Ce.querySelector("[data-adhdev-popout-dock]");$e&&($e.disabled=!Ne,$e.style.opacity=Ne?"1":"0.5",$e.style.cursor=Ne?"pointer":"default",$e.onclick=()=>{var Fe;Ne&&oe(Ne),(Fe=ee.defaultView)==null||Fe.focus()})}},[we,oe]),me=o.useCallback(B=>{var V;const H=S.current,z=H==null?void 0:H.getPanel(B);if(!(!H||!z)){z.group.model.openPanel(z),z.api.setActive();try{const ee=z.group.model.location;ee.type==="popout"?ee.getWindow().focus():An((V=z.group.element)==null?void 0:V.ownerDocument)}catch{}}},[]),E=o.useCallback(B=>{const H=S.current,z=H==null?void 0:H.activePanel,V=(H==null?void 0:H.activeGroup)||(z==null?void 0:z.group);if(!H||!z||!V)return;const ee=V.panels||[];if(ee.length<=1)return;const ve=ee.findIndex(Ue=>Ue.id===z.id);if(ve<0)return;const Ne=(ve+B+ee.length)%ee.length,Se=ee[Ne];Se&&(Se.group.model.openPanel(Se),Se.api.setActive())},[]),ye=o.useCallback(B=>{var $e;const H=S.current,z=(H==null?void 0:H.activeGroup)||(($e=H==null?void 0:H.activePanel)==null?void 0:$e.group);if(!H||!z)return;const V=H.groups||[],ee=V.find(Fe=>Fe.id===z.id);if(!ee)return;const ve=ee.element.getBoundingClientRect(),Ne=ve.left+ve.width/2,Se=ve.top+ve.height/2,Ue=(Fe,_,Y,re)=>Math.max(0,Math.min(_,re)-Math.max(Fe,Y)),We=Fe=>{const _=Fe.element.getBoundingClientRect(),Y=_.left+_.width/2,re=_.top+_.height/2;let _e=0,Te=0,Pe=0,Ee=!1;if(B==="left"?(Ee=Y<Ne,_e=Math.max(0,ve.left-_.right),Te=Math.abs(re-Se),Pe=Ue(ve.top,ve.bottom,_.top,_.bottom)):B==="right"?(Ee=Y>Ne,_e=Math.max(0,_.left-ve.right),Te=Math.abs(re-Se),Pe=Ue(ve.top,ve.bottom,_.top,_.bottom)):B==="above"?(Ee=re<Se,_e=Math.max(0,ve.top-_.bottom),Te=Math.abs(Y-Ne),Pe=Ue(ve.left,ve.right,_.left,_.right)):(Ee=re>Se,_e=Math.max(0,_.top-ve.bottom),Te=Math.abs(Y-Ne),Pe=Ue(ve.left,ve.right,_.left,_.right)),!Ee)return Number.POSITIVE_INFINITY;const Ke=Pe>0?0:120;return _e*3+Te+Ke};let Ce=null,Z=Number.POSITIVE_INFINITY;for(const Fe of V){if(Fe.id===ee.id)continue;const _=We(Fe);Number.isFinite(_)&&(_>=Z||(Z=_,Ce=Fe))}return Ce||void 0},[]),he=o.useCallback(B=>{var V;const H=ye(B);if(!H)return;const z=H.activePanel||H.panels[0];z&&(H.model.openPanel(z),z.api.setActive(),An((V=H.element)==null?void 0:V.ownerDocument))},[ye]),je=o.useCallback((B,H)=>{const z=S.current,V=z==null?void 0:z.activePanel,ee=(z==null?void 0:z.activeGroup)||(V==null?void 0:V.group);if(!z||!V||!ee)return;let ve=ye(B);!ve&&(H!=null&&H.createGroupIfMissing)&&(ve=z.addGroup({referenceGroup:ee,direction:B})),ve&&(V.api.moveTo({group:ve,position:"center"}),V.group.model.openPanel(V),V.api.setActive())},[ye]),{isMac:Q,tabShortcuts:ke,shortcutListening:He,setShortcutListening:De,saveShortcuts:Ge}=bc({sortedTabKeys:e.map(B=>B.tabKey),onFocus:Ie,onSelectTab:me}),Qe=o.useCallback(()=>{var z;const B=S.current;if(!B)return;const H=B.activePanel;if(H){if(Gt(H.id)){const V=((z=H.params)==null?void 0:z.routeId)||H.id.slice(7),ee=Kt(e,V);ee!=null&&ee.tabKey&&De(ee.tabKey);return}we.has(H.id)&&De(H.id)}},[we,me,De,e]),Ze=o.useCallback(B=>{const H=[];return B.metaKey&&H.push(Q?"⌘":"Meta"),B.ctrlKey&&H.push("Ctrl"),B.altKey&&H.push(Q?"⌥":"Alt"),B.shiftKey&&B.key.length!==1&&H.push(Q?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(B.key)?null:(H.push(wc(B.key)),H.join("+"))},[Q]),ut=o.useCallback(B=>{var H,z;switch(B){case"splitActiveTabRight":je("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":je("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const V=J();V&&se(V);return}case"popoutActiveTab":{const V=J();V&&xe(V);return}case"dockActiveTab":{const V=J();if(!V)return;F(V)?oe(V):pe(V)&&de(V);return}case"focusLeftPane":he("left");return;case"focusRightPane":he("right");return;case"focusUpPane":he("above");return;case"focusDownPane":he("below");return;case"moveActiveTabToLeftPane":je("left");return;case"moveActiveTabToRightPane":je("right");return;case"moveActiveTabToUpPane":je("above");return;case"moveActiveTabToDownPane":je("below");return;case"selectPreviousGroupTab":E(-1);return;case"selectNextGroupTab":E(1);return;case"setActiveTabShortcut":Qe();return;case"hideCurrentTab":{const V=(z=(H=S.current)==null?void 0:H.activePanel)==null?void 0:z.id;V&&!Gt(V)&&be(V);return}default:return}},[E,de,he,se,J,be,pe,F,oe,je,xe,Qe]);o.useEffect(()=>{if(!L)return;const B=L.sourceDocument,H=B.defaultView??window,z=V=>{const ee=B.querySelector("[data-dockview-tab-context-menu]");ee&&ee.contains(V.target)||O(null)};return H.addEventListener("mousedown",z,!0),H!==window&&window.addEventListener("mousedown",()=>O(null),!0),()=>{H.removeEventListener("mousedown",z,!0),H!==window&&window.removeEventListener("mousedown",()=>O(null),!0)}},[L]);const qe=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:we,hasDetachedConversationPanels:ce,ides:r,isStandalone:l,hasRegisteredMachines:u,liveSessionInboxState:Le,notificationStateBySessionId:C,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:be,userName:m,scrollToBottomRequest:h,tabShortcuts:ke,openTabContextMenu:({x:B,y:H,tabKey:z,sourceDocument:V})=>O({x:B,y:H,tabKey:z,sourceDocument:V??document}),popoutTab:xe,moveTabBackToMain:oe,isTabInPopout:F,floatTab:se,isTabFloating:pe}),[n,s,we,ce,r,l,u,Le,C,a,c,i,be,m,h,ke,xe,oe,F,se,pe]),ht=L?vf({isTabInPopout:F(L.tabKey),isTabFloating:pe(L.tabKey),tabShortcut:ke[L.tabKey],actionShortcuts:w}):[],mt=o.useCallback(B=>{var V;const H=S.current;if((((V=H==null?void 0:H.activePanel)==null?void 0:V.id)??null)===B.id){B.group.model.openPanel(B);return}B.group.model.openPanel(B),B.api.setActive()},[]),tt=o.useCallback(B=>{if(!B)return!1;const H=S.current;if(!H)return!1;const z=H.getPanel(B);return z?(mt(z),v==null||v(),!0):!1},[mt,v]),xt=o.useCallback(()=>{if(K.current)return!1;const B=tt(I.current);return B&&(K.current=!0),B},[tt]),pt=o.useCallback(()=>{var H;const B=S.current;B&&cp(W,{activeTabId:((H=B.activePanel)==null?void 0:H.id)??null,layout:B.toJSON()})},[W]),le=o.useCallback(()=>{dp(W,X.current)},[W]),Ve=o.useCallback(B=>{var V,ee,ve,Ne;const H=S.current;if(!H)return{kind:"grid"};const z=H.toJSON();for(const Se of z.floatingGroups||[])if((ee=(V=Se.data)==null?void 0:V.views)!=null&&ee.includes(B)&&Se.position)return{kind:"floating",position:Se.position};for(const Se of z.popoutGroups||[])if((Ne=(ve=Se.data)==null?void 0:ve.views)!=null&&Ne.includes(B))return{kind:"popout",position:Se.position,popoutUrl:Se.url};return{kind:"grid"}},[]),lt=o.useCallback(B=>{const H=S.current;if(!H)return;const z=H.getPanel(B),V=X.current[B];if(!z||!V||V.kind==="grid")return;if(z.group.model.location.type===V.kind){delete X.current[B],le();return}if(V.kind==="floating"){H.addFloatingGroup(z,{x:V.position.left??24,y:V.position.top??24,width:V.position.width,height:V.position.height}),delete X.current[B],le();return}delete X.current[B],le()},[le]);o.useEffect(()=>(k==null||k({setShortcutForActiveTab:Qe,restoreHiddenTabToSavedLocation:lt,activateConversationTab:me,resetAllPanelsToMain:ne,activatePreviousTabInGroup:()=>E(-1),activateNextTabInGroup:()=>E(1),floatActiveTab:()=>{const B=J();B&&se(B)},popoutActiveTab:()=>{const B=J();B&&xe(B)},dockActiveTab:()=>{const B=J();B&&(F(B)?oe(B):pe(B)&&de(B))},splitActiveTabRight:()=>je("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>je("below",{createGroupIfMissing:!0}),focusLeftPane:()=>he("left"),focusRightPane:()=>he("right"),focusUpPane:()=>he("above"),focusDownPane:()=>he("below"),moveActiveTabToLeftPane:()=>je("left"),moveActiveTabToRightPane:()=>je("right"),moveActiveTabToUpPane:()=>je("above"),moveActiveTabToDownPane:()=>je("below")}),()=>k==null?void 0:k(null)),[E,de,se,he,J,pe,F,je,oe,xe,k,ne,lt,me,Qe]);const Je=o.useCallback(()=>{const B=j.current;if(!B)return;const H=B.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const z of H)z.setAttribute("data-adhdev-force-hidden","true")},[]),bt=o.useCallback(()=>{const B=j.current;if(!B)return;const H=B.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const z of H)z.removeAttribute("data-adhdev-force-hidden")},[]),kt=o.useCallback(()=>{const B=j.current;if(!B)return;const H=B.querySelectorAll(".dv-drop-target-container");for(const ee of H)ee.remove();const z=B.querySelectorAll(".dv-drop-target-dropzone");for(const ee of z)ee.remove();const V=B.querySelectorAll(".dv-drop-target");for(const ee of V)ee.classList.remove("dv-drop-target")},[]),St=o.useCallback(()=>{N(!1),G(!1),bt(),Je(),kt(),!(typeof window>"u")&&($.current!=null&&window.clearTimeout($.current),window.requestAnimationFrame(()=>{Je(),kt()}),$.current=window.setTimeout(()=>{Je(),kt(),$.current=null},80))},[bt,Je,kt]),Ct=o.useCallback(B=>{var z;S.current=B.api;const H=ip(W);if(I.current=(H==null?void 0:H.activeTabId)??null,H!=null&&H.layout&&B.api.fromJSON(H.layout,{reuseExistingPanels:!1}),x.current=Io({hasStoredLayout:!!(H!=null&&H.layout),initialDataLoaded:p,visibleConversationCount:e.length,ides:r}),x.current||(Mo(B.api,e),Lo(B.api,e,b)),B.api.totalPanels===0&&e.length>0){const V=Sf(B.api,e,d);if(V){const ee=B.api.getPanel(V);ee&&mt(ee)}}else!x.current&&!tt(d)&&xt();g.current=!0,B.api.onDidActivePanelChange(V=>{var ve;if(I.current=(V==null?void 0:V.id)??null,K.current=!0,ge(),V&&Gt(V.id)){const Ne=((ve=V.params)==null?void 0:ve.routeId)||V.id.slice(7),Se=Kt(e,Ne);T((Se==null?void 0:Se.tabKey)??null),pt();return}if(T((V==null?void 0:V.id)??null),pt(),!V)return;const ee=we.get(V.id);(ee==null?void 0:ee.streamSource)==="agent-stream"&&ee.agentType&&y(ee.routeId,lc(),{agentType:ee.agentType,...ee.sessionId&&{targetSessionId:ee.sessionId}}).catch(()=>{})}),B.api.onDidLayoutChange(()=>{pt(),ge(),D(V=>V+1)}),B.api.onWillDragPanel(()=>{N(!0),G(!1),Je()}),B.api.onWillDragGroup(()=>{N(!0),G(!1),Je()}),B.api.onWillShowOverlay(()=>{bt(),G(!0)}),B.api.onDidMovePanel(St),B.api.onDidDrop(St),B.api.onDidAddGroup(V=>{requestAnimationFrame(()=>{var ee,ve;try{const Ne=(ee=V.element)==null?void 0:ee.ownerDocument;if(!Ne||Ne===document)return;(ve=Ne.getElementById("dv-popout-window"))==null||ve.classList.add("adhdev-dockview");const Se=document.documentElement.getAttribute("data-theme");Se&&Ne.documentElement.setAttribute("data-theme",Se),Ne.body.className=document.body.className;const Ue=document.documentElement.getAttribute("style");Ue&&Ne.documentElement.setAttribute("style",Ue)}catch{}ge(),D(Ne=>Ne+1)})}),T(((z=B.api.activePanel)==null?void 0:z.id)??null)},[mt,tt,St,bt,we,r,p,W,Je,T,pt,d,b,y,ge,e]);o.useLayoutEffect(()=>{const B=S.current;if(!B||!g.current||x.current&&Io({hasStoredLayout:!0,initialDataLoaded:p,visibleConversationCount:e.length,ides:r}))return;x.current&&(x.current=!1);const H=M.current,z=new Set(H),V=e.map(We=>We.tabKey),ee=new Set(V);let ve=!1;for(const We of H)ee.has(We)||(X.current[We]=Ve(We),ve=!0);ve&&le(),Mo(B,e),Lo(B,e,b);const Ne=V.filter(We=>!z.has(We));let Se=!1;for(const We of Ne){const Ce=B.getPanel(We),Z=X.current[We];if(!Ce||!Z||Z.kind==="grid")continue;if(Ce.group.model.location.type===Z.kind){delete X.current[We],Se=!0;continue}if(Z.kind==="floating"){B.addFloatingGroup(Ce,{x:Z.position.left??24,y:Z.position.top??24,width:Z.position.width,height:Z.position.height}),delete X.current[We],Se=!0;continue}}if(Se&&le(),M.current=V,d&&tt(d))return;!B.activePanel&&B.panels[0]&&mt(B.panels[0]),!!(B.activePanel&&B.getPanel(B.activePanel.id))||xt()},[mt,tt,xt,r,p,le,Ve,d,b,e]),o.useEffect(()=>{g.current&&tt(d)},[tt,d]),o.useEffect(()=>{if(!R||typeof window>"u")return;const B=()=>St();return window.addEventListener("pointerup",B),window.addEventListener("mouseup",B),window.addEventListener("dragend",B),()=>{window.removeEventListener("pointerup",B),window.removeEventListener("mouseup",B),window.removeEventListener("dragend",B)}},[St,R]),o.useEffect(()=>()=>{typeof window>"u"||$.current!=null&&window.clearTimeout($.current)},[]),o.useEffect(()=>{const B=z=>{const V=z.target;if(!V)return;const ee=V.querySelector("[data-tab-key]")||V.closest("[data-tab-key]");if(ee){const ve=ee.getAttribute("data-tab-key");if(ve&&z.dataTransfer){const Ne=V.closest(".dv-tab")||ee.closest(".dv-tab")||ee;z.dataTransfer.effectAllowed="move",z.dataTransfer.setData("text/tab-key",ve),Ne instanceof HTMLElement&&z.dataTransfer.setDragImage(Ne,Math.max(12,Math.round(Ne.clientWidth/2)),Math.max(10,Math.round(Ne.clientHeight/2)))}}};window.addEventListener("dragstart",B);const H=To(S.current);for(const z of H)z.addEventListener("dragstart",B);return()=>{window.removeEventListener("dragstart",B);for(const z of H)z.removeEventListener("dragstart",B)}},[A]),o.useEffect(()=>{var H;const B=(H=j.current)==null?void 0:H.querySelector(".adhdev-dockview");B instanceof HTMLElement&&Ir(B,P),ue(),ge(),ae()},[ge,ae,ue,P]),o.useEffect(()=>{ge(),ae()},[ge,ae]),o.useEffect(()=>{const B=H=>{if(H.defaultPrevented||He)return;const z=Ze(H);if(!z)return;const V=H.metaKey||H.ctrlKey||H.altKey;Jn(H.target)&&!V||qr(Q).setActiveTabShortcut!==z||(H.preventDefault(),H.stopPropagation(),Qe())};return window.addEventListener("keydown",B,!0),()=>window.removeEventListener("keydown",B,!0)},[Ze,Q,He,Qe]),o.useEffect(()=>{const B=j.current;if(!B)return;const H=z=>{var Se,Ue;if(!z.isTrusted)return;const V=(Ue=(Se=z.target)==null?void 0:Se.closest)==null?void 0:Ue.call(Se,".dv-scrollable");if(!V)return;z.preventDefault(),z.stopPropagation();const ee=Math.abs(z.deltaX),ve=Math.abs(z.deltaY),Ne=ee>ve?z.deltaX:z.deltaY;V.dispatchEvent(new WheelEvent("wheel",{deltaY:Ne,deltaMode:z.deltaMode,bubbles:!1,cancelable:!0}))};return B.addEventListener("wheel",H,{passive:!1,capture:!0}),()=>B.removeEventListener("wheel",H,{capture:!0})},[]),o.useEffect(()=>{const B=To(S.current);if(B.length===0)return;const H=B.map(z=>{let V=[],ee=null;const ve=()=>{ee!=null&&z.clearTimeout(ee),ee=null,V=[]},Ne=()=>{ee!=null&&z.clearTimeout(ee),ee=z.setTimeout(()=>{ee=null,V=[]},1200)},Se=We=>{if(!We.ctrlKey&&!We.metaKey&&!We.altKey)return;const Ce=Ze(We);if(!Ce)return;const Z=xc();for(const[$e,Fe]of Object.entries(Z))if(e.some(_=>_.tabKey===$e)&&Fe===Ce){We.preventDefault(),me($e);return}},Ue=We=>{if(We.defaultPrevented||He)return;const Ce=Ze(We);if(!Ce)return;const Z=We.metaKey||We.ctrlKey||We.altKey;if(Jn(We.target)&&!Z)return;const $e=qr(Q),Fe=Object.entries($e).filter(([Ke,st])=>!!st&&(Ke==="splitActiveTabRight"||Ke==="splitActiveTabDown"||Ke==="floatActiveTab"||Ke==="popoutActiveTab"||Ke==="dockActiveTab"||Ke==="focusLeftPane"||Ke==="focusRightPane"||Ke==="focusUpPane"||Ke==="focusDownPane"||Ke==="moveActiveTabToLeftPane"||Ke==="moveActiveTabToRightPane"||Ke==="moveActiveTabToUpPane"||Ke==="moveActiveTabToDownPane"||Ke==="selectPreviousGroupTab"||Ke==="selectNextGroupTab"||Ke==="setActiveTabShortcut"||Ke==="hideCurrentTab")),_=Z?[Ce]:[...V.slice(-1),Ce].slice(-2),Y=_.join(" "),re=_[_.length-1],_e=Fe.find(([,Ke])=>Ke===Y);if(_e){We.preventDefault(),ve(),ut(_e[0]);return}if(Fe.some(([,Ke])=>Ke.startsWith(`${Y} `))){We.preventDefault(),V=_,Ne();return}const Pe=Fe.find(([,Ke])=>Ke===re);if(Pe){We.preventDefault(),ve(),ut(Pe[0]);return}if(Fe.some(([,Ke])=>Ke.startsWith(`${re} `))){We.preventDefault(),V=[re],Ne();return}ve()};return z.addEventListener("keydown",Se),z.addEventListener("keydown",Ue),()=>{ve(),z.removeEventListener("keydown",Se),z.removeEventListener("keydown",Ue)}});return()=>{for(const z of H)z()}},[Ze,Q,A,me,He,ut,e]);const Lt=P==="light"?Kn:Bn,q=((ft=(Re=(Be=S.current)==null?void 0:Be.activePanel)==null?void 0:Re.group.element)==null?void 0:ft.ownerDocument)??document;return t.jsxs(jc.Provider,{value:qe,children:[t.jsx("div",{ref:j,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(rl,{className:`h-full min-h-0 min-w-0 adhdev-dockview${R?" is-dragging-dockview":""}${U?" is-showing-dockview-overlay":""}`,components:{conversation:Nf,remote:Cf},defaultTabComponent:Af,watermarkComponent:If,onReady:Ct,singleTabMode:"default",tabAnimation:"smooth",theme:Lt,popoutUrl:"/popout.html"})}),L&&sr.createPortal(t.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:L.x,top:L.y},children:ht.map(B=>{if(B.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},B.id);let H=t.jsx(Hl,{size:13,className:"shrink-0 opacity-70"}),z=()=>{};switch(B.id){case"dockInWindow":case"dockBackToGrid":H=t.jsx(Fl,{size:13,className:"shrink-0 opacity-70"}),z=()=>{de(L.tabKey),O(null)};break;case"moveBackToMain":H=t.jsx(Ol,{size:13,className:"shrink-0 opacity-70"}),z=()=>{oe(L.tabKey),O(null)};break;case"floatAsPanel":H=t.jsx(Ul,{size:13,className:"shrink-0 opacity-70"}),z=()=>{se(L.tabKey),O(null)};break;case"openInNewWindow":H=t.jsx(Wl,{size:13,className:"shrink-0 opacity-70"}),z=()=>{xe(L.tabKey),O(null)};break;case"setShortcut":z=V=>{V.stopPropagation(),De(L.tabKey),O(null)};break;case"removeShortcut":H=t.jsx(Nt,{size:13,className:"shrink-0 opacity-70"}),z=()=>{const V={...ke};delete V[L.tabKey],Ge(V),O(null)};break;case"hideTab":H=t.jsx(Zo,{size:13,className:"shrink-0 opacity-70"}),z=()=>{be(L.tabKey),O(null)};break}return t.jsxs("button",{className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${B.tone==="muted"?"text-text-muted":""}`,onClick:z,children:[H,t.jsx("span",{className:"flex-1 min-w-0",children:B.label}),B.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:B.shortcut}):null]},B.id)})}),L.sourceDocument.body),He&&sr.createPortal(t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>De(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:B=>B.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",Q?"⌘+1":"Ctrl+1",", ",Q?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),q.body)]})}const kc="adhdev-recent-launch-args-v1",Mf=8;function Lf(e){return String(e||"").trim().replace(/\s+/g," ")}function Sc(e,s){return`${e.trim()}::${s.trim()}`}function Nc(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(kc)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function _f(e){if(!(typeof window>"u"))try{window.localStorage.setItem(kc,JSON.stringify(e))}catch{}}function Cc(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Nc().byKey[Sc(r,n)])==null?void 0:i.items)||[]}function Ic(e,s,r){var m;const n=String(e||"").trim(),a=String(s||"").trim(),i=Lf(r);if(!n||!a||!i)return;const c=Nc(),l=Sc(n,a),u=((m=c.byKey[l])==null?void 0:m.items)||[],p=[i,...u.filter(f=>f!==i)].slice(0,Mf);c.byKey[l]={items:p},_f(c)}function Rf(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 Ma(e){const s=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return s?s==="auto_resumed"?"restored after restart":s==="resume_failed"?"restore failed":s==="host_restart_interrupted"?"host restart interrupted":s==="orphan_snapshot"?"snapshot recovered":s.replace(/_/g," "):null}function Ac(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=Ma((i==null?void 0:i.meta)||void 0),u=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?s.push(i):(c==="stopped"||c==="failed")&&(u||l)?r.push(i):n.push(i)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function Tc(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function As(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 Tn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Pf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function _o(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function Ro(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function Df(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function $f(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 Ef(e){var r;const s=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const i=`${n.providerType}::${n.workspace}::${a}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function Kf({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:a,onOpenConversation:i,onClose:c}){var G;const[l,u]=o.useState(n||((G=e[0])==null?void 0:G.id)||null),[p,m]=o.useState(""),[f,w]=o.useState(null),[k,T]=o.useState(!1);o.useEffect(()=>{var A;u(n||((A=e[0])==null?void 0:A.id)||null)},[n,e]);const d=o.useMemo(()=>e.find(A=>A.id===l)||e[0]||null,[l,e]),b=o.useMemo(()=>r.filter(A=>{if(A.type==="adhdev-daemon"||A.transport!=="pty")return!1;const D=Pf(A.daemonId||A.id);return!!(d!=null&&d.id)&&D===d.id}),[d==null?void 0:d.id,r]),v=tc(d==null?void 0:d.id,{enabled:!!(d!=null&&d.id),includeSessions:!0,limit:6,intervalMs:1e4}),h=v.diagnostics,C=v.loading,P=v.applyDiagnostics,y=o.useMemo(()=>{const A=new Map;for(const D of b){const $=s.find(W=>W.sessionId===D.sessionId||W.routeId===D.id);D.sessionId&&$&&A.set(D.sessionId,$)}return A},[b,s]),S=o.useCallback(async()=>{if(d!=null&&d.id){T(!0);try{const A=await a(d.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),D=Tn(A);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Could not load hosted runtime diagnostics");P(D.diagnostics||D.result||null),m("")}catch(A){const D=A instanceof Error?A.message:"Could not load hosted runtime diagnostics";m(D)}finally{T(!1)}}},[d==null?void 0:d.id,P,a]);o.useEffect(()=>{!(d!=null&&d.id)||h||C||k||S()},[d==null?void 0:d.id,h,C,S,k]);const j=o.useCallback(async(A,D)=>{if(!(d!=null&&d.id)||A==="session_host_stop_session"&&!window.confirm(`Stop ${D.displayName}?
|
|
55
|
+
This will terminate the hosted runtime.`))return;const $=`${A}:${D.sessionId}`;w($);try{const W=await a(d.id,A,{sessionId:D.sessionId}),X=Tn(W);if(!(X!=null&&X.success))throw new Error((X==null?void 0:X.error)||"Session host action failed");const we=A==="session_host_resume_session"?"resumed":A==="session_host_restart_session"?"restarted":"stopped";it.showToast(`Session host ${we}: ${D.displayName}`,"success"),await S()}catch(W){const X=W instanceof Error?W.message:"Session host action failed";m(X),it.showToast(X,"warning")}finally{w(W=>W===$?null:W)}},[d==null?void 0:d.id,S,a]),g=o.useCallback(async()=>{if(!(!(d!=null&&d.id)||!window.confirm(`Prune duplicate hosted runtimes?
|
|
56
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){w("session_host_prune_duplicate_sessions");try{const D=await a(d.id,"session_host_prune_duplicate_sessions",{}),$=Tn(D);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"Duplicate prune failed");const W=$.result||{},X=Array.isArray(W.prunedSessionIds)?W.prunedSessionIds.length:0,we=typeof W.duplicateGroupCount=="number"?W.duplicateGroupCount:0;it.showToast(`Pruned ${X} duplicate runtime(s) across ${we} group(s)`,"success"),await S()}catch(D){const $=D instanceof Error?D.message:"Duplicate prune failed";m($),it.showToast($,"warning")}finally{w(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[d==null?void 0:d.id,S,a]),x=o.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((A,D)=>(D.lastActivityAt||0)-(A.lastActivityAt||0)),[h==null?void 0:h.sessions]),K=o.useMemo(()=>h!=null&&h.liveRuntimes||h!=null&&h.recoverySnapshots||h!=null&&h.inactiveRecords?{liveRuntimes:(h==null?void 0:h.liveRuntimes)||[],recoverySnapshots:(h==null?void 0:h.recoverySnapshots)||[],inactiveRecords:(h==null?void 0:h.inactiveRecords)||[]}:Ac(x),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,x]),I=K.liveRuntimes,M=K.recoverySnapshots,L=K.inactiveRecords,O=o.useMemo(()=>Ef(I),[I]),R=o.useMemo(()=>[...(h==null?void 0:h.recentLogs)||[]].reverse().find(A=>A.level==="warn"||A.level==="error")||null,[h==null?void 0:h.recentLogs]),N=o.useMemo(()=>[...(h==null?void 0:h.recentTransitions)||[]].slice(-3).reverse(),[h==null?void 0:h.recentTransitions]),U=(A,D)=>{var ae,xe;const $=y.get(A.sessionId),W=b.find(oe=>oe.sessionId===A.sessionId),X=f===`session_host_resume_session:${A.sessionId}`,we=f===`session_host_restart_session:${A.sessionId}`,Le=f===`session_host_stop_session:${A.sessionId}`,ce=Ma(A.meta),Ie=typeof((ae=A.meta)==null?void 0:ae.runtimeRecoveryError)=="string"?String(A.meta.runtimeRecoveryError):"",te=D==="recovery"?"Recover":"Resume",ue=Tc(D);return t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-3.5",children:[t.jsx("div",{className:"flex items-start justify-between gap-3",children:t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("div",{className:"text-[14px] font-bold text-text-primary",children:A.displayName||(W==null?void 0:W.runtimeDisplayName)||(W==null?void 0:W.cliName)||A.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${$f(A.lifecycle)}`,children:A.lifecycle}),ce&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:ce})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:A.workspaceLabel||(W==null?void 0:W.runtimeWorkspaceLabel)||A.workspace||"No workspace"}),t.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-mono text-text-primary",children:A.runtimeKey}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:((xe=A.writeOwner)==null?void 0:xe.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Df(A.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(na,{size:11})," ",A.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",Ro(A.lastActivityAt),A.osPid?` · pid ${A.osPid}`:"",` · Next: ${ue}`]}),Ie&&t.jsx("div",{className:"mt-2 rounded-xl border border-red-500/[0.18] bg-red-500/[0.07] px-3 py-2 text-[11px] text-red-200",children:Ie})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[$&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i($),c()},children:"Open chat"}),D==="recovery"&&(A.lifecycle==="interrupted"||A.lifecycle==="failed"||A.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!f,onClick:()=>{j("session_host_resume_session",A)},children:X?`${te}ing…`:te}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!f,onClick:()=>{j("session_host_restart_session",A)},children:we?"Restarting…":"Restart"}),D==="live"&&(A.lifecycle==="running"||A.lifecycle==="starting"||A.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn border-red-500/20 px-2.5 py-1 text-[11px] text-red-300 hover:text-red-200",disabled:!!f,onClick:()=>{j("session_host_stop_session",A)},children:Le?"Stopping…":"Stop"})]})]},A.sessionId)};return t.jsx("div",{className:"fixed inset-0 z-[115] flex items-end justify-center bg-black/55 backdrop-blur-[2px] md:items-center md:p-4",onClick:c,children:t.jsxs("div",{className:"w-full max-h-[88vh] overflow-hidden rounded-t-[28px] border border-border-subtle bg-bg-primary shadow-[0_-20px_60px_rgba(0,0,0,0.35)] md:max-w-3xl md:rounded-[28px] md:shadow-[0_20px_60px_rgba(0,0,0,0.35)]",onClick:A=>A.stopPropagation(),children:[t.jsx("div",{className:"mx-auto mt-3 h-1.5 w-12 rounded-full bg-border-subtle"}),t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 pt-4 pb-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Ut,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(d==null?void 0:d.label)||"No machine selected"}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:"Live runtime status, next actions, and explicit recover/restart controls."})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:()=>{S()},disabled:C||k,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(Bs,{size:16})}),t.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:c,"aria-label":"Close hosted runtime recovery",children:t.jsx(Nt,{size:16})})]})]}),e.length>1&&t.jsx("div",{className:"flex gap-2 overflow-x-auto px-5 pb-3 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.map(A=>t.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${A.id===(d==null?void 0:d.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>u(A.id),children:A.label},A.id))}),t.jsxs("div",{className:"flex max-h-[calc(88vh-122px)] flex-col gap-3 overflow-y-auto px-5 pb-[calc(18px+env(safe-area-inset-bottom,0px))]",children:[p&&!h&&t.jsx("div",{className:"rounded-2xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-4 py-3 text-[12px] text-amber-100",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(hs,{size:14,className:"mt-0.5 shrink-0 text-amber-300"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"mt-1 text-amber-200/90",children:p})]})]})}),h&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Live"}),t.jsx("div",{className:"mt-1 text-[18px] font-bold text-text-primary",children:h.runtimeCount})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"mt-1 text-[18px] font-bold text-text-primary",children:M.length})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-3 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.16em] text-text-secondary",children:"Started"}),t.jsx("div",{className:"mt-1 text-[12px] font-semibold text-text-primary",children:Ro(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:_o(h.hostStartedAt)})]})]}),R&&t.jsxs("div",{className:"rounded-2xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-4 py-3",children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200",children:[t.jsx(hs,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:R.message})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Qr,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[O>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:f==="session_host_prune_duplicate_sessions",onClick:()=>{g()},children:f==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${O}`}),t.jsxs("div",{className:"text-[11px] text-text-secondary",children:[b.length," dashboard session",b.length===1?"":"s"]})]})]}),t.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:As("live")}),I.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No live hosted CLI runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:I.map(A=>U(A,"live"))}),t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recovery snapshots"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:As("recovery")}),M.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No recovery snapshots need attention."}):t.jsx("div",{className:"space-y-2",children:M.map(A=>U(A,"recovery"))})]}),L.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Inactive records"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:As("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:L.map(A=>U(A,"inactive"))})]}),N.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recent activity"}),t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary divide-y divide-border-subtle",children:N.map(A=>{const D=x.find($=>$.sessionId===A.sessionId);return t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-2.5",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[12px] font-semibold text-text-primary",children:(D==null?void 0:D.displayName)||A.sessionId}),t.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[A.action,A.lifecycle?` · ${A.lifecycle}`:"",A.detail?` · ${A.detail}`:"",A.error?` · ${A.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${A.success===!1?"text-red-300":"text-text-secondary"}`,children:_o(A.timestamp)})]},`${A.sessionId}:${A.timestamp}:${A.action}`)})})]})]})]})]})})}function Xs({title:e,description:s,action:r,children:n,className:a="",contentClassName:i=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),s&&t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:s})]}),r?t.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?t.jsx("div",{className:s||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function Mc({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?mc(n):null;return t.jsxs(Xs,{title:"Saved history",description:ba(),action:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||s,onClick:a,children:s?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:i,children:Vu()})]}),children:[l?t.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),t.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:l.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:l.providerSessionId}),t.jsx("div",{className:"mt-1",children:l.metaLine}),l.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:l.updatedLabel}),l.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:l.preview})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:c,disabled:e,children:"Clear"})]})}):t.jsx("div",{className:"text-[11px] text-text-muted",children:"Start fresh, or open saved history when you want continuity."}),r&&t.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function Mn(e){var n;if(!e)return null;const s=e.availableProviders||[];return s.some(a=>a.category==="cli"&&a.installed!==!1)?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(a=>a.category==="acp"&&a.installed!==!1)?"acp":null}function Ar(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Bf({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:u,sendDaemonCommand:p,onOpenConversation:m}){var Ct,Lt;const f=lr(),w=o.useMemo(()=>[...e].sort(da),[e]),[k,T]=o.useState(((Ct=w[0])==null?void 0:Ct.id)||""),d=o.useMemo(()=>w.find(q=>q.id===k)||w[0],[k,w]),b=o.useMemo(()=>((d==null?void 0:d.workspaces)||[]).map(q=>({id:q.id,path:q.path,label:q.label})),[d]),v=(d==null?void 0:d.defaultWorkspaceId)||null,[h,C]=o.useState(""),[P,y]=o.useState(""),[S,j]=o.useState(Mn(w[0])),[g,x]=o.useState(""),[K,I]=o.useState(""),[M,L]=o.useState([]),[O,R]=o.useState(""),[N,U]=o.useState([]),[G,A]=o.useState(!1),[D,$]=o.useState(""),[W,X]=o.useState(!1),[we,Le]=o.useState(()=>yt()),[ce,Ie]=o.useState(!1),[te,ue]=o.useState(null),[ae,xe]=o.useState(!1),[oe,F]=o.useState(""),[be,se]=o.useState(!1),[pe,J]=o.useState(""),[de,ne]=o.useState([]),[ge,me]=o.useState(!1),[E,ye]=o.useState(""),[he,je]=o.useState(!1),Q=o.useRef(null),ke=o.useRef(0);o.useEffect(()=>{var q;!k&&((q=w[0])!=null&&q.id)&&T(w[0].id)},[k,w]),o.useEffect(()=>{!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||f(d.id,{minFreshMs:3e4}).catch(()=>{})},[f,d]);const He=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(q=>q.category==="cli"&&q.installed!==!1),[d]),De=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(q=>q.category==="acp"&&q.installed!==!1),[d]),Ge=o.useMemo(()=>((d==null?void 0:d.detectedIdes)||[]).map(q=>({id:q.type,label:q.name||q.type,meta:q.running?"Detected locally":"Available to open"})),[d]),Qe=o.useMemo(()=>S==="cli"?He.map(q=>({id:q.type,label:q.displayName||q.type,meta:"CLI provider"})):S==="acp"?De.map(q=>({id:q.type,label:q.displayName||q.type,meta:"ACP provider"})):Ge,[De,S,He,Ge]);o.useEffect(()=>{var Be;if(!d)return;if(Q.current!==d.id){Q.current=d.id,C(v||((Be=b[0])==null?void 0:Be.id)||"__home__"),y(""),j(Mn(d)),x(""),I(""),R(""),U([]),$(""),Le(yt()),F("");return}C(Re=>{var ft;return Re==="__custom__"||Re==="__home__"||b.some(B=>B.id===Re)?Re:v||((ft=b[0])==null?void 0:ft.id)||"__home__"}),j(Re=>Re==="ide"&&Ge.length>0||Re==="cli"&&He.length>0||Re==="acp"&&De.length>0?Re:Mn(d))},[De.length,He.length,v,Ge.length,d,b]),o.useEffect(()=>{var q;S&&(Qe.some(Be=>Be.id===g)||x(((q=Qe[0])==null?void 0:q.id)||""))},[S,Qe,g]);const Ze=o.useCallback(async(q,Be)=>{const Re=ke.current+1;return ke.current=Re,A(!0),$(""),u(q,Be).then(ft=>{ke.current===Re&&U(ft)}).catch(ft=>{ke.current===Re&&(U([]),$(ft instanceof Error?ft.message:"Could not load saved sessions"))}).finally(()=>{ke.current===Re&&A(!1)})},[u]),ut=o.useCallback((q,Be)=>{L(Cc(q,Be))},[]);o.useEffect(()=>{if(R(""),Le(yt()),!d||!g||S==="ide"?L([]):ut(d.id,g),S!=="cli"){U([]),$(""),A(!1);return}if(!d||!g){U([]),$(""),A(!1);return}Ze(d.id,g)},[S,ut,Ze,d,g]),o.useEffect(()=>{if(!O)return;const q=N.find(Be=>Be.providerSessionId===O);q!=null&&q.canResume||R("")},[N,O]);const qe=h==="__custom__"?P.trim():h==="__home__"?"":((Lt=b.find(q=>q.id===h))==null?void 0:Lt.path)||"",ht=o.useMemo(()=>d?r.filter(q=>q.id!==d.id&&q.daemonId===d.id).map(q=>q.workspace):[],[r,d]),mt=o.useMemo(()=>((d==null?void 0:d.recentLaunches)||[]).map(q=>q.workspace),[d]),tt=o.useCallback(q=>{const Be=String(q.workspace||"").trim();if(!Be)return;const Re=b.find(ft=>Ar(ft.path)===Ar(Be));if(Re){C(Re.id),y("");return}C("__custom__"),y(Be)},[b]),xt=o.useCallback(q=>{const Be=String(q.workspace||"").trim();if(!Be)return{workspaceId:null,workspacePath:null};const Re=b.find(ft=>Ar(ft.path)===Ar(Be));return Re?{workspaceId:Re.id,workspacePath:null}:{workspaceId:null,workspacePath:Be}},[b]),pt=o.useMemo(()=>N.find(q=>q.providerSessionId===O)||null,[N,O]),le=o.useMemo(()=>{var Be;if(S!=="cli"||!d||!g)return null;const q=((Be=He.find(Re=>Re.type===g))==null?void 0:Be.displayName)||g;return{routeId:d.id,daemonId:d.id,providerSessionId:O||void 0,transport:"pty",mode:"chat",agentName:q,agentType:g,status:"idle",title:q,messages:[],ideType:g,workspaceName:qe,displayPrimary:q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${d.id}:${g}`,machineName:At(d,{fallbackId:d.id})}},[S,He,qe,d,O,g]),Ve=o.useCallback(()=>{var Be;if(!d)return;C("__custom__"),se(!0),ye("");const q=nn(d.platform,rn(P.trim(),qe,ht,mt,d.defaultWorkspacePath,(Be=b.find(Re=>Re.id===v))==null?void 0:Be.path,b.map(Re=>Re.path)));me(!0),a(d.id,q).then(Re=>{J(Re.path),y(Re.path),ne(Re.directories)}).catch(Re=>{ye(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>me(!1))},[P,v,mt,ht,a,qe,d,b]),lt=o.useCallback(q=>{d&&(me(!0),ye(""),a(d.id,q).then(Be=>{J(Be.path),y(Be.path),ne(Be.directories)}).catch(Be=>{ye(Be instanceof Error?Be.message:"Could not load folder")}).finally(()=>me(!1)))},[a,d]),Je=o.useCallback(async()=>{if(!d||!qe)return;je(!0),F("");const q=await i(d.id,qe);if(je(!1),!q.ok){F(q.error||"Could not save workspace");return}F("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,qe,d]),bt=o.useCallback(async()=>{if(!d||!S||!g)return;xe(!0),F("");const q=K.trim()?K.trim().split(/\s+/).filter(Boolean):[],Be=S==="ide"?await c(d.id,g,{workspacePath:qe||null}):await l(d.id,S,g,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&qe||null,resumeSessionId:S==="cli"&&O?O:null,cliArgs:q});if(xe(!1),!Be.ok){F(Be.error||"Could not start session");return}S!=="ide"&&K.trim()&&(Ic(d.id,g,K),ut(d.id,g)),n()},[S,K,ut,n,c,l,qe,d,O,g,h]),kt=S?Ki(S,S==="cli"&&!!O):"Start",St=S?Bi(S,S==="cli"&&!!O):"Starting…";return d?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:t.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start or recover session"}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh, resume saved history, or recover a hosted runtime."})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:n,"aria-label":"Close new session dialog",children:t.jsx(Nt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[t.jsx(Xs,{title:"Machine",children:t.jsx("select",{value:d.id,onChange:q=>T(q.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:ae,children:w.map(q=>t.jsx("option",{value:q.id,children:At(q,{fallbackId:q.id})},q.id))})}),S==="cli"&&t.jsx(Xs,{title:"Hosted runtimes",description:"Review live runtimes, recovery snapshots, and recover or restart options without leaving this launch flow.",action:t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:ae||!d,onClick:()=>Ie(!0),children:[t.jsx(Ut,{size:14}),Fu()]})}),t.jsxs(Xs,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ve,disabled:ae,children:"Browse…"}),children:[t.jsxs("select",{value:h,onChange:q=>{const Be=q.target.value;C(Be),Be==="__custom__"?Ve():F("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ae,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),b.map(q=>t.jsxs("option",{value:q.id,children:[q.id===v?"⭐ ":"",tn(q.path,q.label)||q.path]},q.id)),t.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h==="__home__"?"Launch without a workspace.":qe||"Select a workspace folder."}),h==="__custom__"&&qe&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ve,disabled:ae,children:[t.jsx(Ms,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Je,disabled:ae||he,children:he?"Saving…":"Save workspace"})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:He.length>0},{id:"ide",label:"IDE",enabled:Ge.length>0},{id:"acp",label:"ACP",enabled:De.length>0}].map(q=>t.jsx("button",{type:"button",className:`btn btn-sm ${S===q.id?"btn-primary":"btn-secondary"}`,onClick:()=>j(q.id),disabled:!q.enabled||ae,children:q.label},q.id))})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:S==="ide"?"Choose IDE":S==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Qe.map(q=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${g===q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>x(q.id),disabled:ae,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:q.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:q.meta})]},q.id)),Qe.length===0&&t.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),S!=="ide"&&t.jsxs(Xs,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:K,onChange:q=>I(q.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:ae}),M.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:M.map(q=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>I(q),disabled:ae,title:q,children:q},q))})]}),S==="cli"&&t.jsx(Mc,{busy:ae,savedSessionsLoading:G,savedSessionsError:D,selectedSession:pt,onRefresh:()=>{!d||!g||Ze(d.id,g)},onOpenHistory:()=>{!d||!g||(X(!0),Ze(d.id,g))},onClearSelection:()=>R("")}),oe&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${oe.includes("saved")||oe.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:oe})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:n,disabled:ae,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:bt,disabled:ae||!S||!g||h==="__custom__"&&!qe,children:[t.jsx(oa,{size:14}),ae?St:kt]})]})]})}),be&&t.jsx(on,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:pe,directories:de,busy:ge,error:E,onClose:()=>se(!1),onNavigate:lt,onConfirm:q=>{y(q),J(q),C("__custom__"),se(!1)}}),W&&le&&t.jsx(va,{activeConv:le,ides:[],isCreatingChat:!1,isRefreshingHistory:G,savedSessions:N,isSavedSessionsLoading:G,isResumingSavedSessionId:te,savedHistoryFilters:we,onSavedHistoryFiltersChange:Le,onClose:()=>X(!1),onNewChat:()=>{R(""),X(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!d||!g||Ze(d.id,g)},onResumeSavedSession:q=>{if(!d||!g||te||!q.canResume)return;const Be=xt(q);R(q.providerSessionId),tt(q),ue(q.providerSessionId),X(!1),xe(!0),F(""),l(d.id,"cli",g,{workspaceId:Be.workspaceId,workspacePath:Be.workspacePath,resumeSessionId:q.providerSessionId}).then(Re=>{if(!Re.ok){F(Re.error||"Could not resume session");return}n()}).finally(()=>{xe(!1),ue(Re=>Re===q.providerSessionId?null:Re)})}}),ce&&d&&t.jsx(Kf,{machineCards:[{id:d.id,label:At(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",fc(d)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:d.id,sendDaemonCommand:p,onOpenConversation:q=>{Ie(!1),n(),m(q)},onClose:()=>Ie(!1)})]}):null}function Wf(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 Of(e){return e instanceof Error?e.message:String(e||"")}function Hf(e){const s=Of(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Uf({showMobileChatMode:e,isMobile:s,activeConv:r,chatIdes:n,wsStatus:a,isConnected:i,onOpenHistory:c,onOpenRemote:l,onStopCli:u,activeCliViewMode:p,onSetActiveCliViewMode:m,mobileChatConversations:f,hiddenConversations:w,ides:k,actionLogs:T,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:v,isStandalone:h,initialDataLoaded:C,userName:P,requestedMobileTabKey:y,onRequestedMobileTabConsumed:S,requestedMachineId:j,onRequestedMachineConsumed:g,requestedMobileSection:x,onRequestedMobileSectionConsumed:K,containerRef:I,isSplitMode:M,numGroups:L,groupSizes:O,groupedConvs:R,clearedTabs:N,focusedGroup:U,setFocusedGroup:G,moveTabToGroup:A,splitTabRelative:D,closeGroup:$,handleResizeStart:W,groupActiveTabIds:X,setGroupActiveTabIds:we,groupTabOrders:Le,setGroupTabOrders:ce,toggleHiddenTab:Ie,visibleConversations:te,requestedDesktopTabKey:ue,onRequestedDesktopTabConsumed:ae,onDesktopActiveTabChange:xe,onHideConversation:oe,onShowHiddenConversation:F,onShowAllHiddenConversations:be,scrollToBottomRequest:se,machineEntries:pe,onBrowseMachineDirectory:J,onSaveMachineWorkspace:de,onLaunchMachineIde:ne,onLaunchMachineProvider:ge,onListMachineSavedSessions:me,notifications:E,notificationUnreadCount:ye,notificationStateBySessionId:he,onMarkNotificationRead:je,onMarkNotificationUnread:Q,onDeleteNotification:ke,onMarkNotificationTargetRead:He}){const De=at.useRef(null),[Ge,Qe]=at.useState(!1),[Ze,ut]=at.useState(!1),[qe,ht]=at.useState(!1),[mt,tt]=at.useState(!1),xt=at.useCallback(Z=>{var $e;sr.flushSync(()=>{F(Z)}),($e=De.current)==null||$e.restoreHiddenTabToSavedLocation(Z.tabKey)},[F]),pt=at.useCallback(Z=>{var Fe;const $e=f.find(_=>Wr(_,Z))||w.find(_=>Wr(_,Z));$e&&(w.some(_=>_.tabKey===$e.tabKey)&&xt($e),xe($e.tabKey),(Fe=De.current)==null||Fe.activateConversationTab($e.tabKey)),je(Z.id),(Z.sessionId||Z.providerSessionId||Z.tabKey||Z.routeId)&&He({sessionId:Z.sessionId,providerSessionId:Z.providerSessionId,tabKey:Z.tabKey,routeId:Z.routeId}),Qe(!1)},[xt,w,f,xe,je,He]),[le,Ve]=at.useState(!1),[lt,Je]=at.useState("quickstart"),[bt,kt]=at.useState("workspace"),St=!e&&!s,Ct=at.useCallback(Z=>{Qe(Z),Z&&ut(!1)},[]),Lt=at.useCallback(Z=>{ut(Z),Z&&Qe(!1)},[]),q=at.useCallback(()=>{var $e;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&(($e=De.current)==null||$e.resetAllPanelsToMain(),ut(!1))},[]),Be=at.useCallback(()=>{Je(te.length===0?"quickstart":"shortcuts"),kt("workspace"),ht(!0),Qe(!1),ut(!1)},[te.length]),Re=at.useCallback(async Z=>{var re;if(!r)return;const $e=(re=r.modalButtons)==null?void 0:re[Z];if(!$e)return;const Fe=ar(r);if(!Fe)return;const _=$e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Y=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_);try{await d(Fe,"resolve_action",{button:$e,action:Y?"approve":"reject",buttonIndex:Z,...Is(r)})}catch(_e){Hf(_e)||console.error("[Shortcut approval] Failed:",_e)}},[r,d]),{isMac:ft,actionDefinitions:B,actionShortcuts:H,shortcutListening:z,shortcutListeningDraft:V,setShortcutListening:ee,setShortcutListeningDraft:ve,saveShortcuts:Ne}=yf({enabled:St&&!qe,onTrigger:Z=>{var $e,Fe,_,Y,re,_e,Te,Pe,Ee,Ke,st,Vt,Zt,ur,es,mr;if(Z==="openShortcutHelp"){Be();return}if(Z==="hideCurrentTab"){r&&oe(r);return}if(Z==="toggleHiddenTabs"){Lt(!Ze);return}if(Z==="openHistoryForActiveTab"){r&&!Xe(r)&&c(r);return}if(Z==="openRemoteForActiveTab"){r&&!et(r)&&!Xe(r)&&l(r);return}if(Z==="splitActiveTabRight"){($e=De.current)==null||$e.splitActiveTabRight();return}if(Z==="splitActiveTabDown"){(Fe=De.current)==null||Fe.splitActiveTabDown();return}if(Z==="floatActiveTab"){(_=De.current)==null||_.floatActiveTab();return}if(Z==="popoutActiveTab"){(Y=De.current)==null||Y.popoutActiveTab();return}if(Z==="dockActiveTab"){(re=De.current)==null||re.dockActiveTab();return}if(Z==="focusLeftPane"){(_e=De.current)==null||_e.focusLeftPane();return}if(Z==="focusRightPane"){(Te=De.current)==null||Te.focusRightPane();return}if(Z==="focusUpPane"){(Pe=De.current)==null||Pe.focusUpPane();return}if(Z==="focusDownPane"){(Ee=De.current)==null||Ee.focusDownPane();return}if(Z==="moveActiveTabToLeftPane"){(Ke=De.current)==null||Ke.moveActiveTabToLeftPane();return}if(Z==="moveActiveTabToRightPane"){(st=De.current)==null||st.moveActiveTabToRightPane();return}if(Z==="moveActiveTabToUpPane"){(Vt=De.current)==null||Vt.moveActiveTabToUpPane();return}if(Z==="moveActiveTabToDownPane"){(Zt=De.current)==null||Zt.moveActiveTabToDownPane();return}if(Z==="triggerPrimaryApprovalAction"){Re(0);return}if(Z==="triggerSecondaryApprovalAction"){Re(1);return}if(Z==="triggerTertiaryApprovalAction"){Re(2);return}if(Z==="setActiveTabShortcut"){(ur=De.current)==null||ur.setShortcutForActiveTab();return}if(Z==="selectPreviousGroupTab"){(es=De.current)==null||es.activatePreviousTabInGroup();return}if(Z==="selectNextGroupTab"){(mr=De.current)==null||mr.activateNextTabInGroup();return}!r||!et(r)||Xe(r)||Z==="toggleCliView"&&m(p==="chat"?"terminal":"chat")}}),Se=at.useCallback(()=>{ht(!1),ee(null),ve([])},[ee,ve]),Ue=at.useMemo(()=>bt==="all"?B:B.filter(Z=>Wf(Z)===bt),[B,bt]),We=at.useCallback(()=>{const Z=Object.fromEntries(B.map($e=>[$e.id,""]));Ne(Z)},[B,Ne]),Ce=at.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Z=Object.fromEntries(B.map($e=>[$e.id,$e.defaultShortcut]));Ne(Z)},[B,Ne]);return at.useEffect(()=>{const Z=$e=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?$e.metaKey&&$e.key.toLowerCase()==="w":$e.ctrlKey&&$e.key.toLowerCase()==="w")&&($e.preventDefault(),r&&oe&&oe(r))};return window.addEventListener("keydown",Z),()=>window.removeEventListener("keydown",Z)},[r,oe]),at.useEffect(()=>{if(!qe||z)return;const Z=$e=>{$e.key==="Escape"&&($e.preventDefault(),Se())};return window.addEventListener("keydown",Z,!0),()=>window.removeEventListener("keydown",Z,!0)},[Se,qe,z]),at.useEffect(()=>{if(!St){Ve(!1);return}Ve(!0);const Z=window.setTimeout(()=>{Ve(!1)},1e4);return()=>window.clearTimeout(Z)},[St]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(Bu,{activeConv:r,agentCount:n.length,wsStatus:a,isConnected:i,conversations:te,hiddenConversations:w,onOpenHistory:c,onHideConversation:oe,onShowConversation:xt,onShowAllHidden:be,onResetPanelsToMain:q,notifications:E,notificationUnreadCount:ye,onOpenNotification:pt,onMarkNotificationRead:je,onMarkNotificationUnread:Q,onDeleteNotification:ke,inboxOpen:Ge,onInboxOpenChange:Ct,hiddenOpen:Ze,onHiddenOpenChange:Lt,onOpenNewSession:s?void 0:()=>tt(!0),actionShortcuts:H,onOpenRemote:()=>{!r||et(r)||Xe(r)||l(r)},onStopCli:u,activeCliViewMode:p,onSetCliViewMode:m}),e?t.jsx(of,{conversations:f,hiddenConversations:w,ides:k,actionLogs:T,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:v,isStandalone:h,userName:P,requestedActiveTabKey:y,onRequestedActiveTabConsumed:S,requestedMachineId:j,onRequestedMachineConsumed:g,requestedMobileSection:x,onRequestedMobileSectionConsumed:K,onOpenHistory:c,onOpenRemote:l,onStopCli:u,wsStatus:a,isConnected:i,onShowHiddenConversation:xt,onShowAllHiddenConversations:be,onOpenNewSession:()=>tt(!0),notificationStateBySessionId:he,onMarkNotificationTargetRead:He}):s?t.jsx(hf,{containerRef:I,isSplitMode:M,numGroups:L,groupSizes:O,groupedConvs:R,clearedTabs:N,ides:k,actionLogs:T,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:v,isStandalone:h,hasRegisteredMachines:pe.length>0,userName:P,focusedGroup:U,setFocusedGroup:G,moveTabToGroup:A,splitTabRelative:D,closeGroup:$,handleResizeStart:W,groupActiveTabIds:X,setGroupActiveTabIds:we,groupTabOrders:Le,setGroupTabOrders:ce,toggleHiddenTab:Ie,allowTabShortcuts:!1}):t.jsx(Tf,{visibleConversations:te,clearedTabs:N,ides:k,actionLogs:T,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:v,isStandalone:h,hasRegisteredMachines:pe.length>0,initialDataLoaded:C,userName:P,toggleHiddenTab:Ie,actionShortcuts:H,registerActionHandlers:Z=>{De.current=Z},notificationStateBySessionId:he,onActiveTabChange:xe,requestedActiveTabKey:ue,onRequestedActiveTabConsumed:ae,scrollToBottomRequest:se}),mt&&t.jsx(Bf,{machines:pe,conversations:f,ides:k,onClose:()=>tt(!1),onBrowseDirectory:J,onSaveWorkspace:de,onLaunchIde:ne,onLaunchProvider:ge,onListSavedSessions:me,sendDaemonCommand:d,onOpenConversation:Z=>{tt(!1),F(Z),xe(Z.tabKey)}}),qe&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:Se,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:Z=>Z.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Se,"aria-label":"Close dashboard guide",children:t.jsx(Nt,{size:14})})]}),t.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(Z=>t.jsx("button",{type:"button",className:`btn btn-sm ${lt===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>Je(Z.id),children:Z.label},Z.id))}),lt==="overview"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",ft?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),lt==="quickstart"&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),lt==="shortcuts"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(Z=>t.jsx("button",{type:"button",className:`btn btn-sm ${bt===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>kt(Z.id),children:Z.label},Z.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:We,children:"Disable all"}),t.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:Ce,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:Ue.map(Z=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${z===Z.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:Z.defaultShortcut})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:z===Z.id?V.length>0?`${V.join(" ")} ...`:"Listening...":H[Z.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{ee(Z.id),ve([])},children:z===Z.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const $e={...H};$e[Z.id]="",Ne($e)},children:"Disable"})]})]})},Z.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",ft?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:Be,className:`fixed right-4 bottom-24 z-40 hidden md:inline-flex items-center rounded-full border border-border-subtle bg-bg-primary/88 backdrop-blur py-2 text-xs text-text-secondary hover:text-text-primary transition-all ${le?"gap-2 px-2.5":"justify-center w-10 px-0"}`,style:{boxShadow:"0 6px 18px rgba(0,0,0,0.12)"},title:"Dashboard guide","aria-label":"Open dashboard guide",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-5 h-5 rounded-full bg-bg-secondary text-[11px] font-semibold text-text-primary shrink-0",children:"?"}),le&&t.jsx("span",{children:"Guide"})]})]})}const Ln=[{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 Ff({onClose:e}){const[s,r]=o.useState(0),n=Ln[s],a=s===Ln.length-1;return t.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.target===i.currentTarget&&e()},children:[t.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[t.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:t.jsx(Nt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Ln.map((i,c)=>t.jsx("div",{style:{width:c===s?24:8,height:8,borderRadius:4,background:c===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),t.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),t.jsxs("div",{style:{textAlign:"center"},children:[t.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[t.jsx("span",{children:n.icon})," ",n.title]}),t.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&t.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[t.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),t.jsxs("div",{className:"flex justify-between items-center mt-6",children:[t.jsx("button",{onClick:e,className:"btn btn-secondary border-none",children:"Skip"}),t.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})]})]}),t.jsx("style",{children:`
|
|
57
|
+
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
58
|
+
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
59
|
+
`})]})}function zf({hasExtensions:e,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?t.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[t.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:s}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",u=i.status==="generating";return t.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(i.tabKey),children:[t.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&t.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},i.tabKey)})]}):null}function Vf({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),u=o.useMemo(()=>Oi(s),[s]),p=o.useMemo(()=>e?wa(e,n,{machineNames:u,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,u,r]),m=o.useMemo(()=>p.find(b=>b.streamSource==="native"),[p]),f=o.useMemo(()=>p.filter(b=>b.streamSource==="agent-stream"),[p]),w=o.useMemo(()=>e?Kt(p,e.id):null,[p,e]);o.useEffect(()=>{i&&l(i)},[i]),o.useEffect(()=>{if(i||!w)return;const b=w.streamSource==="native"?"native":w.tabKey;!b||c===b||c==="native"&&l(b)},[c,w,i]),o.useEffect(()=>{var b;c!=="native"&&(f.some(v=>v.tabKey===c)||l(((b=f[0])==null?void 0:b.tabKey)||"native"))},[c,f]),o.useEffect(()=>{c==="native"&&(m||f[0]&&l(f[0].tabKey))},[c,m,f]);const k=o.useMemo(()=>c==="native"&&m?m:f.find(b=>b.tabKey===c)||w||m||f[0],[c,m,w,f]),T=o.useMemo(()=>f.map(b=>({tabKey:b.tabKey,title:Di(b)||a,status:b.status})),[f,a]),d=o.useCallback(b=>{if(b)return p.find(v=>Wr(v,{sessionId:b,routeId:b,tabKey:b,providerSessionId:b}))},[p]);return{activeChatTab:c,setActiveChatTab:l,activeConv:k,conversations:p,extensionTabs:T,hasExtensions:T.length>0,resolveConversationByTarget:d}}function Gf({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:u,isStandalone:p,userName:m,onOpenHistory:f,onConversationChange:w,onClose:k}){const[T,d]=o.useState("split"),[b,v]=o.useState(()=>Yt(e)?"native":e.tabKey),h=o.useRef(null),C=o.useMemo(()=>s||r.find(A=>A.id===e.routeId),[e.routeId,s,r]),P=o.useMemo(()=>ot((C==null?void 0:C.type)||""),[C==null?void 0:C.type]),{conversations:y,extensionTabs:S,hasExtensions:j}=Vf({ideData:C,allIdes:r,connectionStates:n,localUserMessages:i,ideName:P||"IDE",preferredTabKey:Yt(e)?void 0:e.tabKey}),g=o.useMemo(()=>C?Kt(y,C.id):null,[C,y]);o.useEffect(()=>{const A=h.current,D={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=D,!(A&&A.routeId===D.routeId&&A.tabKey===D.tabKey&&A.streamSource===D.streamSource)){if(Yt(e)){v("native");return}v(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(b==="native"){if(y.some(A=>A.streamSource==="native"))return;(g==null?void 0:g.streamSource)==="agent-stream"&&v(g.tabKey);return}if(!y.some(A=>A.tabKey===b)){if((g==null?void 0:g.streamSource)==="agent-stream"){v(g.tabKey);return}v("native")}},[y,b,g]);const x=o.useMemo(()=>b==="native"?y.find(A=>A.streamSource==="native")||e:y.find(A=>A.tabKey===b)||e,[e,y,b]),K=sc(x),I=o.useMemo(()=>K.status||K.modalMessage||K.modalButtons?{...x,...K.status?{status:K.status}:{},...K.modalMessage!==void 0?{modalMessage:K.modalMessage}:{},...K.modalButtons!==void 0?{modalButtons:K.modalButtons}:{}}:x,[x,K]),M=cr(I),L=sn({sendDaemonCommand:c,activeConv:I,setLocalUserMessages:l,setActionLogs:u,isStandalone:p}),{connScreenshot:O,screenshotUsage:R,handleRemoteAction:N}=gc({doId:M,targetSessionId:wi(I),connState:I.connectionState||"new",viewMode:T}),U=o.useMemo(()=>a.filter(A=>A.routeId===I.tabKey),[a,I.tabKey]);o.useEffect(()=>{w==null||w(I)},[I,w]),o.useEffect(()=>{const A=D=>{D.key==="Escape"&&k()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[k]);const G=o.useCallback(A=>{A.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:k,children:t.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:G,children:[t.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[t.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[t.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Tt,{size:16})}),t.jsx("span",{className:"truncate",children:ma(x)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:k,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(A=>{const D=T===A;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${D?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>d(A),title:A==="split"?"Split view":"Remote only",children:A==="split"?t.jsx(Il,{size:15}):t.jsx(Tt,{size:15})},A)})}),t.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),t.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>f(x),title:"Chat History",children:[t.jsx(aa,{size:14,className:"md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"History"})]}),t.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:k,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${T==="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:[T!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${T==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(zf,{hasExtensions:j,ideName:P||"IDE",activeChatTab:b,extensionTabs:S,onSelectTab:v}),t.jsx(li,{activeConv:I,onModalButton:L.handleModalButton}),t.jsx(Gn,{activeConv:I,ideEntry:C,showMetaChips:!1,handleSendChat:L.handleSendChat,isSendingChat:L.isSendingChat,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:U,userName:m})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${T==="split"?"order-1 md:order-2":""}`,children:t.jsx(ni,{addLog:()=>{},connState:I.connectionState||"new",connScreenshot:O,screenshotUsage:R,transportType:I.transport,onAction:N})})]})]})})}function qf({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=Du(e);return t.jsxs("div",{className:"fixed inset-0 z-[1400] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.jsxs("div",{role:"dialog","aria-modal":"true",className:"card fade-in relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[t.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",i,"?"]}),t.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:s?"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.":"This provider does not support graceful stop. Force Stop will end the runtime immediately."})]}),t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s&&t.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),t.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:"Force Stop"}),t.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Yf({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:a,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:u,onNewHistoryChat:p,onSwitchHistorySession:m,onRefreshHistory:f,onResumeSavedHistorySession:w,remoteDialogConv:k,remoteDialogIdeEntry:T,connectionStates:d,actionLogs:b,localUserMessages:v,sendDaemonCommand:h,setLocalUserMessages:C,setActionLogs:P,isStandalone:y,userName:S,onOpenRemoteHistory:j,onRemoteConversationChange:g,onCloseRemoteDialog:x,cliStopDialogOpen:K,cliStopTargetConv:I,onCancelCliStop:M,onStopCliNow:L,onSaveCliAndStop:O,toasts:R,onDismissToast:N,onClickToast:U,showOnboarding:G,onCloseOnboarding:A}){var W;const[D,$]=at.useState(()=>yt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(va,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:D,onSavedHistoryFiltersChange:$,onClose:u,onNewChat:p,onSwitchSession:m,onRefreshHistory:f,onResumeSavedSession:w}),k&&t.jsx(Gf,{activeConv:k,ideEntry:T,ides:r,connectionStates:d,actionLogs:b,localUserMessages:v,sendDaemonCommand:h,setLocalUserMessages:C,setActionLogs:P,isStandalone:y,userName:S,onOpenHistory:j,onConversationChange:g,onClose:x}),K&&I&&(et(I)||Xe(I))&&t.jsx(qf,{activeConv:I,canSaveAndStop:et(I)&&!Xe(I)&&!!((W=I.resume)!=null&&W.supported),onCancel:M,onStopNow:L,onSaveAndStop:O}),t.jsx(Wi,{toasts:R,onDismiss:N,onClickToast:U}),G&&t.jsx(Ff,{onClose:A})]})}function Xf({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:t.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[t.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:t.jsx(Bs,{size:14})}),t.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[t.jsxs("span",{children:[r?"Daemon update required":"Update available",s?t.jsxs(t.Fragment,{children:[": ",t.jsxs("strong",{children:["v",s]})]}):null]}),e.map(c=>{const l=At(c,{fallbackId:c.id}),u=n[c.id],p=c.version||c.daemonVersion||"unknown",m=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${m?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:l}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",p]}),m&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:m?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):t.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:m?"var(--status-danger)":"var(--status-warning)",background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${m?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:m?"Update now":"Upgrade"})]},c.id)})]}),!r&&t.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:t.jsx(Nt,{size:16})})]})}function Qf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Po(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Jf(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Zf(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function eh(){var Da,$a,Ea,Ka,Ba;const{sendCommand:e}=Mt(),s=lr(),r=sa(),n=Ks(),[a,i]=nl(),c=a.get("activeTab"),l=((Da=r.state)==null?void 0:Da.openRemoteForTabKey)||null,u=(($a=r.state)==null?void 0:$a.openMachineId)||null,p=((Ea=r.state)==null?void 0:Ea.mobileSection)||null,m=Li(),f=m.ides||[],w=m.initialLoaded??!0,{updateRouteChats:k,setToasts:T}=m,[d,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),v=m.toasts||[],h=m.wsStatus||"connected",C=m.isConnected??!0,P=m.connectionStates||{},y=m.showReconnected||!1,{groupAssignments:S,setGroupAssignments:j,focusedGroup:g,setFocusedGroup:x,groupActiveTabIds:K,setGroupActiveTabIds:I,groupTabOrders:M,setGroupTabOrders:L,groupSizes:O,setGroupSizes:R,isMobile:N,hasHydratedStoredLayout:U,hydrateStoredLayout:G}=mp(),[A,D]=o.useState(!1),[$,W]=o.useState(!1),[X,we]=o.useState(null),[Le,ce]=o.useState([]),[Ie,te]=o.useState(!1),[ue,ae]=o.useState(null),[xe]=o.useState(()=>ec()),[oe,F]=o.useState([]),[be,se]=o.useState({}),[pe,J]=o.useState({}),[de,ne]=o.useState({}),[ge,me]=o.useState(null),[E,ye]=o.useState(null),[he,je]=o.useState(null),Q=o.useRef(null);or("Dashboard",{ideCount:f.length,toastCount:v.length,focusedGroup:g,groupCount:Object.keys(S).length,localMessageTabs:Object.keys(be).length,actionLogCount:oe.length});const ke=f.find(fe=>fe.type==="adhdev-daemon"),He=o.useMemo(()=>f.filter(fe=>fe.type==="adhdev-daemon").sort(da),[f]),De=!!ke;o.useEffect(()=>{!ke||!(!ke.detectedIdes||!ke.availableProviders||!ke.recentLaunches||!ke.workspaces)||s(ke.id,{minFreshMs:3e4}).catch(()=>{})},[ke,s]);const Ge=(ke==null?void 0:ke.terminalBackend)||null,Qe=ke?At(ke,{fallbackId:ke.id}):null,Ze=(ke==null?void 0:ke.id)||null,ut=o.useMemo(()=>Om(f,pe),[f,pe]),{hiddenTabs:qe,hideTab:ht,toggleTab:mt,showTab:tt,showAllTabs:xt}=Wm(),{chatIdes:pt,conversations:le,visibleConversations:Ve,visibleTabKeys:lt,resolveConversationBySessionId:Je,resolveConversationByTarget:bt}=Zm({ides:ut,connectionStates:P,localUserMessages:be,clearedTabs:de,hiddenTabs:qe});Nu(le),o.useEffect(()=>{Object.keys(pe).length!==0&&J(fe=>Hm(fe,f))},[f,pe]);const kt=o.useMemo(()=>en(f),[f]),{notifications:St,unreadCount:Ct,notificationStateBySessionId:Lt,markRead:q,markUnread:Be,markTargetRead:Re,deleteNotification:ft}=Dp({conversations:le,liveSessionInboxState:kt}),B=o.useRef(null),{containerRef:H,normalizedGroupAssignments:z,numGroups:V,isSplitMode:ee,groupedConvs:ve,moveTabToGroup:Ne,closeGroup:Se,handleResizeStart:Ue,splitTabRelative:We}=vp({groupAssignments:S,setGroupAssignments:j,setFocusedGroup:x,setGroupActiveTabIds:I,setGroupTabOrders:L,groupSizes:O,setGroupSizes:R,isMobile:N,visibleConversations:Ve,visibleTabKeys:lt}),Ce=o.useMemo(()=>{var Me,Ae;if(!N){if(ge){const ie=le.find(ze=>ze.tabKey===ge);if(ie)return ie}return Ve[0]}const fe=K[g];if(fe){const ie=le.find(ze=>ze.tabKey===fe);if(ie)return ie}return((Me=ve[g])==null?void 0:Me[0])||((Ae=ve[0])==null?void 0:Ae[0])},[ge,N,K,g,le,ve,Ve]);o.useEffect(()=>{if(N){B.current=null;return}if(!(Ce!=null&&Ce.sessionId)){B.current=null;return}const fe=Or(Ce,kt),Me=ii(Ce),Ae=[Ce.tabKey,ir(Ce)||"",Ce.lastMessageHash||"",String(Ce.lastMessageAt||0),fe.inboxBucket,fe.unread?"1":"0"].join(":");if(B.current===Ae)return;const ie=()=>{if(document.visibilityState!=="visible"||B.current===Ae)return;B.current=Ae;const ze=Math.max(Date.now(),os(Ce),fe.lastUpdated||0);Re({...Me},ze),e(Ce.daemonId||Ce.routeId,"mark_session_seen",{sessionId:Ce.sessionId,seenAt:ze}).catch(()=>{})};if(document.visibilityState==="visible"){const ze=setTimeout(ie,1500),rt=()=>{document.visibilityState!=="visible"&&clearTimeout(ze)};return document.addEventListener("visibilitychange",rt),()=>{clearTimeout(ze),document.removeEventListener("visibilitychange",rt)}}else{const ze=()=>{document.visibilityState==="visible"&&(setTimeout(ie,800),document.removeEventListener("visibilitychange",ze))};return document.addEventListener("visibilitychange",ze),()=>{document.removeEventListener("visibilitychange",ze)}}},[Ce,N,kt,Re,e]);const{requestedDesktopTabKey:Z,requestedMobileTabKey:$e,consumeRequestedActiveTab:Fe}=ep({isMobile:N,urlActiveTab:c,resolveConversationBySessionId:Je,setSearchParams:i}),{remoteDialogConv:_,remoteDialogIdeEntry:Y,remoteDialogActiveConv:re,setRemoteDialogActiveConv:_e,openRemoteDialog:Te,closeRemoteDialog:Pe}=hp({isMobile:N,location:r,navigate:n,requestedRemoteTabTarget:l,requestedDesktopTabKey:Z,conversations:le,ides:f,resolveConversationByTarget:bt}),Ee=re||_||Ce,Ke=!!Ee&&et(Ee)&&!Xe(Ee),st=o.useMemo(()=>{if(!Ee||!Ke)return null;const fe=Ee.daemonId||Ee.routeId||"",Me=$t(Ee);return`${fe}:${Me}`},[Ee,Ke]),Vt=o.useMemo(()=>Ve,[Ve]),Zt=N&&xe==="chat",ur=o.useMemo(()=>le.filter(fe=>qe.has(fe.tabKey)),[le,qe]),es=o.useCallback(fe=>{const Me=new URLSearchParams(a);Me.set("activeTab",fe),i(Me,{replace:!0})},[a,i]),mr=o.useCallback(async(fe,Me)=>an(e,fe,Me),[e]),Lc=o.useCallback(async(fe,Me)=>{if(!Me.trim())return{ok:!1,error:"Choose a workspace path first."};try{const Ae=await e(fe,"workspace_add",{path:Me.trim()});return Ae!=null&&Ae.success?{ok:!0}:{ok:!1,error:(Ae==null?void 0:Ae.error)||"Could not save workspace"}}catch(Ae){return{ok:!1,error:Ae instanceof Error?Ae.message:"Could not save workspace"}}},[e]),_c=o.useCallback(async(fe,Me,Ae)=>{var ie;try{const ze={ideType:Me,enableCdp:!0};(ie=Ae==null?void 0:Ae.workspacePath)!=null&&ie.trim()&&(ze.workspace=Ae.workspacePath.trim());const rt=await e(fe,"launch_ide",ze);return!(rt!=null&&rt.success)&&(rt==null?void 0:rt.success)!==void 0?{ok:!1,error:(rt==null?void 0:rt.error)||"Could not launch IDE"}:(je({machineId:fe,kind:"ide",providerType:Me,workspacePath:(Ae==null?void 0:Ae.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(ze){return{ok:!1,error:ze instanceof Error?ze.message:"Could not launch IDE"}}},[e]),Rc=o.useCallback(async(fe,Me,Ae,ie)=>{var rt,Os,ys;const ze=Date.now();try{const It={cliType:Ae};(rt=ie==null?void 0:ie.workspacePath)!=null&&rt.trim()?It.dir=ie.workspacePath.trim():ie!=null&&ie.workspaceId&&(It.workspaceId=ie.workspaceId),(Os=ie==null?void 0:ie.resumeSessionId)!=null&&Os.trim()&&(It.resumeSessionId=ie.resumeSessionId.trim()),Array.isArray(ie==null?void 0:ie.cliArgs)&&ie.cliArgs.length>0&&(It.cliArgs=ie.cliArgs),(ys=ie==null?void 0:ie.initialModel)!=null&&ys.trim()&&(It.initialModel=ie.initialModel.trim());const gt=await e(fe,"launch_cli",It),_t=(gt==null?void 0:gt.result)||gt,Hs=(_t==null?void 0:_t.sessionId)||(_t==null?void 0:_t.id);return gt!=null&>.success&&Hs?(es(Hs),{ok:!0}):gt!=null&>.success?(je({machineId:fe,kind:Me,providerType:Ae,workspacePath:(ie==null?void 0:ie.workspacePath)||null,resumeSessionId:(ie==null?void 0:ie.resumeSessionId)||null,startedAt:ze}),{ok:!0}):{ok:!1,error:(gt==null?void 0:gt.error)||(_t==null?void 0:_t.error)||`Could not launch ${Me.toUpperCase()} session`}}catch(It){return Jf(It)?(je({machineId:fe,kind:Me,providerType:Ae,workspacePath:(ie==null?void 0:ie.workspacePath)||null,resumeSessionId:(ie==null?void 0:ie.resumeSessionId)||null,startedAt:ze}),{ok:!0}):{ok:!1,error:It instanceof Error?It.message:`Could not launch ${Me.toUpperCase()} session`}}},[es,e]),Pc=o.useCallback(async(fe,Me)=>{if(!fe||!Me)return[];try{const Ae=await e(fe,"list_saved_sessions",{providerType:Me,kind:"cli",limit:30}),ie=(Ae==null?void 0:Ae.result)??Ae;return Array.isArray(ie==null?void 0:ie.sessions)?ie.sessions:[]}catch(Ae){return console.error("List saved sessions failed",Ae),[]}},[e]);o.useEffect(()=>{if(!he)return;const fe=Po(he.workspacePath),Me=f.find(ie=>{var It,gt,_t,Hs;if(!ie||ie.type==="adhdev-daemon"||Qf(ie.daemonId||ie.id)!==he.machineId||(nr(ie)?"cli":Cs(ie)?"acp":"ide")!==he.kind||String(ie.agentType||ie.type||"")!==he.providerType)return!1;if(he.resumeSessionId)return String(ie.providerSessionId||"")===he.resumeSessionId;if(fe){const dn=Po(ie.workspace||ie.runtimeWorkspaceLabel);return dn?dn===fe:!1}return Number(ie.lastUpdated||ie._lastUpdate||ie.timestamp||((Hs=(_t=(gt=(It=ie.activeChat)==null?void 0:It.messages)==null?void 0:gt.at)==null?void 0:_t.call(gt,-1))==null?void 0:Hs.timestamp)||0)>=he.startedAt-5e3});if(!Me)return;const Ae=Si({entrySessionId:Me.sessionId,entryInstanceId:Me.instanceId,entryRouteId:Me.id,conversations:le});Ae&&(je(null),es(Ae))},[le,es,f,he]),o.useEffect(()=>{if(!he)return;const fe=window.setTimeout(()=>{je(Me=>!Me||Me.startedAt!==he.startedAt?Me:null)},45e3);return()=>window.clearTimeout(fe)},[he]),Um({visibleConversations:Ve,clearedTabs:de,setClearedTabs:ne,setActionLogs:F}),tp({ides:f,sendDaemonCommand:e,setToasts:T,setLocalUserMessages:se,resolveConversationByTarget:bt});const{isRefreshingHistory:Dc,handleRefreshHistory:$c}=xo({sendDaemonCommand:e,activeConv:Ce,chats:(Ka=f.find(fe=>fe.id===(Ce==null?void 0:Ce.routeId)))==null?void 0:Ka.chats,updateRouteChats:k,setToasts:T,setLocalUserMessages:se,setClearedTabs:ne}),{isCreatingChat:Ec,isRefreshingHistory:Kc,handleSwitchSession:Bc,handleNewChat:Wc,handleRefreshHistory:Oc}=xo({sendDaemonCommand:e,activeConv:Ee,chats:(Ba=f.find(fe=>fe.id===(Ee==null?void 0:Ee.routeId)))==null?void 0:Ba.chats,updateRouteChats:k,setToasts:T,setLocalUserMessages:se,setClearedTabs:ne}),ln=o.useCallback(async()=>{if(!(!Ee||!Ke||Ie)){te(!0);try{const fe=Ee.daemonId||Ee.routeId,Me=$t(Ee),Ae=await e(fe,"list_saved_sessions",{agentType:Me,providerType:Me,kind:"cli",limit:50}),ie=(Ae==null?void 0:Ae.result)??Ae;ce(Array.isArray(ie==null?void 0:ie.sessions)?ie.sessions:[])}catch(fe){console.error("Refresh saved sessions failed",fe),ce([])}finally{te(!1)}}},[Ee,Ie,Ke,e]);o.useEffect(()=>{if(!A){Q.current=null;return}if(!Ke){Q.current=null,ce([]),te(!1);return}!st||Ie||Q.current!==st&&(Q.current=st,ln())},[ln,A,Ie,Ke,st]);const Hc=o.useCallback(async fe=>{if(!Ee||!Ke||!fe.providerSessionId||!fe.workspace)return;const Me=Ee.daemonId||Ee.routeId,Ae=$t(Ee);try{ae(fe.providerSessionId);const ie=await e(Me,"launch_cli",{cliType:Ae,dir:fe.workspace,resumeSessionId:fe.providerSessionId,initialModel:pi(fe.summaryMetadata,"model",{preferShortValue:!0})||void 0}),ze=(ie==null?void 0:ie.result)??ie,rt=typeof(ze==null?void 0:ze.sessionId)=="string"?ze.sessionId:typeof(ze==null?void 0:ze.id)=="string"?ze.id:"";rt&&i(Os=>{const ys=new URLSearchParams(Os);return ys.set("activeTab",rt),ys},{replace:!0}),D(!1)}catch(ie){console.error("Resume saved session failed",ie)}finally{ae(null)}},[Ee,Ke,e,i]);fp({urlActiveTab:N&&!Zt?c:null,conversations:le,resolveConversationBySessionId:Je,normalizedGroupAssignments:z,hasHydratedStoredLayout:N&&!Zt?U:!0,hydrateStoredLayout:N&&!Zt?G:()=>{},setGroupActiveTabIds:I,setFocusedGroup:x,setSearchParams:i,historyModalOpen:A,activeConv:Ce,isRefreshingHistory:Dc,ides:f,handleRefreshHistory:$c});const La=o.useCallback(async(fe,Me)=>{const Ae=Me||X||Ce;if(!Ae||!et(Ae)&&!Xe(Ae))return;const ie=$t(Ae),ze=Ae.routeId||Ae.daemonId||"";try{await e(ze,"stop_cli",{cliType:ie,targetSessionId:Ae.sessionId,mode:fe})}catch(rt){console.error("Stop CLI failed:",rt)}},[Ce,X,e]),Uc=o.useCallback(async fe=>{const Me=fe||Ce;!Me||!et(Me)&&!Xe(Me)||(we(Me),W(!0))},[Ce]),Fc=o.useMemo(()=>!Ce||!et(Ce)||Xe(Ce)?null:Rs(Ce),[Ce]),zc=o.useCallback(async fe=>{if(!Ce||!et(Ce)||Xe(Ce))return;const Me=Rs(Ce);if(Me===fe)return;const Ae=Ce.sessionId;Ae&&J(ie=>({...ie,[Ae]:fe}));try{await e(Jt(Ce)||Ce.routeId,"set_cli_view_mode",{targetSessionId:Ce.sessionId,cliType:$t(Ce),mode:fe})}catch(ie){Ae&&J(ze=>{const rt={...ze};return Me===nc(f,Ae)?delete rt[Ae]:rt[Ae]=Me,rt}),Zf(ie)?console.warn("Skipped CLI view mode switch:",ie instanceof Error?ie.message:String(ie)):console.error("Failed to switch CLI view mode:",ie)}},[Ce,f,e]),{versionMismatchDaemons:Vc,hasRequiredVersionDaemons:_a,appVersion:Gc,versionBannerDismissed:qc,setVersionBannerDismissed:Yc,upgradingDaemons:Xc,handleBannerUpgrade:Qc}=wp({ides:f,sendDaemonCommand:e}),Ra=o.useCallback(fe=>{me(fe.tabKey),i(Me=>{const Ae=new URLSearchParams(Me),ie=Xd(fe);return ie?Ae.set("activeTab",ie):Ae.delete("activeTab"),Ae},{replace:!0})},[i]),Pa=o.useCallback(fe=>{tt(fe.tabKey),Ra(fe)},[Ra,tt]),Jc=o.useCallback(fe=>{ht(fe.tabKey)},[ht]);return t.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[t.jsx(Eu,{wsStatus:h,showReconnected:y}),t.jsx(Ku,{terminalBackend:Ge,isStandalone:De,machineLabel:Qe,machineKey:Ze}),(!qc||_a)&&t.jsx(Xf,{daemons:Vc,targetVersion:Gc,required:_a,upgradingDaemons:Xc,onUpgrade:Qc,onDismiss:()=>Yc(!0)}),t.jsx(Uf,{showMobileChatMode:Zt,isMobile:N,activeConv:Ce,chatIdes:pt,wsStatus:h,isConnected:C,onOpenHistory:fe=>{fe&&_e(fe),D(!0)},onOpenRemote:Te,onStopCli:Uc,activeCliViewMode:Fc,onSetActiveCliViewMode:zc,mobileChatConversations:Vt,ides:f,actionLogs:oe,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:F,isStandalone:De,initialDataLoaded:w,userName:m.userName,requestedMobileTabKey:$e,onRequestedMobileTabConsumed:Fe,requestedMachineId:u,onRequestedMachineConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:p,onRequestedMobileSectionConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},containerRef:H,isSplitMode:ee,numGroups:V,groupSizes:O,groupedConvs:ve,clearedTabs:de,focusedGroup:g,setFocusedGroup:x,moveTabToGroup:Ne,splitTabRelative:We,closeGroup:Se,handleResizeStart:Ue,groupActiveTabIds:K,setGroupActiveTabIds:I,groupTabOrders:M,setGroupTabOrders:L,toggleHiddenTab:mt,visibleConversations:Ve,hiddenConversations:ur,requestedDesktopTabKey:Z,onRequestedDesktopTabConsumed:Fe,onDesktopActiveTabChange:me,onHideConversation:Jc,onShowHiddenConversation:Pa,onShowAllHiddenConversations:xt,scrollToBottomRequest:E,machineEntries:He,onBrowseMachineDirectory:mr,onSaveMachineWorkspace:Lc,onLaunchMachineIde:_c,onLaunchMachineProvider:Rc,onListMachineSavedSessions:Pc,notifications:St,notificationUnreadCount:Ct,notificationStateBySessionId:Lt,onMarkNotificationRead:q,onMarkNotificationUnread:Be,onDeleteNotification:ft,onMarkNotificationTargetRead:Re}),t.jsx("style",{children:`
|
|
60
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
61
|
+
`}),t.jsx(Yf,{historyModalOpen:A,historyTargetConv:Ee,ides:f,isHistoryCreatingChat:Ec,isHistoryRefreshingHistory:Ke?!1:Kc,savedHistorySessions:Le,isSavedHistoryLoading:Ie,isResumingSavedHistorySessionId:ue,onCloseHistory:()=>D(!1),onNewHistoryChat:Wc,onSwitchHistorySession:Bc,onRefreshHistory:Ke?ln:Oc,onResumeSavedHistorySession:Hc,remoteDialogConv:_,remoteDialogIdeEntry:Y,connectionStates:P,actionLogs:oe,localUserMessages:be,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:F,isStandalone:De,userName:m.userName,onOpenRemoteHistory:fe=>{fe&&_e(fe),D(!0)},onRemoteConversationChange:_e,onCloseRemoteDialog:Pe,cliStopDialogOpen:$,cliStopTargetConv:X,onCancelCliStop:()=>{W(!1),we(null)},onStopCliNow:async()=>{W(!1),await La("hard",X),we(null)},onSaveCliAndStop:async()=>{W(!1),await La("save",X),we(null)},toasts:v,onDismissToast:fe=>T(Me=>Me.filter(Ae=>Ae.id!==fe)),onClickToast:fe=>{if(fe.targetKey){const Me=bt(fe.targetKey);Me&&(x(z.get(Me.tabKey)??0),Pa(Me),ye({tabKey:Me.tabKey,nonce:Date.now()}))}},showOnboarding:d,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function th({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[p,m]=o.useState(null),[f,w]=o.useState(!1),[k,T]=o.useState(null),[d,b]=o.useState(!1),[v,h]=o.useState(""),C=o.useRef(null),P=o.useCallback(A=>{C.current=A},[]),y=o.useCallback((A,D,$=!1)=>{c(W=>[...W.slice(-100),{timestamp:Date.now(),level:A,message:D}]),setTimeout(()=>{var W;return(W=a.current)==null?void 0:W.scrollIntoView({behavior:"smooth"})},100),$&&it.showToast(D,A==="error"||A==="warn"?"warning":"success")},[a]),S=o.useCallback(A=>{const D=A instanceof Error?A.message:String(A||"");return D.includes("P2P command timeout")||D.includes("P2P not connected")||D.includes("P2P not available")},[]),j=o.useCallback(async(A,D)=>{var $;if(!e||l)return!1;u(A),y("info",`Launching ${ot(A)}${D!=null&&D.workspace?` in ${D.workspace}`:""}...`);try{const W={ideType:A,enableCdp:!0};($=D==null?void 0:D.workspace)!=null&&$.trim()?W.workspace=D.workspace.trim():D!=null&&D.useDefaultWorkspace&&(W.useDefaultWorkspace=!0);const X=await r(e,"launch_ide",W);return y(X!=null&&X.success?"info":"error",X!=null&&X.success?`${ot(A)} launched`:`Failed: ${X==null?void 0:X.error}`,!0),!!(X!=null&&X.success)}catch(W){return y("error",`Launch error: ${W.message}`,!0),!1}finally{u(null)}},[e,l,y,r]),g=o.useCallback(async A=>{if(!e)return{success:!1};const{cliType:D,dir:$,workspaceId:W,useDefaultWorkspace:X,useHome:we,argsStr:Le,model:ce,resumeSessionId:Ie}=A;if(!D)return y("warn","Select a CLI or ACP provider first",!0),{success:!1};const te=Le?Le.split(/\s+/).filter(Boolean):void 0,ue=($==null?void 0:$.trim())||(W?"(saved id)":X?"(default workspace)":we?"(home)":"");y("info",`Launching ${D}${ue?` in ${ue}`:""}${ce?` (model: ${ce})`:""}...`),m(D);try{const ae={cliType:D,cliArgs:te,initialModel:ce||void 0};$!=null&&$.trim()?ae.dir=$.trim():W?ae.workspaceId=W:X?ae.useDefaultWorkspace=!0:we&&(ae.useHome=!0),Ie&&(ae.resumeSessionId=Ie);const xe=await r(e,"launch_cli",ae),oe=(xe==null?void 0:xe.result)||xe;return xe!=null&&xe.success?(y("info",`${D} launched`,!0),(oe==null?void 0:oe.launchSource)==="home"?y("info","📂 Running in home directory (explicit choice)"):(oe==null?void 0:oe.launchSource)==="defaultWorkspace"&&y("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:oe==null?void 0:oe.sessionId}):(y("error",`Failed: ${(xe==null?void 0:xe.error)||(oe==null?void 0:oe.error)}`,!0),(xe==null?void 0:xe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&T({cliType:D,argsStr:Le,model:ce}),{success:!1,sessionId:oe==null?void 0:oe.sessionId})}catch(ae){return S(ae)?(y("warn",`${D} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(y("error",`Launch error: ${ae.message}`,!0),{success:!1})}finally{m(null)}},[e,y,S,r]),x=o.useCallback(async(A,D,$,W)=>e?A?D.trim()?g({cliType:A,dir:D,argsStr:$,model:W}):(T({cliType:A,argsStr:$,model:W}),{success:!1}):(y("warn","Select a provider",!0),{success:!1}):{success:!1},[e,y,g]),K=o.useCallback(async(A,D,$)=>{if(e&&window.confirm(`Stop ${A}?
|
|
62
|
+
This will terminate the process.`))try{const W=await r(e,"stop_cli",{cliType:A,dir:D,targetSessionId:$});W!=null&&W.success?y("info",`${A} stopped`,!0):y("error",`Stop failed: ${(W==null?void 0:W.error)||"Unknown error"}`,!0)}catch(W){y("error",`Stop failed: ${W.message}`,!0)}},[e,y,r]),I=o.useCallback(async A=>{try{await r(A.daemonId,"restart_ide",{ideType:A.type}),y("info",`${ot(A.type)} restart initiated`,!0)}catch(D){y("error",`Restart failed: ${D.message}`,!0)}},[y,r]),M=o.useCallback(async A=>{if(window.confirm(`Stop ${ot(A.type)}?
|
|
63
|
+
This will disconnect CDP and optionally kill the process.`))try{const D=await r(A.daemonId,"stop_ide",{ideType:A.type,killProcess:!0});D!=null&&D.success?y("info",`${ot(A.type)} stopped`,!0):y("error",`Stop failed: ${(D==null?void 0:D.error)||"Unknown error"}`,!0)}catch(D){y("error",`Stop failed: ${D.message}`,!0)}},[y,r]),L=o.useCallback(async()=>{if(e)try{const A=await r(e,"detect_ides",{});y("info",`Found ${((A==null?void 0:A.result)||[]).length} IDE(s)`,!0)}catch(A){y("error",`Detection failed: ${A.message}`,!0)}},[e,y,r]),O=o.useCallback(async A=>{if(!e||!A.trim())return!1;w(!0);try{const D=await r(e,"workspace_add",{path:A.trim()});return D!=null&&D.success?(y("info",`Workspace added: ${A.trim()}`),!0):(y("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return y("error",D.message),!1}finally{w(!1)}},[e,y,r]),R=o.useCallback(async A=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){w(!0);try{const D=await r(e,"workspace_remove",{id:A});D!=null&&D.success?y("info","Workspace removed",!0):y("error",(D==null?void 0:D.error)||"workspace_remove failed",!0)}catch(D){y("error",D.message,!0)}finally{w(!1)}}},[e,y,r]),N=o.useCallback(async A=>{var D;if(e){w(!0);try{const $=await r(e,"workspace_set_default",A===null?{clear:!0}:{id:A});if($!=null&&$.success){y("info",A?"Default workspace updated":"Default workspace cleared",!0);const W=typeof $.defaultWorkspacePath=="string"?$.defaultWorkspacePath:"";W&&((D=C.current)==null||D.call(C,W))}else y("error",($==null?void 0:$.error)||"workspace_set_default failed",!0)}catch($){y("error",$.message,!0)}finally{w(!1)}}},[e,y,r]),U=o.useCallback(async A=>{var $;if(!e||!A.trim())return;const D=A.trim();w(!0);try{const W=await r(e,"workspace_set_default",{path:D});W!=null&&W.success?(y("info","Default workspace set from history"),($=C.current)==null||$.call(C,D)):y("error",(W==null?void 0:W.error)||"Could not set default (path missing on disk?)")}catch(W){y("error",W.message)}finally{w(!1)}},[e,y,r]),G=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:v}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:v})}catch(A){y("warn",`Live nickname updated, but account sync failed: ${A.message}`)}y("info",`Nickname set to "${v||"(cleared)"}"`),b(!1)}catch(A){y("error",`Failed: ${A.message}`)}},[e,v,s,y,n,r]);return{logs:i,launchingIde:l,launchingAgentType:p,workspaceBusy:f,launchPick:k,setLaunchPick:T,editingNickname:d,setEditingNickname:b,nicknameInput:v,setNicknameInput:h,addLog:y,handleLaunchIde:j,runLaunchCliCore:g,handleLaunchCli:x,handleStopCli:K,handleRestartIde:I,handleStopIde:M,handleDetectIdes:L,handleWorkspaceAdd:O,handleWorkspaceRemove:R,handleWorkspaceSetDefault:N,handleWorkspaceResumePath:U,handleSaveNickname:G,setOnDefaultWorkspaceChanged:P}}function sh({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var I;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:m}=i,[f,w]=o.useState(!1),[k,T]=o.useState(""),[d,b]=o.useState([]),[v,h]=o.useState(!1),[C,P]=o.useState(""),y=o.useCallback(async M=>{h(!0),P("");try{const L=await an(c,e,M);T(L.path),b(L.directories)}catch(L){P(L instanceof Error?L.message:"Could not load folder")}finally{h(!1)}},[e,c]),S=o.useCallback(()=>{w(!0);const M=[...r.map(O=>O.workspace),...n.map(O=>O.workspace),...a.map(O=>O.workspace)],L=nn(s.platform,rn(M,s.defaultWorkspacePath,(s.workspaces||[]).map(O=>O.path)));y(L)},[a,n,r,y,s.defaultWorkspacePath,s.platform,s.workspaces]),j=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,g=s.availableMem??s.freeMem??s.totalMem,x=j&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-g)/s.totalMem*100))):0,K=((I=s.loadavg)==null?void 0:I[0])||0;return t.jsxs("div",{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[t.jsx(xr,{icon:t.jsx(ei,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?dd(s.uptime):"Waiting…"}),t.jsx(xr,{icon:t.jsx(Tt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(xr,{icon:t.jsx(Qr,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(xr,{icon:t.jsx(Ml,{size:16}),label:"ACPs",value:`${a.length}`})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),t.jsxs("div",{className:"flex gap-6",children:[t.jsx(qa,{value:j?Math.min(Math.round(K/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:j?`${K.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(qa,{value:x,max:100,label:"Memory",color:"#3b82f6",detail:j?`${fn(s.totalMem-g)} / ${fn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${fn(s.totalMem)} total`})]})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[t.jsx(Ms,{size:14})," Workspaces"]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[t.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),t.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:l,value:s.defaultWorkspaceId||"",onChange:M=>void m(M.target.value===""?null:M.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(M=>t.jsx("option",{value:M.id,children:M.label||M.path},M.id))]}),s.defaultWorkspacePath&&t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:l,onClick:S,children:"Select workspace…"}),t.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&t.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(M=>t.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[M.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:tn(M.path,M.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:M.path,children:M.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void p(M.id),children:"Remove"})]},M.id))})]}),f&&t.jsx(on,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:d,busy:v,error:C,confirmLabel:"Add workspace",onClose:()=>w(!1),onNavigate:M=>{y(M)},onConfirm:M=>{(async()=>{if(!M)return;await u(M)&&w(!1)})()}})]})}function rh(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function nh(e,s,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=i;if(c.length===0)continue;const l=s.find(u=>u.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function _n(e){if(!e||typeof e!="object")return!1;const s=e;return(s.sourceMode==="normal"||s.sourceMode==="no-upstream")&&typeof s.disableUpstream=="boolean"&&(s.explicitProviderDir===null||typeof s.explicitProviderDir=="string")&&typeof s.userDir=="string"&&typeof s.upstreamDir=="string"&&Array.isArray(s.providerRoots)}function Do(e){if(!e||typeof e!="object")return null;if(_n(e))return e;const s=e,r=s.result;return _n(r)?r:_n(s.sourceConfig)?s.sourceConfig:null}function ah(e){const s=e.trim();return s||null}const $o=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],oh=[{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 ih({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,p]=o.useState([]),[m,f]=o.useState(""),[w,k]=o.useState([]),[T,d]=o.useState(""),b=o.useRef(null),v=o.useRef(null),h=g=>{p(x=>x.includes(g)?x.filter(K=>K!==g):[...x,g])},C=()=>p([...$o]),P=()=>p([]);o.useEffect(()=>{var g;(g=b.current)==null||g.scrollIntoView({behavior:"smooth"})},[w]),o.useEffect(()=>()=>{v.current&&clearInterval(v.current)},[]);const y=o.useCallback(()=>{v.current&&clearInterval(v.current),v.current=setInterval(async()=>{try{const g=await r(e,"provider_auto_fix_status",{providerType:s.type});(g==null?void 0:g.running)===!1&&a==="running"&&(i("done"),k(x=>[...x,`
|
|
64
|
+
✅ Auto-fix completed!`]),v.current&&clearInterval(v.current))}catch{}},3e3)},[e,s.type,r,a]),S=async()=>{if(u.length!==0){i("running"),k(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),d("");try{const g=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...m?{comment:m}:{}});g!=null&&g.success&&(g!=null&&g.started||g!=null&&g.running)?(k(x=>[...x,"✅ Agent started. Monitoring progress..."]),y()):(i("error"),d((g==null?void 0:g.error)||"Failed to start auto-fix"))}catch(g){i("error"),d((g==null?void 0:g.message)||"Connection failed")}}},j=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),k(g=>[...g,`
|
|
65
|
+
⚠️ Auto-fix cancelled.`]),i("done"),v.current&&clearInterval(v.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:oh.map(g=>t.jsxs("button",{onClick:()=>l(g.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===g.value?g.color+"66":"var(--border-subtle)",background:c===g.value?g.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===g.value?g.color:"var(--text-primary)"},children:g.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:g.desc})]},g.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:C,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:P,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:$o.map(g=>t.jsxs("button",{onClick:()=>h(g),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(g)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(g)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(g)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(g)?"☑ ":"☐ ",g]},g))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:m,onChange:g=>f(g.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[w.map((g,x)=>t.jsx("div",{className:g.startsWith("✅")?"text-green-400":"",style:g.startsWith("❌")||g.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:g},x)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:b})]}),T&&t.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:T})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&u.length>0&&`${u.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[a==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:S,disabled:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&t.jsx("button",{onClick:j,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),k([]),d("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function ch({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var y;const i=s.filter(S=>S.category==="ide"),[c,l]=o.useState(((y=i[0])==null?void 0:y.type)||""),[u,p]=o.useState(""),[m,f]=o.useState(""),[w,k]=o.useState(!1),[T,d]=o.useState(""),[b,v]=o.useState(!1),h=S=>{const j=S.toLowerCase().replace(/[^a-z0-9-]/g,"");p(j),(!m||m===C(u))&&f(C(j))},C=S=>S.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),P=async()=>{if(!(!u||!m||!c)){k(!0),d("");try{const S=await r(e,"provider_clone",{type:u,name:m,category:"ide",location:"user",cloneFrom:c});S!=null&&S.success||S!=null&&S.created?(v(!0),a==null||a(u)):d((S==null?void 0:S.error)||"Failed to create provider")}catch(S){d((S==null?void 0:S.message)||"Connection failed")}k(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:S=>S.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:b?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:u})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(S=>t.jsxs("button",{onClick:()=>l(S.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===S.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===S.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:S.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===S.type?"#a78bfa":"var(--text-secondary)"},children:S.displayName})]},S.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:u,onChange:S=>h(S.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",u||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:m,onChange:S=>f(S.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"})]}),T&&t.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:T})]})}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:b?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:P,disabled:!u||!m||w,className:"machine-btn",style:{background:u&&m?"rgba(34,197,94,0.12)":void 0,borderColor:u&&m?"rgba(34,197,94,0.3)":void 0,color:u&&m?"#86efac":void 0,opacity:!u||!m||w?.4:1},children:w?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function lh({machineId:e,providers:s,sendDaemonCommand:r}){var I;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[p,m]=o.useState("all"),[f,w]=o.useState(null),[k,T]=o.useState(!1),[d,b]=o.useState(null),[v,h]=o.useState("normal"),[C,P]=o.useState(""),[y,S]=o.useState(!1),j=o.useCallback(async()=>{if(e)try{const M=await r(e,"get_provider_source_config",{}),L=Do(M);L&&(b(L),h(L.sourceMode),P(L.explicitProviderDir||""))}catch{}},[e,r]),g=o.useCallback(async()=>{if(e){c(!0);try{const M=await r(e,"get_provider_settings",{}),L=rh(M);if(L){const O=nh(L,s);O.sort((R,N)=>R.category.localeCompare(N.category)||R.displayName.localeCompare(N.displayName)),a(O)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&g(),d||j()},[]);const x=async(M,L,O)=>{u(`${M}.${L}`),a(R=>R.map(N=>N.type===M?{...N,values:{...N.values,[L]:O}}:N));try{const R=await r(e,"set_provider_setting",{providerType:M,key:L,value:O});R!=null&&R.success||g()}catch{g()}u(null)},K=async()=>{S(!0);try{const M=await r(e,"set_provider_source_config",{providerSourceMode:v,providerDir:ah(C)}),L=Do(M);L?(b(L),h(L.sourceMode),P(L.explicitProviderDir||"")):await j(),await g()}catch{await j()}S(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(M=>t.jsx("button",{onClick:()=>m(M),className:`machine-btn text-[10px] px-2 py-0.5 ${p===M?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.toUpperCase()},M))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>T(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),t.jsx("button",{onClick:g,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick:j,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:v,onChange:M=>h(M.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:C,onChange:M=>P(M.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void K(),disabled:y,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:y?"Applying…":"Apply + Reload"})]}),t.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(d==null?void 0:d.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(d==null?void 0:d.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((I=d==null?void 0:d.providerRoots)==null?void 0:I.join(" → "))||"loading…"]})]})]}),p!=="all"&&n.filter(M=>M.category===p).length>1&&(()=>{const M=n.filter(N=>N.category===p),L=new Map;for(const N of M)for(const U of N.schema){if(U.type!=="boolean")continue;const G=L.get(U.key),A=!!(N.values[U.key]??U.default);G?(G.onCount+=A?1:0,G.total+=1):L.set(U.key,{label:U.label||U.key,onCount:A?1:0,total:1})}const O=[...L.entries()].filter(([,N])=>N.total===M.length);if(O.length===0)return null;const R=async(N,U)=>{for(const G of M)await x(G.type,N,U)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",p.toUpperCase()," providers (",M.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:O.map(([N,U])=>{const G=U.onCount===U.total,A=U.onCount===0;return t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:"text-text-secondary font-medium",children:U.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",U.onCount,"/",U.total,")"]}),t.jsx("button",{onClick:()=>void R(N,!0),disabled:G,className:`machine-btn text-[9px] px-1.5 py-px ${G?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void R(N,!1),disabled:A,className:`machine-btn text-[9px] px-1.5 py-px ${A?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},N)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(M=>p==="all"||M.category===p).map(M=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:M.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:M.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:M.category==="acp"?"rgba(139,92,246,0.08)":M.category==="cli"?"rgba(59,130,246,0.08)":M.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:M.category==="acp"?"#a78bfa":M.category==="cli"?"#60a5fa":M.category==="ide"?"#86efac":"var(--status-warning)"},children:M.category}),M.category==="ide"&&t.jsx("button",{onClick:()=>w(s.find(L=>L.type===M.type)||{type:M.type,name:M.displayName,displayName:M.displayName,icon:M.icon,category:M.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),t.jsx("div",{className:"flex flex-col gap-2",children:M.schema.map(L=>t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[L.label||L.key,l===`${M.type}.${L.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),L.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:L.description})]}),t.jsx("div",{className:"shrink-0",children:L.type==="boolean"?t.jsx("button",{onClick:()=>x(M.type,L.key,!(M.values[L.key]??L.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:M.values[L.key]??L.default?"#8b5cf6":"var(--border-subtle)"},children:t.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:M.values[L.key]??L.default?21:3}})}):L.type==="number"?t.jsx("input",{type:"number",value:Number(M.values[L.key]??L.default??0)||0,min:L.min,max:L.max,onChange:O=>{const R=parseInt(O.target.value)||0;L.min!==void 0&&R<L.min||L.max!==void 0&&R>L.max||x(M.type,L.key,R)},className:"machine-input w-20 text-center text-[11px]"}):L.type==="select"&&L.options?t.jsx("select",{value:String(M.values[L.key]??L.default??""),onChange:O=>x(M.type,L.key,O.target.value),className:"machine-input text-[11px]",children:L.options.map(O=>t.jsx("option",{value:O,children:O},O))}):t.jsx("input",{type:"text",value:String(M.values[L.key]??L.default??""),onBlur:O=>x(M.type,L.key,O.target.value),className:"machine-input w-[120px] text-[11px]"})})]},L.key))})]},M.type))}),f&&t.jsx(ih,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>w(null)}),k&&t.jsx(ch,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>T(!1),onCreated:()=>{T(!1),g()}})]})}const dh=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function uh({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function mh(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Eo(e){if(!e||Object.keys(e).length===0)return"";try{const s=JSON.stringify(e);return s.length>220?`${s.slice(0,220)}…`:s}catch{return"[unserializable payload]"}}function ph({machineId:e,sendDaemonCommand:s}){const[r,n]=o.useState([]),[a,i]=o.useState([]),[c,l]=o.useState([]),[u,p]=o.useState(0),[m,f]=o.useState(0),[w,k]=o.useState(!0),[T,d]=o.useState("debug"),[b,v]=o.useState("all"),h=o.useRef(null),C=o.useRef(!1),P=mh(a,b);return o.useEffect(()=>{if(!e||!w)return;const y=async()=>{try{const[j,g]=await Promise.all([s(e,"get_logs",{count:200,minLevel:T,since:u}),s(e,"get_debug_trace",uh({count:120,since:m,category:b}))]),x=(j==null?void 0:j.result)||j;if(j!=null&&j.success&&Array.isArray(x==null?void 0:x.logs)&&x.logs.length>0){n(M=>[...M,...x.logs.map(O=>({timestamp:O.ts,level:O.level,message:`[${O.category}] ${O.message}`}))].slice(-300));const I=Math.max(...x.logs.map(M=>M.ts));p(I)}const K=(g==null?void 0:g.result)||g;if(g!=null&&g.success&&Array.isArray(K==null?void 0:K.trace)){i(K.trace.slice(-120));const I=K.trace.reduce((M,L)=>Math.max(M,Number(L.ts||0)),m);I>m&&f(I)}}catch{}l(Ts.list({limit:120}))};y();const S=setInterval(y,3e3);return()=>clearInterval(S)},[e,w,u,m,T,b,s]),o.useEffect(()=>{if(w&&(r.length>0||a.length>0||c.length>0)){const y=C.current?"smooth":"instant";setTimeout(()=>{var S;(S=h.current)==null||S.scrollIntoView({behavior:y}),C.current=!0},50)}},[r.length,a.length,c.length,w]),o.useEffect(()=>{i([]),f(0)},[b]),t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-3",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Level"}),["debug","info","warn","error"].map(y=>t.jsx("button",{onClick:()=>{d(y),n([]),p(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${T===y?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.toUpperCase()},y))]}),t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsxs("span",{className:"text-[10px] text-text-muted",children:["logs=",r.length," trace=",P.length," web=",c.length]}),t.jsx("button",{onClick:()=>k(!w),className:`machine-btn ${w?"text-green-500 border-green-500/30":""}`,children:w?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>{n([]),i([]),l([]),p(0),f(0),Ts.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),r.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs..."}),r.map((y,S)=>t.jsxs("div",{className:"flex gap-2 py-px",style:{color:y.level==="error"?"#ef4444":y.level==="warn"?"var(--status-warning)":y.level==="debug"?"#64748b":"#94a3b8"},children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(y.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:y.level==="error"?"ERR":y.level==="warn"?"WRN":y.level==="debug"?"DBG":"INF"}),t.jsx("span",{children:y.message})]},`log-${S}`))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsxs("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",b==="session_host"?" · session_host only":""]}),t.jsx("div",{className:"flex gap-1 items-center",children:dh.map(y=>t.jsx("button",{onClick:()=>v(y.value),className:`machine-btn text-[10px] px-2 py-0.5 ${b===y.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:y.label},y.value))})]}),P.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:b==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),P.map(y=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(y.ts).toLocaleTimeString()}),t.jsx("span",{children:y.level.toUpperCase()}),t.jsxs("span",{children:[y.category,".",y.stage]}),y.interactionId&&t.jsxs("span",{children:["ix=",y.interactionId]})]}),t.jsx("div",{children:Eo(y.payload)})]},y.id))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[160px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),c.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No browser debug events captured yet."}),c.map(y=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(y.ts).toLocaleTimeString()}),t.jsx("span",{children:y.kind}),y.topic&&t.jsxs("span",{children:["topic=",y.topic]}),y.interactionId&&t.jsxs("span",{children:["ix=",y.interactionId]})]}),t.jsx("div",{children:Eo(y.payload)})]},y.id))]})]}),t.jsx("div",{ref:h})]})}function Rn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Pn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ko(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function fh(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function hh(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 xh(e){var r;const s=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const i=`${n.providerType}::${n.workspace}::${a}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function bh({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),p=tc(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),m=p.diagnostics,f=p.loading,w=p.applyDiagnostics,k=o.useMemo(()=>Rf({diagnostics:m,loading:f,refreshing:l,error:n}),[m,f,l,n]),T=o.useMemo(()=>new Map(s.map(I=>[I.sessionId||I.id,I])),[s]),d=o.useCallback(async()=>{if(e){u(!0);try{const I=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),M=Rn(I);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Could not load hosted runtime diagnostics");w(M.diagnostics||M.result||null),a("")}catch(I){const M=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";a(M)}finally{u(!1)}}},[w,e,r]);o.useEffect(()=>{!e||m||f||l||d()},[m,f,e,d,l]);const b=o.useCallback(async(I,M)=>{const L=`${I}:${M.sessionId}`;if(!(I==="session_host_stop_session"&&!window.confirm(`Stop ${M.displayName}?
|
|
66
|
+
This will terminate the hosted runtime.`))){c(L);try{const O=await r(e,I,{sessionId:M.sessionId}),R=Rn(O);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Session host action failed");const N=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";it.showToast(`Session host ${N}: ${M.displayName}`,"success"),await d()}catch(O){const R=O instanceof Error?O.message:"Session host action failed";it.showToast(R,"warning"),a(R)}finally{c(O=>O===L?null:O)}}},[e,d,r]),v=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
67
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const M=await r(e,"session_host_prune_duplicate_sessions",{}),L=Rn(M);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Duplicate prune failed");const O=L.result||{},R=Array.isArray(O.prunedSessionIds)?O.prunedSessionIds.length:0,N=typeof O.duplicateGroupCount=="number"?O.duplicateGroupCount:0;it.showToast(`Pruned ${R} duplicate runtime(s) across ${N} group(s)`,"success"),await d()}catch(M){const L=M instanceof Error?M.message:"Duplicate prune failed";it.showToast(L,"warning"),a(L)}finally{c(M=>M==="session_host_prune_duplicate_sessions"?null:M)}}},[e,d,r]),h=o.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((I,M)=>(M.lastActivityAt||0)-(I.lastActivityAt||0)),[m==null?void 0:m.sessions]),C=o.useMemo(()=>m!=null&&m.liveRuntimes||m!=null&&m.recoverySnapshots||m!=null&&m.inactiveRecords?{liveRuntimes:(m==null?void 0:m.liveRuntimes)||[],recoverySnapshots:(m==null?void 0:m.recoverySnapshots)||[],inactiveRecords:(m==null?void 0:m.inactiveRecords)||[]}:Ac(h),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,h]),P=C.liveRuntimes,y=C.recoverySnapshots,S=C.inactiveRecords,j=o.useMemo(()=>xh(P),[P]),g=o.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),x=o.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[m==null?void 0:m.recentLogs]),K=(I,M)=>{var $;const L=i===`session_host_resume_session:${I.sessionId}`,O=i===`session_host_restart_session:${I.sessionId}`,R=i===`session_host_stop_session:${I.sessionId}`,N=Ma(I.meta),U=T.get(I.sessionId),G=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,A=M==="recovery"?"Recover":"Resume",D=Tc(M);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:I.displayName||(U==null?void 0:U.cliName)||I.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${hh(I.lifecycle)}`,children:I.lifecycle}),N&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:N})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:I.workspaceLabel||(U==null?void 0:U.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:(($=I.writeOwner)==null?void 0:$.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:fh(I.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(na,{size:11})," ",G]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Ko(I.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",D]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[M==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_resume_session",I)},children:L?`${A}ing…`:A}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",I)},children:O?"Restarting…":"Restart"}),M==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{b("session_host_stop_session",I)},children:R?"Stopping…":"Stop"})]})]})},I.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(Ut,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:zu()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{v()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${k.toneClass}`,children:k.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:f||l,children:[t.jsx(Bs,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!m&&t.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(hs,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),m&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:y.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:m.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Ko(m.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Pn(m.hostStartedAt)})]})]}),x&&t.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(hs,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:x.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Pn(x.timestamp),x.sessionId?` · ${x.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Qr,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:As("live")}),P.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:P.map(I=>K(I,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Ut,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:As("recovery")}),y.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):t.jsx("div",{className:"space-y-2",children:y.map(I=>K(I,"recovery"))})]}),S.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:As("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:S.map(I=>K(I,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),g.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:g.map(I=>{var L;const M=h.find(O=>O.sessionId===I.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(M==null?void 0:M.displayName)||((L=T.get(I.sessionId))==null?void 0:L.cliName)||I.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:Pn(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:m.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function gh({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return t.jsx("div",{className:"fixed inset-0 z-[100] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:t.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>t.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),n({cliType:s.cliType,workspaceId:i.id,argsStr:s.argsStr,model:s.model})},children:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Dn({icon:e,children:s}){return t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,t.jsx("span",{children:s})]})}function $n({children:e,className:s=""}){return t.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:e})}function yh({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),m=Zs(e,"0.8.72");return t.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[l.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Dn,{icon:t.jsx(Ft,{size:13}),children:"Current Chats"}),t.jsx($n,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const w=Un(f);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>c(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:ct(f)}),w>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Zr(w)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:bs(f)})]},f.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Dn,{icon:t.jsx(ei,{size:13}),children:"Recent Launches"}),t.jsx($n,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const{metaText:w,updatedLabel:k}=pc(f);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),k&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:k})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:w})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Dn,{icon:t.jsx(hs,{size:13}),children:"Daemon Update"}),t.jsx($n,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:m?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),t.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[t.jsx(Bs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function vh(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const wh={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 Tr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function jh(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function En({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const m=Ks(),{handleLaunchIde:f,handleStopCli:w,handleRestartIde:k,handleStopIde:T,handleDetectIdes:d,launchingIde:b,launchingAgentType:v,addLog:h}=c,[C,P]=o.useState(null),y=o.useCallback(_=>{_&&m(Xt(_))},[m]),S=wh[e],j=e==="ide",g=e==="acp",x=o.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),K=o.useMemo(()=>new Map(x.map(_=>[_.type,_.displayName||_.type])),[x]),[I,M]=o.useState(""),[L,O]=o.useState(""),[R,N]=o.useState([]),[U,G]=o.useState(""),[A,D]=o.useState(""),[$,W]=o.useState([]),[X,we]=o.useState(!1),[Le,ce]=o.useState(""),[Ie,te]=o.useState(!1),[ue,ae]=o.useState(()=>yt()),[xe,oe]=o.useState(null),[F,be]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[se,pe]=o.useState(p||""),[J,de]=o.useState([]),[ne,ge]=o.useState(!1),[me,E]=o.useState(""),[ye,he]=o.useState([]),[je,Q]=o.useState(!1),[ke,He]=o.useState(""),De=o.useRef(null),[Ge,Qe]=o.useState(null),Ze=o.useRef("__home__"),[ut,qe]=o.useState("__home__"),[ht,mt]=o.useState(!1),tt=o.useRef(0),xt=J.filter(_=>!a.some(Y=>Y.type===_&&wt(Y.status)!=="stopped")),pt=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!F&&be(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){be("__custom__"),pe(p);return}u&&(be(u),pe(""))},[u,p]),o.useEffect(()=>{j||I&&(x.some(_=>_.type===I)||(M(""),D("")))},[x,j,I]);const le=(()=>{if(F==="__custom__")return se.trim();if(!F)return"";const _=(s.workspaces||[]).find(Y=>Y.id===F);return(_==null?void 0:_.path)||""})(),Ve=o.useCallback(_=>{const Y=pt.current[_];Y&&(clearTimeout(Y),delete pt.current[_]),de(re=>re.includes(_)?re.filter(_e=>_e!==_):re)},[]),lt=o.useRef(new Set),Je=o.useCallback(async _=>{if(l){Q(!0),He("");try{const Y=await an(l,r,_);E(Y.path),pe(Y.path),he(Y.directories)}catch(Y){He(Y instanceof Error?Y.message:"Could not load folder")}finally{Q(!1)}}},[r,l]),bt=o.useCallback(()=>{if(!l)return;be("__custom__"),ge(!0);const _=a.map(re=>re.workspace),Y=nn(s.platform,rn(se.trim(),le,p,_,s.defaultWorkspacePath,(s.workspaces||[]).map(re=>re.path)));Je(Y)},[se,p,Je,s.defaultWorkspacePath,s.platform,s.workspaces,a,le,l]),kt=o.useCallback(_=>{const Y=String(_.workspace||"").trim();if(!Y)return;const re=(s.workspaces||[]).find(_e=>Tr(_e.path)===Tr(Y));if(re){be(re.id),pe("");return}be("__custom__"),pe(Y)},[s.workspaces]),St=o.useCallback(_=>{const Y=String(_.workspace||"").trim();if(!Y)return{workspaceId:null,workspacePath:"",useHome:!0};const re=(s.workspaces||[]).find(_e=>Tr(_e.path)===Tr(Y));return re?{workspaceId:re.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Y,useHome:!1}},[s.workspaces]),Ct=o.useCallback(async _=>{if(!l||!_||e!=="cli"){W([]),we(!1),ce("");return}const Y=tt.current+1;tt.current=Y,we(!0),ce("");try{const re=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(tt.current!==Y)return;const _e=(re==null?void 0:re.result)??re;W(Array.isArray(_e==null?void 0:_e.sessions)?_e.sessions:[])}catch(re){if(tt.current!==Y)return;W([]),ce(re instanceof Error?re.message:"Could not load saved sessions")}finally{tt.current===Y&&we(!1)}},[e,r,l]),Lt=o.useMemo(()=>{if(e!=="cli"||!I)return null;const _=K.get(I)||I;return{routeId:r,daemonId:r,providerSessionId:A||void 0,transport:"pty",mode:"chat",agentName:_,agentType:I,status:"idle",title:_,messages:[],ideType:I,workspaceName:le,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${I}`}},[e,r,K,le,A,I]),q=o.useCallback(_=>{if(e==="ide"||!_){N([]);return}N(Cc(r,_))},[e,r]);o.useEffect(()=>{if(D(""),q(I),e!=="cli"||!I){W([]),ce(""),we(!1);return}Ct(I)},[e,q,Ct,I]);const Be=o.useMemo(()=>$.find(_=>_.providerSessionId===A)||null,[$,A]);o.useEffect(()=>{if(!A)return;const _=$.find(Y=>Y.providerSessionId===A);_!=null&&_.canResume||D("")},[$,A]);const Re=o.useCallback((_,Y)=>{De.current=Y,Ze.current=_.selectedWorkspaceKey||"__home__",qe(_.selectedWorkspaceKey||"__home__"),Qe(_)},[]),ft=o.useCallback(()=>{De.current&&(mt(!0),De.current().finally(()=>{De.current=null,mt(!1),Qe(null)}))},[]),B=o.useCallback(_=>{if(!_)return;de(re=>re.includes(_)?re:[...re,_]);const Y=pt.current[_];Y&&clearTimeout(Y),pt.current[_]=setTimeout(()=>{de(re=>re.includes(_)?re.filter(_e=>_e!==_):re),delete pt.current[_]},2e4)},[]);o.useEffect(()=>{for(const Y of a)wt(Y.status)!=="stopped"&&(J.includes(Y.type)&&!lt.current.has(Y.type)&&(lt.current.add(Y.type),h("info",`${K.get(Y.type)||Y.type} launched`,!0)),Ve(Y.type));const _=new Set(a.filter(Y=>wt(Y.status)!=="stopped").map(Y=>Y.type));lt.current.forEach(Y=>{!J.includes(Y)&&!_.has(Y)&<.current.delete(Y)})},[h,Ve,a,J,K]),o.useEffect(()=>()=>{Object.values(pt.current).forEach(clearTimeout),pt.current={}},[]);const[H,z]=o.useState({}),[V,ee]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const Y=await l(r,"get_ide_extensions",{}),re=(Y==null?void 0:Y.result)||Y;re!=null&&re.success&&(re!=null&&re.ideExtensions)&&z(re.ideExtensions)}catch{}})()},[j,r,l]);const ve=_=>j?ot(_.type):e==="cli"?_.cliName:_.acpName,Ne=j?s.detectedIdes||[]:[],Se=o.useCallback(async _=>{const Y=(_==null?void 0:_.type)||I,re=(_==null?void 0:_.workspacePath)??le;if(j){await f(Y,re?{workspace:re}:void 0)&&B(Y);return}const _e=await c.runLaunchCliCore({cliType:Y,dir:_!=null&&_.workspaceId?void 0:re||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!re,argsStr:(_==null?void 0:_.argsStr)??(L||void 0),model:(_==null?void 0:_.model)??(g&&U||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!g&&e==="cli"&&Y===I&&A||void 0});if(_e.success||_e.pending){const Te=(_==null?void 0:_.argsStr)??L;!j&&(Te!=null&&Te.trim())&&(Ic(r,Y,Te),q(Y)),B(Y),_e.success&&_e.sessionId&&y(_e.sessionId)}},[c,f,g,j,L,U,q,B,r,y,le,A,I]),Ue=Ki(j?"ide":g?"acp":"cli",!j&&!g&&!!A),We=Bi(j?"ide":g?"acp":"cli",!j&&!g&&!!A),Ce=()=>{var Te;const _=j?ot(I):K.get(I)||I,Y=!j&&!g&&!!A,{options:re,selectedKey:_e}=ps({machine:s,currentWorkspaceId:F&&F!=="__custom__"?F:null,currentWorkspacePath:le});Re({title:Y?ga(_):ls("start-fresh",_),description:Y?ya():ds("start-fresh"),confirmLabel:Ue,busyLabel:We,workspaceOptions:re,selectedWorkspaceKey:_e,details:[{label:"Mode",value:S.label},{label:"Provider",value:_},...!j&&e==="cli"&&A?[{label:"Resume",value:((Te=$.find(Pe=>Pe.providerSessionId===A))==null?void 0:Te.title)||A}]:[],...!j&&L.trim()?[{label:"Arguments",value:L.trim()}]:[],...g&&U.trim()?[{label:"Model",value:U.trim()}]:[]]},async()=>{const Pe=re.find(Ee=>Ee.key===Ze.current);Pe!=null&&Pe.workspaceId?(be(Pe.workspaceId),pe("")):Pe!=null&&Pe.workspacePath?(be("__custom__"),pe(Pe.workspacePath)):(be(""),pe("")),await Se({workspaceId:(Pe==null?void 0:Pe.workspaceId)??null,workspacePath:(Pe==null?void 0:Pe.workspacePath)??"",useHome:!(Pe!=null&&Pe.workspaceId)&&!(Pe!=null&&Pe.workspacePath)})})},Z=_=>{j?T(_):w(_.type,_.workspace,_.id)},$e=o.useCallback(async(_,Y,re=!1)=>{if(_.mode===Y){re&&_.sessionId&&y(_.sessionId);return}if(!l||!_.sessionId){re&&_.sessionId&&y(_.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:Y}),re&&y(_.sessionId)}catch(_e){jh(_e)?console.warn("Skipped CLI view mode switch:",_e instanceof Error?_e.message:String(_e)):console.error("Failed to switch CLI view mode:",_e)}},[r,y,l]),Fe=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:F,onChange:_=>{const Y=_.target.value;if(be(Y),Y==="__custom__"&&l){bt();return}Y!=="__custom__"&&pe("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(_=>t.jsxs("option",{value:_.id,children:[_.id===s.defaultWorkspaceId?"⭐ ":"",tn(_.path,_.label)]},_.id)),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),F==="__custom__"&&(l?t.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:bt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:se,onChange:_=>pe(_.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:F==="__custom__"?le?t.jsx("span",{className:"font-mono truncate block",title:le,children:le}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":le?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:F===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:le,children:le})]}):"No workspace selected. This launches in the home directory."})]});return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${S.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",S.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?Ne.length>0?Ne.map(_=>{const Y=a.find(Ee=>(Ee.type||"").toLowerCase()===(_.type||"").toLowerCase()&&wt(Ee.status)!=="stopped"),re=_.running||!!Y,_e=!!Y&&Y.cdpConnected,Te=J.includes(_.type||_.id||""),Pe=I===(_.type||"");return t.jsxs("button",{onClick:()=>{if(_e&&Y){const Ee=Y.sessionId;Ee?m(Xt(Ee),{state:{openRemoteForTabKey:Ee}}):m("/dashboard",{state:{openRemoteForTabKey:Y.id}});return}Te||M(Ee=>Ee===(_.type||"")?"":_.type||"")},disabled:!!b||Te,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${_e?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Pe?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:b&&b!==_.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(_.type)}),re&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${_e?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.name||ot(_.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${_e?"text-green-400":Te?"text-orange-400":Pe?"text-accent-primary":"text-text-muted"}`,children:_e?"Open Session":Te?"Starting...":Pe?"Configure":"Select"})]})]},_.type)}):t.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",t.jsxs("button",{onClick:d,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[t.jsx(Nl,{size:14})," Scan System"]})]}):x.length>0?x.map(_=>{const Y=I===_.type,re=J.includes(_.type),Te=!!a.find(Pe=>Pe.type===_.type&&wt(Pe.status)!=="stopped");return t.jsxs("button",{onClick:()=>M(Pe=>Pe===_.type?"":_.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Y?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:_.icon}),Te&&t.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${re?"text-orange-400":Y?"text-accent-primary":"text-text-muted"}`,children:re?"Starting...":Y?"Configure":"Select"})]})]},_.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),I&&(j?Ne.find(_=>_.type===I):x.find(_=>_.type===I))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?ot(I):K.get(I)||I})]}),Fe,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!g&&e==="cli"&&t.jsx(Mc,{busy:!!v||!!b||J.includes(I),savedSessionsLoading:X,savedSessionsError:Le,selectedSession:Be,onRefresh:()=>void Ct(I),onOpenHistory:()=>{I&&(te(!0),Ct(I))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[g&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:U,onChange:_=>G(_.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:L,onChange:_=>O(_.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"}),R.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:R.map(_=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>O(_),title:_,children:_},_))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Ce,disabled:!!v||!!b||J.includes(I),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:v===I||b===I?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+J.filter(_=>!a.some(Y=>Y.type===_&&wt(Y.status)!=="stopped")).length,")"]}),a.length===0&&xt.length===0?t.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",S.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[xt.map(_=>t.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(_)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?ot(_):K.get(_)||_}),t.jsx("div",{className:"text-[11px] text-text-muted",children:v===_?"Launching process...":"Waiting for process and session to register..."})]})]}),t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${_}`)),a.map(_=>{const Y=j?_:null,re=!j&&!g?_:null,_e=wt(_.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(_.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[ve(_),(Y==null?void 0:Y.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Y.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:_.workspace||"—"}),(re==null?void 0:re.mode)&&t.jsx("span",{className:re.mode==="chat"?"text-violet-400":"text-text-secondary",children:re.mode==="chat"?"Chat view":"Terminal view"})]}),re&&(re.runtimeKey||re.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[re.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",re.runtimeKey]}),t.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Te;(Te=navigator.clipboard)==null||Te.writeText(`adhdev attach ${re.runtimeKey}`),P(re.runtimeKey||null),window.setTimeout(()=>{P(Pe=>Pe===re.runtimeKey?null:Pe)},1200)},children:C===re.runtimeKey?"Copied":"Copy"})]}),re.runtimeWriteOwner&&t.jsx("span",{style:{color:re.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:re.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:vh(re.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${_e==="stopped"?"bg-red-500/[0.08] text-red-500":_e==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:_e}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Te=_.sessionId;if(Te){m(Xt(Te),{state:{openRemoteForTabKey:Te}});return}m("/dashboard",{state:{openRemoteForTabKey:_.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:t.jsx(Tt,{size:13})}),t.jsx("button",{onClick:()=>{const Te=_.workspace||"",{options:Pe,selectedKey:Ee}=ps({machine:s,currentWorkspacePath:Te});Re({title:ls("restart-ide",ot(_.type)),description:ds("restart-ide"),confirmLabel:$s("restart-ide"),busyLabel:Es("restart-ide"),workspaceOptions:Pe,selectedWorkspaceKey:Ee,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ot(_.type)}]},async()=>{const Ke=Pe.find(Vt=>Vt.key===Ze.current),st=(Ke==null?void 0:Ke.workspacePath)??"";if(st&&st!==Te){await Se({type:_.type,workspacePath:st});return}await k(_)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:t.jsx(Bs,{size:14})})]}),g&&t.jsx("button",{onClick:()=>{const Te=_.sessionId;Te&&y(Te)},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:!_.sessionId,children:t.jsx(Ft,{size:14})}),re&&_e!=="stopped"&&t.jsxs(t.Fragment,{children:[re.mode&&t.jsx(ha,{mode:re.mode,onChange:Te=>void $e(re,Te,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Te=_.sessionId;Te&&y(Te)},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:!_.sessionId,children:re.mode==="chat"?t.jsx(Ft,{size:14}):t.jsx(Tt,{size:13})})]}),_e==="stopped"?t.jsx("button",{onClick:()=>{const Te=_.workspace||"",Pe=j?ot(_.type):ve(_),{options:Ee,selectedKey:Ke}=ps({machine:s,currentWorkspacePath:Te});Re({title:ls("restart-stopped",Pe),description:ds("restart-stopped"),confirmLabel:$s("restart-stopped"),busyLabel:Es("restart-stopped"),workspaceOptions:Ee,selectedWorkspaceKey:Ke,details:[{label:"Mode",value:S.label},{label:"Provider",value:Pe}]},async()=>{const st=Ee.find(Vt=>Vt.key===Ze.current);await Se({type:_.type,workspaceId:(st==null?void 0:st.workspaceId)??null,workspacePath:(st==null?void 0:st.workspacePath)??"",useHome:!(st!=null&&st.workspaceId)&&!(st!=null&&st.workspacePath)})})},disabled:J.includes(_.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:J.includes(_.type)?"⏳":t.jsx(oa,{size:14})}):t.jsx("button",{onClick:()=>Z(_),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:t.jsx(Nt,{size:14})})]})]}),Y&&Y.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Y.aiAgents.map(Te=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${di(Te.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Te.name," · ",wt(Te.status)]},Te.id))}),Y&&(H[Y.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(H[Y.type]||[]).map(Te=>t.jsxs("button",{disabled:V===`${Y.type}.${Te.type}`,onClick:async()=>{const Pe=`${Y.type}.${Te.type}`;ee(Pe);try{await l(r,"set_ide_extension",{ideType:Y.type,extensionType:Te.type,enabled:!Te.enabled}),z(Ee=>({...Ee,[Y.type]:(Ee[Y.type]||[]).map(Ke=>Ke.type===Te.type?{...Ke,enabled:!Ke.enabled}:Ke)}))}catch(Ee){console.error("Extension toggle failed:",Ee)}finally{ee(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 ${Te.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Te.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Te.name,t.jsx("span",{className:"text-[9px] font-normal",children:Te.enabled?"ON":"OFF"})]},Te.type))})]})]},_.id)})]}),ne&&l&&t.jsx(on,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:me,directories:ye,busy:je,error:ke,confirmLabel:"Use this folder",onClose:()=>ge(!1),onNavigate:_=>{Je(_)},onConfirm:_=>{pe(_),be("__custom__"),ge(!1)}}),Ge&&t.jsx(Aa,{title:Ge.title,description:Ge.description,details:Ge.details,workspaceOptions:Ge.workspaceOptions,selectedWorkspaceKey:ut,onWorkspaceChange:_=>{Ze.current=_,qe(_)},confirmLabel:Ge.confirmLabel,busyLabel:Ge.busyLabel,busy:ht,onConfirm:ft,onCancel:()=>{De.current=null,Qe(null)}}),Ie&&Lt&&t.jsx(va,{activeConv:Lt,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:$,isSavedSessionsLoading:X,isResumingSavedSessionId:xe,savedHistoryFilters:ue,onSavedHistoryFiltersChange:ae,onClose:()=>te(!1),onNewChat:()=>{D(""),te(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Ct(I)},onResumeSavedSession:_=>{if(!_.canResume||xe)return;const Y=St(_);D(_.providerSessionId),kt(_),oe(_.providerSessionId),te(!1),Se({type:_.providerType,workspaceId:Y.workspaceId,workspacePath:Y.workspacePath,useHome:Y.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{oe(re=>re===_.providerSessionId?null:re)})}})]})}const Bo=[{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 kh({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:p,initialWorkspacePath:m,sendDaemonCommand:f}){var d;const[w,k]=o.useState(u);o.useEffect(()=>{k(u)},[u]);const T=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Bo.map(b=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${w===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>k(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${w===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:T[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=Bo.find(b=>b.id===w))==null?void 0:d.helper})]}),w==="ide"&&t.jsx(En,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),w==="cli"&&t.jsx(En,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),w==="acp"&&t.jsx(En,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m})]})}function Sh({onNicknameSynced:e}={}){var F,be,se,pe,J,de,ne,ge,me;const{id:s}=al(),r=Ks(),n=sa(),{sendCommand:a}=Mt(),i=lr(),c=Li(),l=c.ides||[],u=c.initialLoaded??!0,p=l.find(E=>E.id===s&&E.type==="adhdev-daemon"),m=l.some(E=>E.type==="adhdev-daemon"),[f,w]=o.useState("workspace"),[k,T]=o.useState("ide"),d=o.useRef(null),[b,v]=o.useState(null),h=o.useRef("__home__"),[C,P]=o.useState("__home__"),[y,S]=o.useState(!1),j=o.useRef(null);o.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),$m(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:15e3});const g=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=th({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>it.onToast(ye=>{c.setToasts(je=>{if(je.some(He=>He.message===ye.message&&ye.timestamp-He.timestamp<3e3))return je;const ke={id:ye.id,message:ye.message,type:ye.type,timestamp:ye.timestamp,targetKey:ye.targetKey,actions:ye.actions};return[...je.slice(-4),ke]});const he=ye.duration||5e3;setTimeout(()=>c.setToasts(je=>je.filter(Q=>Q.id!==ye.id)),he)}),[c]);const K=(p==null?void 0:p.availableProviders)||[],I={};for(const E of K)I[E.type]=E.icon;const M=E=>I[E]||"",L=p?{id:p.id,hostname:ui(p,{fallbackId:p.id}),platform:((F=p.machine)==null?void 0:F.platform)||"unknown",arch:((be=p.machine)==null?void 0:be.arch)||"",cpus:((se=p.machine)==null?void 0:se.cpus)||0,totalMem:((pe=p.machine)==null?void 0:pe.totalMem)||0,freeMem:(J=p.machine)==null?void 0:J.freeMem,availableMem:(de=p.machine)==null?void 0:de.availableMem,loadavg:(ne=p.machine)==null?void 0:ne.loadavg,uptime:(ge=p.machine)==null?void 0:ge.uptime,release:((me=p.machine)==null?void 0:me.release)||"",cdpConnected:!!p.cdpConnected,machineNickname:p.machineNickname||null,p2p:p.p2p?{screenshotActive:!1,...p.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:p.detectedIdes||[],workspaces:p.workspaces||[],defaultWorkspaceId:p.defaultWorkspaceId??p.activeWorkspaceId??null,defaultWorkspacePath:p.defaultWorkspacePath??p.activeWorkspacePath??null}:null,O=l.filter(E=>E.daemonId===s&&E.type!=="adhdev-daemon").filter(E=>!nr(E)&&!Cs(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,version:E.version||"",instanceId:E.instanceId||"",status:E.status,workspace:E.workspace||null,terminals:E.terminals||0,aiAgents:bd(E.aiAgents||(E.agents||[]).map(ye=>({id:ye.name,name:ye.name,status:ye.status,version:ye.version}))),activeChat:E.activeChat||null,chats:E.chats||[],childSessions:E.childSessions||[],cdpConnected:E.cdpConnected||!1,daemonId:s})),R=l.filter(E=>E.daemonId===s&&nr(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,cliName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,mode:E.mode,runtimeKey:E.runtimeKey,runtimeDisplayName:E.runtimeDisplayName,runtimeWorkspaceLabel:E.runtimeWorkspaceLabel,runtimeWriteOwner:E.runtimeWriteOwner||null,runtimeAttachedClients:E.runtimeAttachedClients||[],daemonId:s})),N=l.filter(E=>E.daemonId===s&&Cs(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,acpName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,daemonId:s})),U=p?At(p,{fallbackId:s}):"",G="workspace",A=n.state,D=A==null?void 0:A.initialMachineTab,$=A==null?void 0:A.initialWorkspaceCategory,W=A==null?void 0:A.initialWorkspaceId,X=A==null?void 0:A.initialWorkspacePath,we=D==="ides"||D==="clis"||D==="acps"?"workspace":D||G,Le=D==="ides"?"ide":D==="clis"?"cli":D==="acps"?"acp":$,ce=[...O.map(E=>{var ye,he,je,Q,ke;return{id:`ide:${E.type}:${E.workspace||""}`,label:((ye=E.activeChat)==null?void 0:ye.title)||E.type,kind:"ide",providerType:E.type,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((ke=(Q=(je=(he=E.activeChat)==null?void 0:he.messages)==null?void 0:je.at)==null?void 0:Q.call(je,-1))==null?void 0:ke.timestamp)||0}}),...R.map(E=>{var ye,he,je,Q,ke;return{id:`cli:${E.type}:${E.workspace||""}`,label:((ye=E.activeChat)==null?void 0:ye.title)||E.cliName,kind:"cli",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((ke=(Q=(je=(he=E.activeChat)==null?void 0:he.messages)==null?void 0:je.at)==null?void 0:Q.call(je,-1))==null?void 0:ke.timestamp)||0}}),...N.map(E=>{var ye,he,je,Q,ke;return{id:`acp:${E.type}:${E.workspace||""}`,label:((ye=E.activeChat)==null?void 0:ye.title)||E.acpName,kind:"acp",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:xs(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((ke=(Q=(je=(he=E.activeChat)==null?void 0:he.messages)==null?void 0:je.at)==null?void 0:Q.call(je,-1))==null?void 0:ke.timestamp)||0}})].sort((E,ye)=>(ye.lastLaunchedAt||0)-(E.lastLaunchedAt||0)),Ie=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(E=>({id:E.id,label:E.title||E.providerName||E.providerType,kind:E.kind,providerType:E.providerType,providerSessionId:E.providerSessionId,subtitle:xs(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace,summaryMetadata:E.summaryMetadata,lastLaunchedAt:E.lastLaunchedAt})):ce,te=o.useMemo(()=>{var ye;const E=((ye=c.connectionStates)==null?void 0:ye[s||""])||void 0;return l.filter(he=>he.daemonId===s&&he.type!=="adhdev-daemon").flatMap(he=>wa(he,{},{connectionStates:s&&E?{[s]:E}:void 0,defaultConnectionState:E})).filter(he=>!(he.transport==="pty"&&he.mode==="terminal")).sort((he,je)=>Un(je)-Un(he))},[l,c.connectionStates,s]),ue=o.useCallback(E=>{const ye=pa(E);ye&&r(Xt(ye))},[r]),ae=o.useCallback(()=>{d.current&&(S(!0),d.current().finally(()=>{d.current=null,S(!1),v(null)}))},[]),xe=o.useCallback(E=>{if(!L)return;const{options:ye,selectedKey:he}=ps({machine:L,currentWorkspacePath:E.workspace}),je=async()=>{T(E.kind),w("workspace")};d.current=async()=>{const Q=ye.find(De=>De.key===h.current),ke=(Q==null?void 0:Q.workspacePath)??null,He=(Q==null?void 0:Q.workspaceId)??null;if(E.kind==="ide"&&E.providerType){await x.handleLaunchIde(E.providerType,ke?{workspace:ke}:void 0);return}if((E.kind==="cli"||E.kind==="acp")&&E.providerType){await x.runLaunchCliCore({cliType:E.providerType,dir:He?void 0:ke||"",workspaceId:He||void 0,model:E.kind==="acp"&&pi(E.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:E.providerSessionId});return}await je()},h.current=he,P(he),v({title:E.kind==="ide"?ls("restart-ide",E.label):E.providerSessionId?ga(E.label):ls("start-fresh",E.label),description:E.kind==="ide"?ds("restart-ide"):E.providerSessionId?ya():ds("start-fresh"),confirmLabel:E.kind==="ide"?$s("restart-ide"):E.providerSessionId?Fr(!0):$s("start-fresh"),busyLabel:E.kind==="ide"?Es("restart-ide"):E.providerSessionId?xa(!0):Es("start-fresh"),workspaceOptions:ye,details:[{label:"Mode",value:E.kind.toUpperCase()},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]})},[x,L]);if(o.useEffect(()=>{w(we)},[G,we,s]),o.useEffect(()=>{Le&&T(Le)},[Le,s]),!L)return u?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:g,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const oe=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tt,{size:14})," Workspace"]}),count:O.length+R.length+N.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ut,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Xr,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Cl,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(kl,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:g,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[x.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:x.nicknameInput,onChange:E=>x.setNicknameInput(E.target.value),onKeyDown:E=>{E.key==="Enter"&&x.handleSaveNickname(),E.key==="Escape"&&x.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),t.jsx("button",{onClick:x.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),t.jsx("button",{onClick:()=>x.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):t.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{x.setEditingNickname(!0),x.setNicknameInput(L.machineNickname||"")},title:"Click to set nickname",children:U}),t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),t.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[L.platform," · ",L.arch]}),t.jsxs("span",{children:[L.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),L.p2p.available&&t.jsxs("span",{children:["P2P ",L.p2p.state==="connected"?"connected":L.p2p.state]}),L.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:L.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:oe.map(E=>t.jsxs("button",{onClick:()=>w(E.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===E.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[E.label,E.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===E.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:E.count})]},E.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[f==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(yh,{machineEntry:p,providers:K,recentLaunches:Ie,currentConversations:te,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:xe,onOpenConversation:ue}),t.jsx(kh,{machine:L,machineId:s,providers:K,ideSessions:O,cliSessions:R,acpSessions:N,actions:x,getIcon:M,initialCategory:k,initialWorkspaceId:W,initialWorkspacePath:X,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(lh,{machineId:s,providers:K,sendDaemonCommand:a}),f==="overview"&&t.jsx(sh,{machineId:s,machine:L,ideSessions:O,cliSessions:R,acpSessions:N,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(bh,{machineId:s,cliSessions:R,sendDaemonCommand:a}),f==="logs"&&t.jsx(ph,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&L&&t.jsx(gh,{machine:L,launchPick:x.launchPick,actions:x}),b&&t.jsx(Aa,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:E=>{h.current=E,P(E)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:y,onConfirm:ae,onCancel:()=>{d.current=null,v(null)}}),t.jsx(Wi,{toasts:c.toasts||[],onDismiss:E=>c.setToasts(ye=>ye.filter(he=>he.id!==E)),onClickToast:E=>{E.targetKey&&r(Xt(E.targetKey))}}),t.jsx("style",{children:`
|
|
68
|
+
@keyframes toast-in {
|
|
69
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
70
|
+
to { opacity: 1; transform: translateX(0); }
|
|
71
|
+
}
|
|
72
|
+
`})]})}class Nh{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,a){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const a=this.runtimeListeners.get(s);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return;const n=await fetch(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const a=await n.json();this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof a.seq=="number"?a.seq:0,text:typeof a.text=="string"?a.text:"",truncated:!!a.truncated,cols:typeof a.cols=="number"?a.cols:void 0,rows:typeof a.rows=="number"?a.rows:void 0})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Wt=new Nh;function Ch(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=new URLSearchParams(window.location.search).get("token");return n?`${s}?token=${encodeURIComponent(n)}`:s}const Mr=Ch(),Wo=3e3,Ih=3e4;let Bt=null,Ah=0;const Yr=new Map;let rs=null,tr=null;function Oo(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function qs(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function Th(e){return e==="connected"?"connected":e}async function Er(e,s,r){const n=rm(e,r||{}),a=Bt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++Ah}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Yr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Yr.set(i,{resolve:p=>{clearTimeout(u),c(p)},reject:p=>{clearTimeout(u),l(p)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function Zn(e,s){const r=Bt;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class Mh{constructor(s){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Bt==null?void 0:Bt.readyState)===WebSocket.OPEN}get connectionState(){return(Bt==null?void 0:Bt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Er(this.daemonId,s,r)}async sendInput(s,r){return Er(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,rs&&(clearInterval(rs),rs=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Er(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());Wt.emitScreenshot(this.daemonId,a)}}catch{}};r(),rs=setInterval(r,2e3)}stopScreenshots(s){rs&&(clearInterval(rs),rs=null)}}let Pt=null;function Lh(e){return(!Pt||Pt.daemonId!==e)&&(Pt=new Mh(e)),Pt}function _h({children:e}){const s=o.useRef(Br()),r=Br();s.current=r;const{setUserName:n}=fs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((d,b)=>{l(d),tr==null||tr(d,b)},[]),p=o.useRef(null),m=o.useRef(),f=o.useRef(Wo),w=o.useRef(!0),k=o.useRef(!1),T=o.useRef("initial_connect");return o.useEffect(()=>{w.current=!0,k.current=!1;function d(){var h,C;if(!w.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((C=p.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Mr}...`),qs("connect_attempt",{url:Mr,reason:T.current,delayMs:f.current});let v;try{v=new WebSocket(Mr)}catch(P){console.error("[Standalone WS] Failed to create WebSocket:",P),b();return}p.current=v,v.onopen=()=>{if(!w.current){v.close();return}u("connected"),f.current=Wo,qs("open",{url:Mr,reason:T.current}),Qt.resubscribeAll({sendData:Zn}),console.log("[Standalone WS] Connected")},Bt=v,v.onmessage=P=>{var y,S;try{const j=JSON.parse(P.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const g=Yr.get(j.requestId);g&&(Yr.delete(j.requestId),j.type==="error"?g.reject(new Error(((y=j.data)==null?void 0:y.message)||"Command failed")):g.resolve(j.data));return}if(j.type==="session_output"){const g=j.sessionId||j.cliId||j.cliType;g&&Wt.emitSessionOutput(g,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Wt.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated);return}if(j.type==="topic_update"){const g=j.update;g&&Qt.publish(g);return}if(j.type==="status"||j.type==="initial_state"){const g=j.data;if(!g)return;const{injectEntries:x,markLoaded:K,getIdes:I}=s.current,M=g.instanceId||"standalone",L=I().find(N=>N.id===M),O=Lh(M);Wt.register(M,O),Wt.setState(M,"connected"),u("connected",M),Wt.emitStatus(M,g);const R=Ur(g,{daemonId:M,existingDaemon:L,existingEntries:I()});Oo("ws_status",{type:j.type,daemonId:M,sessions:(g.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:(g.recentLaunches||[]).map(N=>({id:N.id,providerType:N.providerType,kind:N.kind,workspace:N.workspace,lastLaunchedAt:N.lastLaunchedAt}))}),Oo("entries",{daemonId:M,entries:R.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}))}),R.length>0&&x(R,{authoritativeDaemonIds:[M]}),K(),c.current!==M&&((S=i.current)==null||S.call(i),c.current=M,i.current=Qt.subscribe({sendData:Zn},M,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${M}`,params:{includeSessions:!0}},N=>{if(N.topic!=="daemon.metadata")return;const U=s.current.getIdes(),G=U.find(D=>D.id===M),A=Ur(N.status,{daemonId:M,existingDaemon:G,existingEntries:U,timestamp:N.timestamp});A.length>0&&s.current.injectEntries(A),N.userName&&a.current&&a.current(N.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},v.onclose=P=>{w.current&&(Pt==null||Pt.stopScreenshots(),Pt&&Wt.setState(Pt.daemonId,"disconnected"),u("disconnected"),p.current=null,T.current=`close:${P.code}${P.wasClean?":clean":":unclean"}`,qs("close",{code:P.code,reason:P.reason||"",wasClean:P.wasClean}),b())},v.onerror=P=>{k.current||!w.current||(T.current="error",qs("error",{message:P instanceof Event?"event":String(P),readyState:v.readyState}),console.warn("[Standalone WS] Error, will reconnect:",P))}}function b(){if(!w.current)return;clearTimeout(m.current);const v=f.current;console.log(`[Standalone WS] Reconnecting in ${v}ms...`),qs("schedule_reconnect",{reason:T.current,delayMs:v}),m.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,Ih),d()},v)}return d(),()=>{var v;w.current=!1,k.current=!0,(v=i.current)==null||v.call(i),i.current=null,c.current=null,clearTimeout(m.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,Bt=null),Pt&&(Pt.stopScreenshots(),Wt.unregister(Pt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Rh({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(tr=(c,l)=>{r(c),l&&a(l)},()=>{tr=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=Th(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(hl,{connectionOverrides:i,children:t.jsx(_h,{children:e})})}const Ph=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Yo,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Ut,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Xr,{}),label:"Settings"}];function Dh({children:e}){const s=Ks(),r=sa(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=m=>{s(m),a(!1)},u=()=>{c(m=>{const f=!m;try{localStorage.setItem("sidebar-collapsed",f?"1":"0")}catch{}return f})},p=m=>`nav-item${r.pathname.startsWith(m)?" active":""} cursor-pointer ${i?"justify-center py-2.5 px-0":""}`;return t.jsxs("div",{className:`app-layout${n?" mobile-menu-open":""}${i?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:()=>a(!0),children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),n&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:()=>a(!1),onKeyDown:m=>m.key==="Escape"&&a(!1)}),t.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>a(!1),children:t.jsx(Nt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:Ph.map(m=>t.jsxs("div",{className:p(m.path),id:`nav-${m.id}`,onClick:()=>l(m.path),title:i?m.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:m.icon}),!i&&m.label]},m.id))}),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":""}`,id:"nav-docs",onClick:()=>window.open("https://docs.adhf.dev","_blank"),title:i?"Docs":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(Xo,{})}),!i&&t.jsxs(t.Fragment,{children:["Docs",t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]})]}),t.jsxs("div",{className:`nav-item cursor-pointer${r.pathname==="/about"?" active":""} ${i?"justify-center py-2.5 px-0":""}`,id:"nav-about",onClick:()=>s("/about"),title:i?"About":void 0,children:[t.jsx("span",{className:"nav-icon",children:t.jsx(Qo,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.72"]}),t.jsx(xm,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:u,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const $h=[{icon:t.jsx(Ut,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Ft,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Jo,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Tt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(rr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Xo,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Eh=[{icon:t.jsx(Tl,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Yo,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Jr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(jl,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(na,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Sl,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Kh=[{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 Bh(){return t.jsxs(Vi,{icon:t.jsx(Qo,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.8.72"]}),children:[t.jsx(Dt,{children:t.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),t.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:"Keep the same dashboard experience, with the runtime fully on-device."}),t.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers."})]}),t.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"Docs ↗"}),t.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:"GitHub ↗"}),t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:"Try Cloud ↗"})]})]})}),t.jsx(Dt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:$h.map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Dt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Ui.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:zi.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Fi.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:s},s))})]},e.label))})}),t.jsx(Dt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:Eh.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Dt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:t.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-bg-secondary",children:[t.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),t.jsx("tbody",{children:Kh.map((e,s)=>t.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[t.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?t.jsx("span",{className:"text-emerald-500",children:"✓"}):t.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:t.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),t.jsx(Gi,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:t.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),t.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[t.jsx(Bl,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Wh(){const{ides:e}=fs(),s=e.find(f=>f.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Mt(),{userName:a}=fs(),[i,c]=o.useState(a||"");o.useEffect(()=>{a!==void 0&&c(a)},[a]);const l=f=>{const w=f.target.value.trim();s!=null&&s.id&&w!==a&&n(s.id,"set_user_name",{userName:w}).catch(console.error)},[u,p]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),m=f=>{p(f);try{localStorage.setItem("adhdev_sound",f?"1":"0")}catch{}};return t.jsxs(Vi,{icon:t.jsx(Xr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(dm,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),t.jsx(Dt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.8.72"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"WebSocket"}),t.jsx("span",{className:"font-mono text-xs",children:"ws://localhost:19222"}),t.jsx("span",{className:"text-text-muted",children:"HTTP"}),t.jsx("span",{className:"font-mono text-xs",children:"http://localhost:19280"})]})}),t.jsx(Dt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(f=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${f.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:f.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:f.type})]},f.type))})}),t.jsx(Dt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(vm,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Dt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode and theme.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(Sm,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),t.jsx(_m,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),t.jsx(Pm,{})]})]})}),t.jsx(Dt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(bm,{}),t.jsx(ns,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Kl,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:u,onChange:m})]})}),t.jsx(Dt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(wl,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:f=>c(f.target.value),onBlur:l,onKeyDown:f=>{f.key==="Enter"&&f.currentTarget.blur()}})]})})})]})}hm();Mm();const Oh=Go({baseUrl:""});function Ho(){const{ides:e,initialLoaded:s}=fs();if(!s)return t.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?t.jsx(Wn,{to:`/machines/${r.id}`,replace:!0}):t.jsx(Wn,{to:"/dashboard",replace:!0})}function Hh(){const e=o.useMemo(()=>({sendCommand:Er,sendData:Zn}),[]);return t.jsx(ol,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(gl,{client:Oh,children:t.jsx(Rh,{children:t.jsx(vl,{value:e,children:t.jsx(Dh,{children:t.jsxs(il,{children:[t.jsx(ts,{path:"/dashboard",element:t.jsx(eh,{})}),t.jsx(ts,{path:"/machine",element:t.jsx(Ho,{})}),t.jsx(ts,{path:"/machines/:id",element:t.jsx(Sh,{})}),t.jsx(ts,{path:"/machines",element:t.jsx(Ho,{})}),t.jsx(ts,{path:"/about",element:t.jsx(Bh,{})}),t.jsx(ts,{path:"/settings",element:t.jsx(Wh,{})}),t.jsx(ts,{path:"*",element:t.jsx(Wn,{to:"/dashboard",replace:!0})})]})})})})})})}Lu({connectionManager:Wt});cl(document.getElementById("root")).render(t.jsx(Hh,{}));
|