@adhdev/daemon-standalone 0.8.86 → 0.8.88
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 +74 -18
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/{index-C01OH_JA.js → index-i2SMIomG.js} +23 -23
- package/public/index.html +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-2SYILvaH.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var ld=Object.defineProperty;var dd=(e,s,r)=>s in e?ld(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Ye=(e,s,r)=>dd(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as Ta,a as La,b as $i,c as Ki,u as Vs,R as at,d as pr,t as ud,e as md,D as pd,f as ua,g as ma,h as _a,i as fd,k as hd,B as xd,l as bd,m as cs,N as pa,n as gd}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 yd(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 Ks=yd();function Ao(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 vd(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function wd(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 ar(e,s){const r=vd(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:wd(e.activeChat,s==null?void 0:s.activeChat),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),summaryMetadata:e.summaryMetadata??(s==null?void 0:s.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash),unread:e.unread??(s==null?void 0:s.unread),lastSeenAt:e.lastSeenAt??(s==null?void 0:s.lastSeenAt),inboxBucket:e.inboxBucket??(s==null?void 0:s.inboxBucket),completionMarker:e.completionMarker??(s==null?void 0:s.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(s==null?void 0:s.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(s==null?void 0:s.surfaceHidden),resume:e.resume??(s==null?void 0:s.resume),runtimeKey:e.runtimeKey??(s==null?void 0:s.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(s==null?void 0:s.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(s==null?void 0:s.runtimeWorkspaceLabel)}}function Mo(e,s){if(!(s!=null&&s.length))return e;if(!(e!=null&&e.length))return s;const r=new Map(e.map(n=>[n.id,n]));return s.map(n=>{const a=r.get(n.id);return a?ar(n,a):n})}const Bi=o.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0}),Oi=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function To(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 Pn(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 on(e){return Array.isArray(e)?e.map(on):!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,on(r)]))}function jd(e,s){try{return JSON.stringify(on(e))===JSON.stringify(on(s))}catch{return!1}}function Lr(e,s,r){return jd(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function kd(e,s,r){var u,p,m,f,g,w,A;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 y=To(d),h=To(b);if(y>h){const S=(u=d.chats)!=null&&u.length?d.chats:b.chats,_=Mo(b.childSessions,d.childSessions),k=Pn(b,d,{...b,...d,chats:S,childSessions:_,_lastUpdate:n});i.set(d.id,Lr(b,k,n))}else if(y<h){const S={};if(d.status&&d.status!==b.status&&(S.status=d.status),d.cdpConnected!==void 0&&(S.cdpConnected=d.cdpConnected),(p=d.chats)!=null&&p.length&&!((m=b.chats)!=null&&m.length)&&(S.chats=d.chats),d.machineNickname!==void 0&&d.machineNickname!==b.machineNickname&&(S.machineNickname=d.machineNickname),d.version!==void 0&&(S.version=d.version),d.serverVersion!==void 0&&(S.serverVersion=d.serverVersion),d.versionMismatch===!0&&(S.versionMismatch=!0),Object.keys(S).length>0){const _=Pn(b,d,{...b,...S,_lastUpdate:b._lastUpdate});i.set(d.id,Lr(b,_,n))}else Lr(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const S=d.timestamp||n,_=b._lastUpdate||b.timestamp||0;if(S>=_){const k=(f=d.chats)!=null&&f.length?d.chats:b.chats,I=Mo(b.childSessions,d.childSessions),j=Pn(b,d,{...b,...d,chats:k,childSessions:I,_lastUpdate:n});i.set(d.id,Lr(b,j,n))}else(g=d.chats)!=null&&g.length&&!((w=b.chats)!=null&&w.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||((A=d.id)==null?void 0:A.split(":")[0]);b&&l.add(b)}for(const[d,b]of i){const y=b.daemonId||d.split(":")[0];if(!l.has(y))continue;if(a.has(y)&&!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 Sd(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 Nd({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((y,h)=>{n(S=>{let _=!1;const k=S.map(I=>I.id!==y||I.chats===h?I:(_=!0,{...I,chats:h}));return _?k:S})},[]),g=o.useCallback((y,h)=>{n(S=>{const _=S.length===0?y:kd(y,S,h),k=!Sd(S,_);return k&&Ks.record({kind:"dashboard.entries_applied",payload:{incoming:Ao(y),next:Ao(_)}}),k?_:S})},[]),w=o.useCallback(()=>i(!0),[]),A=o.useMemo(()=>({injectEntries:g,markLoaded:w,getIdes:()=>m.current}),[g,w]),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(Oi.Provider,{value:A,children:t.jsx(Bi.Provider,{value:b,children:e})})}function js(){return o.useContext(Bi)}function cn(){return o.useContext(Oi)}function Wi(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),g=new AbortController,w=setTimeout(()=>g.abort(),15e3);try{const A=await fetch(f,{...u,headers:p,signal:g.signal});if(A.status===401)throw n==null||n(),new Error("Unauthorized");if(!A.ok){const d=await A.json().catch(()=>({error:A.statusText}));throw new Error(d.error||`API Error: ${A.status}`)}return A.json()}finally{clearTimeout(w)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,p={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),execTerminal:(l,u,p)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:p})}),sendAgentMessage:(l,u,p)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:p})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,p)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:p?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,p={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Cd=Wi({baseUrl:"http://localhost:3847"}),Id=o.createContext(Cd);function Ad({client:e,children:s}){return t.jsx(Id.Provider,{value:e,children:s})}const Md={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Hi=o.createContext(Md);function Td({value:e,children:s}){return t.jsx(Hi.Provider,{value:e,children:s})}function Pt(){return o.useContext(Hi)}function Ld(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 _d(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Fi(e){return e?Ld([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),_d(e.content)]):""}const He={size:18};function Ui({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Qt({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),t.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),t.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),t.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Pa({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"9",cy:"7",r:"4"}),t.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),t.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Rd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Pd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"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 zi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Dd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 bn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Vi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Ed({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Zt({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Rt({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Da({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t.jsx("polyline",{points:"14 2 14 8 20 8"}),t.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),t.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function $d({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Bs({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function Gs({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"23 4 23 10 17 10"}),t.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function ks({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function fr({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M12 22v-5"}),t.jsx("path",{d:"M9 8V2"}),t.jsx("path",{d:"M15 8V2"}),t.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function Gi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),t.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function qi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),t.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),t.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Yi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Kd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"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 gn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Bd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Ea({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Od({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function At({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Wd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),t.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),t.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),t.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Hd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"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 Fd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function Ud({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),t.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function yn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 zd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Vd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Gd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 qd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Yd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Xd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Jd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"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 Qd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}function Zd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function eu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"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 tu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 su({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function Lo(e){return!!e&&typeof e=="object"&&"text"in e}function $a(e,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(i=>typeof i=="string"?i:Lo(i)?String(i.text||""):"").join(r):Lo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Os(e){return $a(e,{normalizeWhitespace:!0})}const Dn=new Map;function _o(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function ru(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${Fi(s)}`}function Ro(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function Xi(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function nu(e,s,r){return Number(e.receivedAt||r[_s(e,s)]||0)||0}function Ji(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function au(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function _r(e,s){if(!e)return s;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||s}catch{return e.split(/[\\/]/).filter(Boolean).pop()||s}}function En(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 Po(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):Ji(e)?t.jsx(Ta,{remarkPlugins:[La,$i,Ki],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Rr({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:Po(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=En(r);return a?t.jsx("img",{src:a,alt:_r(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=En(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=En(r);return a?t.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:_r(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||_r(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=_r(r.resource.uri,"resource");if(r.resource.text)return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[t.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),Po(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return t.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function _s(e,s){const r=e,n=$a(e.content,{joiner:`
|
|
3
|
-
`});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${s}`].filter(Boolean).join("|")}const
|
|
4
|
-
`});if(m==="thought"){const x=typeof((I=s.meta)==null?void 0:I.label)=="string"?s.meta.label:"Thought";return t.jsxs("div",{className:"self-start chat-msg-thought",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx(Fd,{size:13}),t.jsx("span",{children:x})]}),t.jsx("div",{className:"chat-msg-body",children:w})]})}if(m==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),g&&f?t.jsx("div",{className:"tool-text w-full",children:t.jsx(Rr,{parts:f,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(m==="terminal"){const x=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",E=typeof((v=s.meta)==null?void 0:v.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:x}),t.jsx("span",{children:E})]}),g&&f?t.jsx("div",{className:"chat-msg-body",children:t.jsx(Rr,{parts:f,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:w})]})}if(m==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:g&&f?t.jsx(Rr,{parts:f,renderAsPreformatted:!1}):w.slice(0,100)});const A=s.meta,b=(typeof(A==null?void 0:A.renderMode)=="string"?A.renderMode.trim():"")==="preformatted",y=w,h=!1,S=y,_=b,k=!_&&Ji(S);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(y||g||p)&&t.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${y||g?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:p?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Xi(r)})]}),(y||g)&&t.jsx("div",{className:"chat-markdown",children:g&&f?t.jsx(Rr,{parts:f,renderAsPreformatted:_}):_?t.jsx("pre",{className:"chat-preformatted",children:S}):k?t.jsx(Ta,{remarkPlugins:[La,$i,Ki],children:S}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:S})}),h]})})},(e,s)=>e.message===s.message&&e.receivedAt===s.receivedAt&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isTextExpanded===s.isTextExpanded),cu=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:g,hiddenLiveCount:w=0,loadError:A,scrollToBottomRequestNonce:d},b){const y=o.useRef(null),h=o.useRef(null),S=o.useRef(null),_=o.useRef(0),k=o.useRef(""),I=o.useRef(!1),j=o.useRef(null),v=o.useRef(!1),x=o.useRef(null),E=o.useRef(!1),[L,M]=o.useState(new Set),T=o.useRef(!1),B=o.useRef(!1),H=()=>{const X=y.current;return X?X.scrollHeight-X.scrollTop-X.clientHeight<200:!0},C=o.useCallback((X="auto")=>{const he=y.current;he&&he.scrollTo({top:he.scrollHeight,behavior:X})},[]),R=o.useCallback(()=>{var ue;const X=y.current,he=(ue=window.getSelection)==null?void 0:ue.call(window);if(!X||!he||he.rangeCount===0||he.isCollapsed){E.current=!1;return}const J=he.anchorNode,Z=he.focusNode;E.current=!!(J&&Z&&X.contains(J)&&X.contains(Z))},[]),U=ru(s),N=o.useCallback(()=>{const X=y.current;!X||!l||Dn.set(l,{top:X.scrollTop,fromBottom:Math.max(0,X.scrollHeight-X.scrollTop-X.clientHeight),messageFingerprint:U})},[l,U]),D=o.useCallback((X="auto")=>{j.current!=null&&cancelAnimationFrame(j.current),j.current=requestAnimationFrame(()=>{j.current=null,C(X)})},[C]);o.useEffect(()=>{const X=!I.current,he=k.current!==l;if(k.current=l,X||he){if(I.current=!0,T.current=!1,v.current=!0,!E.current){const Z=l?Dn.get(l):null;Z&&_o(Z,U)?requestAnimationFrame(()=>{const ue=y.current;ue&&(Ro(ue,Z),B.current=!0)}):D("auto")}_.current=s.length;return}s.length>_.current?!T.current&&!E.current&&D("auto"):H()&&!T.current&&!E.current&&D("auto"),_.current=s.length},[U,l,c,s.length,D]),o.useEffect(()=>{d&&(T.current=!1,v.current=!0,B.current=!0,x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{v.current=!1,x.current=null},180),E.current||D("auto"))},[D,d]),o.useEffect(()=>()=>{N(),j.current!=null&&cancelAnimationFrame(j.current),x.current!=null&&window.clearTimeout(x.current)},[N]),o.useEffect(()=>{const X=h.current;if(!X)return;const he=()=>{x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{v.current=!1,x.current=null},180)},J=new ResizeObserver(()=>{v.current&&(E.current||(D("auto"),he()))});return J.observe(X),()=>{J.disconnect(),x.current!=null&&(window.clearTimeout(x.current),x.current=null)}},[D,l]),o.useImperativeHandle(b,()=>({scrollToBottom:(X="smooth")=>{C(X)}}),[C]),o.useEffect(()=>{const X=y.current;if(!X)return;let he;const J=()=>{clearTimeout(he),he=setTimeout(()=>{T.current=!H(),N()},50)};return X.addEventListener("scroll",J,{passive:!0}),()=>{X.removeEventListener("scroll",J),clearTimeout(he)}},[N]),o.useEffect(()=>(document.addEventListener("selectionchange",R),()=>document.removeEventListener("selectionchange",R)),[R]);const Y=o.useRef(0),q=o.useRef(!1);o.useEffect(()=>{const X=y.current;if(!X||!q.current||Y.current===0)return;const he=X.scrollHeight-Y.current;he>0&&(X.scrollTop=he),N(),Y.current=0,q.current=!1},[s.length,N]),o.useEffect(()=>{if(B.current||!l)return;const X=Dn.get(l),he=y.current;if(!(!X||!he)){if(!_o(X,U)){C("auto"),B.current=!0;return}Ro(he,X),B.current=!0}},[l,U,s.length,C]);const W=()=>{const X=y.current;X&&(Y.current=X.scrollHeight),q.current=!0,m==null||m()},ae=o.useMemo(()=>{const X=s.map((ue,de)=>({type:"message",data:ue,index:de,ts:nu(ue,de,u)}));if(!r||r.length===0)return X;const he=[...r].sort((ue,de)=>ue.timestamp-de.timestamp).map((ue,de)=>({type:"action",data:ue,index:de,ts:ue.timestamp})),J=[];let Z=0;for(const ue of X){for(;Z<he.length&&ue.ts>0&&he[Z].ts<ue.ts;)J.push(he[Z++]);J.push(ue)}for(;Z<he.length;)J.push(he[Z++]);return J},[s,r,u]),ce=w>0||!!g,Se=w>0?`↑ Show ${Math.min(w,80)} earlier messages${w>80?` (${w} hidden)`:""}`:A?`↻ ${A}`:"↑ Load older messages";return t.jsx("div",{ref:y,"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..."}),ce&&!f&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:W,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${A&&w===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:Se})}),ae.length===0&&!ce&&(p||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ae.map(X=>{if(X.type==="action"){const ye=X.data;return t.jsx(ou,{log:ye},`action-${X.index}`)}const he=X.data,J=X.index,Z=_s(he,J),ue=he.receivedAt||u[Z],de=`${l}-${Z}`,z=L.has(de);return t.jsx(iu,{message:he,receivedAt:ue,agentName:n,userName:a,isCliMode:i,isTextExpanded:z,onToggleTextExpanded:()=>M(ye=>{const ie=new Set(ye);return z?ie.delete(de):ie.add(de),ie})},`msg-${Z}`)}),c&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:S})]})})}),lu=o.memo(cu,(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),du="modulepreload",uu=function(e){return"/"+e},Do={},mu=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=uu(u),u in Do)return;Do[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":du,p||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),p)return new Promise((g,w)=>{f.addEventListener("load",g),f.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})};let Eo=!1;const Qi=o.forwardRef(({onInput:e,fontSize:s=13,readOnly:r=!1,sizingMode:n="measured"},a)=>{const i=o.useRef(null),[c,l]=o.useState(null),u=o.useRef([]),p=o.useRef(!1),m=o.useRef(!1),f=o.useRef(!1),g=()=>{const w=i.current;if(w){p.current&&(w.clear(),p.current=!1);for(const A of u.current)w.write(A);u.current=[],m.current&&(w.fit(),m.current=!1),f.current&&(w.bumpResize(),f.current=!1)}};return o.useImperativeHandle(a,()=>({write:w=>{i.current?i.current.write(w):u.current.push(w)},clear:()=>{i.current?i.current.clear():(u.current=[],p.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(u.current=[],p.current=!0)},resize:(w,A)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(w,A)},fit:()=>{i.current?i.current.fit():m.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():f.current=!0}}),[]),o.useEffect(()=>{if(!c)return;const w=requestAnimationFrame(()=>{g()});return()=>cancelAnimationFrame(w)},[c]),o.useEffect(()=>{let w=!1;return mu(()=>import("./terminal-2SYILvaH.js"),__vite__mapDeps([0,1,2])).then(A=>{Eo||(Eo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),w||l(()=>A.GhosttyTerminalView)}).catch(A=>{console.error("[CliTerminal] failed to load terminal renderer",A)}),()=>{w=!0}},[]),c?t.jsx(c,{ref:i,onInput:e,fontSize:s,readOnly:r,sizingMode:n,className:"w-full h-full rounded-lg overflow-hidden"}):t.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Qi.displayName="CliTerminal";function Pr({label:e,value:s,sub:r,icon:n}){return t.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[t.jsx("span",{className:"text-base flex items-center",children:n}),t.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),t.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function $o({value:e,max:s,label:r,color:n="#8b5cf6",detail:a,compact:i=!1}){const c=s>0?Math.min(Math.round(e/s*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-0.5",children:[t.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),t.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-1.5",children:[t.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),t.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function pu({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,g,w;u>p?(m=a.width,f=a.width/u,g=0,w=(a.height-f)/2):(f=a.height,m=a.height*u,g=(a.width-m)/2,w=0);const A=a.left-i.left+g+m*e.nx,d=a.top-i.top+w+f*e.ny,b=Math.max(8,Math.min(i.width-8,A)),y=Math.max(8,Math.min(i.height-8,d));return t.jsxs("div",{style:{position:"absolute",left:b-8,top:y-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 fu({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:g,onZoomOut:w,onZoomReset:A,onZoomIn:d,transportType:b,screenshotUsage:y,lastActionStatus:h}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:S=>S.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[t.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[t.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),t.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("div",{onClick:()=>{n(S=>!S),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&t.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:t.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:S=>S.stopPropagation(),onChange:S=>l(S.target.value),onKeyDown:S=>{u(S)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),t.jsx("div",{className:"relative",children:t.jsx("div",{onClick:()=>{i(S=>!S),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⚙️"})})}),t.jsx("div",{className:"w-px h-[18px] bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:p?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:p?"Connected":"WS"})]}),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"}),y&&y.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),h&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:h})]})]}),a&&t.jsxs("div",{onTouchStart:S=>S.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",m<=(f?g:1)+.01?f?"FILL":"FIT":`${Math.round(m*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:S=>{S.stopPropagation(),w()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),t.jsx("button",{onClick:S=>{S.stopPropagation(),A()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:f?"FILL":"FIT"}),t.jsx("button",{onClick:S=>{S.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 hu({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 xu(){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 Ko(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 wr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!xu())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,Ko(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,Ko(s[c])]))}),r.current=s})}function bu({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:g,onAction:w,setLastActionStatus:A,spawnRippleFromNormalized:d,clampPan:b,isMobile:y,mobileFillZoom:h}){const[S,_]=o.useState(null),k=o.useRef(null),I=o.useRef(null),j=o.useRef(null),v=o.useRef(!1),x=o.useRef(null),E=o.useRef(0),L=o.useRef(null),M=o.useRef(1),T=o.useRef({x:0,y:0}),B=o.useRef(!1),H=o.useRef(n),C=o.useRef(w),R=30,U=550,N=18,D=60,Y=400,q=12,W=()=>{if(k.current)return;const Se={nx:.5,ny:.5};k.current=Se,_(Se)};return o.useEffect(()=>{H.current=n,n==="mouse"&&W()},[n]),o.useEffect(()=>{C.current=w},[w]),o.useEffect(()=>{const Se=e.current;if(!Se)return;const X=z=>{if(!r.current)return null;const ye=r.current.getBoundingClientRect();return!ye.width||!ye.height?null:{nx:Math.max(0,Math.min(1,(z.clientX-ye.left)/ye.width)),ny:Math.max(0,Math.min(1,(z.clientY-ye.top)/ye.height))}},he=(z,ye)=>{if(!r.current)return{dnx:0,dny:0};const ie=r.current,le=ie.getBoundingClientRect(),se=ie.naturalWidth||le.width,pe=ie.naturalHeight||le.height,ne=se/pe,ke=le.width/le.height;let ve,K;return ne>ke?(ve=le.width,K=le.width/ne):(K=le.height,ve=le.height*ne),{dnx:z/ve,dny:ye/K}},J=(z,ye,ie)=>{if(ie<=1.05)return;const le=-(z-.5)*100,se=-(ye-.5)*100,pe=b(le,se,ie);(Math.abs(pe.x-l.current)>.1||Math.abs(pe.y-u.current)>.1)&&(p(pe.x),m(pe.y),l.current=pe.x,u.current=pe.y)},Z=z=>{const ye=s.current;if(ye&&z.target instanceof Node&&ye.contains(z.target))z.preventDefault();else return;if(z.touches.length===1){const ie=z.touches[0];I.current={x:ie.clientX,y:ie.clientY,time:Date.now()},j.current={x:ie.clientX,y:ie.clientY},B.current||(v.current=!1),x.current=setTimeout(()=>{if(!v.current&&!B.current)if(v.current=!0,H.current==="mouse"){const le=k.current||{nx:.5,ny:.5};A("Right Click"),d(le.nx,le.ny,"right"),C.current("input_click",{...le,button:"right"}).catch(()=>{})}else{const le=X(ie);le&&(A("Right Click"),d(le.nx,le.ny,"right"),C.current("input_click",{...le,button:"right"}).catch(()=>{}))}},500);return}if(z.touches.length===2){x.current&&clearTimeout(x.current),v.current=!0,B.current=!0;const ie=z.touches[1].clientX-z.touches[0].clientX,le=z.touches[1].clientY-z.touches[0].clientY;L.current=Math.sqrt(ie*ie+le*le),M.current=c.current,T.current={x:(z.touches[0].clientX+z.touches[1].clientX)/2,y:(z.touches[0].clientY+z.touches[1].clientY)/2}}},ue=z=>{const ye=s.current;if(ye&&z.target instanceof Node&&ye.contains(z.target)&&z.preventDefault(),z.touches.length===1&&j.current){const ie=z.touches[0],le=ie.clientX-j.current.x,se=ie.clientY-j.current.y;if(!v.current&&I.current){const pe=ie.clientX-I.current.x,ne=ie.clientY-I.current.y;Math.sqrt(pe*pe+ne*ne)>8&&(v.current=!0,x.current&&clearTimeout(x.current))}if(v.current)if(H.current==="mouse"){const pe=he(le,se),ne=k.current||{nx:.5,ny:.5},ke=Math.max(0,Math.min(1,ne.nx+pe.dnx)),ve=Math.max(0,Math.min(1,ne.ny+pe.dny));k.current={nx:ke,ny:ve},_({nx:ke,ny:ve}),A(`Cursor: ${Math.round(ke*100)}%, ${Math.round(ve*100)}%`),J(ke,ve,c.current);const K=Date.now();K-g.current>=30&&(g.current=K,C.current("input_mouseMoved",{nx:ke,ny:ve}).catch(()=>{}))}else if(c.current>1){const pe=s.current;if(pe){const ne=pe.clientWidth,ke=pe.clientHeight,ve=l.current+le/ne*100,K=u.current+se/ke*100,V=b(ve,K,c.current);p(V.x),m(V.y),l.current=V.x,u.current=V.y}}else{const pe=X(ie);if(pe){const ne=Date.now();ne-g.current>=40&&(g.current=ne,A("Scroll"),C.current("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(-le*2.5),deltaY:Math.round(-se*2.5)}).catch(()=>{}))}}j.current={x:ie.clientX,y:ie.clientY};return}if(z.touches.length===2&&L.current!==null){const ie=z.touches[1].clientX-z.touches[0].clientX,le=z.touches[1].clientY-z.touches[0].clientY,pe=Math.sqrt(ie*ie+le*le)/L.current,ne=(z.touches[0].clientX+z.touches[1].clientX)/2,ke=(z.touches[0].clientY+z.touches[1].clientY)/2,ve=ne-T.current.x,K=ke-T.current.y,V=Math.abs(pe-1)>.03;if(H.current==="mouse"){if(V){const we=Math.max(i,Math.min(5,M.current*pe));f(we),c.current=we}else if(Math.abs(ve)>2||Math.abs(K)>2){const we=k.current||{nx:.5,ny:.5},be=Date.now();be-g.current>=30&&(g.current=be,A("Scroll"),C.current("input_wheel",{nx:we.nx,ny:we.ny,deltaX:Math.round(-ve*3),deltaY:Math.round(-K*3)}).catch(()=>{}))}}else{const we=Math.max(i,Math.min(5,M.current*pe));f(we),c.current=we;const be=s.current;if(be&&we>1){const Q=be.clientWidth,Me=be.clientHeight,Oe=l.current+ve/Q*100,Pe=u.current+K/Me*100,Ke=b(Oe,Pe,we);p(Ke.x),m(Ke.y),l.current=Ke.x,u.current=Ke.y}}T.current={x:ne,y:ke}}},de=z=>{var ye;if(x.current&&clearTimeout(x.current),L.current=null,z.touches.length===1&&B.current){const ie=z.touches[0];I.current={x:ie.clientX,y:ie.clientY,time:Date.now()},j.current={x:ie.clientX,y:ie.clientY},v.current=!0;return}if(z.touches.length===0){if(B.current){B.current=!1,v.current=!1;return}if(z.changedTouches.length===1){const ie=z.changedTouches[0],le=Date.now(),se=le-(((ye=I.current)==null?void 0:ye.time)||0),pe=I.current?ie.clientX-I.current.x:0,ne=I.current?ie.clientY-I.current.y:0,ke=Math.sqrt(pe*pe+ne*ne);if(H.current==="mouse"){if(se<R||se>U||ke>N){v.current=!1;return}const ve=k.current||X(ie);ve&&(A(`Click: ${Math.round(ve.nx*100)}%, ${Math.round(ve.ny*100)}%`),d(ve.nx,ve.ny,"left"),C.current("input_click",{...ve}).catch(()=>{}))}else{if(v.current){v.current=!1;return}if(se<D||se>Y||ke>q){v.current=!1;return}const ve=X(ie);if(!ve)return;le-E.current<300?(A("Double tap"),d(ve.nx,ve.ny,"double"),C.current("input_click",{...ve,clickCount:2}).catch(()=>{}),E.current=0):(A(`Tap: ${Math.round(ve.nx*100)}%, ${Math.round(ve.ny*100)}%`),d(ve.nx,ve.ny,"left"),C.current("input_click",{...ve}).catch(()=>{}),E.current=le)}}v.current=!1}};return Se.addEventListener("touchstart",Z,{passive:!1}),Se.addEventListener("touchmove",ue,{passive:!1}),Se.addEventListener("touchend",de,{passive:!1}),()=>{Se.removeEventListener("touchstart",Z),Se.removeEventListener("touchmove",ue),Se.removeEventListener("touchend",de),x.current&&clearTimeout(x.current)}},[e,s,r,i,c,l,u,p,m,f,g,A,d,b]),{cursorPos:S,cursorPosRef:k,handleToggleInputMode:()=>{a(Se=>{const X=Se==="touch"?"mouse":"touch";return X==="mouse"&&W(),X})},handleZoomReset:()=>{const Se=y?h:1;f(Se),c.current=Se,p(0),m(0),l.current=0,u.current=0}}}function Zi({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,g]=o.useState(""),[,w]=o.useState(!1),[A,d]=o.useState([]),b=o.useRef(0),[y,h]=o.useState(!1),[S,_]=o.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[I,j]=o.useState(k?"mouse":"touch"),[v,x]=o.useState(1),E=o.useRef(!1),[L,M]=o.useState(1),[T,B]=o.useState(0),[H,C]=o.useState(0);wr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:I,zoom:L,panX:T,panY:H,isMenuOpen:y,isImeOpen:S});const R=o.useRef(0),U=o.useRef(L),N=o.useRef(T),D=o.useRef(H);o.useEffect(()=>{U.current=L},[L]),o.useEffect(()=>{N.current=T},[T]),o.useEffect(()=>{D.current=H},[H]),o.useEffect(()=>{var se;(se=c.current)==null||se.focus()},[]);const Y=r==="connected",q=n,W=Y?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ae=Y?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!k||E.current||!q)return;const se=u.current,pe=l.current;if(!se||!pe)return;const ne=()=>{const ke=pe.clientWidth,ve=pe.clientHeight,K=se.naturalWidth,V=se.naturalHeight;if(!K||!V||!ke||!ve)return;const we=Math.min(ke/K,ve/V),Q=Math.max(ke/K,ve/V)/we;Q>1.01&&(x(Q),M(Q),U.current=Q),E.current=!0};se.complete&&se.naturalWidth?ne():se.addEventListener("load",ne,{once:!0})},[q,k]);const ce=.5;o.useEffect(()=>{L<=ce&&(B(0),C(0))},[L,ce]);const Se=(se,pe,ne)=>{if(ne<=ce)return{x:0,y:0};const ke=(ne-1)/(2*ne)*100,ve=(ne-1)/(2*ne)*100;return{x:Math.max(-ke,Math.min(ke,se)),y:Math.max(-ve,Math.min(ve,pe))}},X=(se,pe)=>{if(!u.current)return null;const ne=u.current.getBoundingClientRect();return!ne.width||!ne.height?null:{nx:Math.max(0,Math.min(1,(se-ne.left)/ne.width)),ny:Math.max(0,Math.min(1,(pe-ne.top)/ne.height))}},he=(se,pe,ne)=>{const ke=l.current;if(!ke)return;const ve=ke.getBoundingClientRect(),K=++b.current;d(V=>[...V,{id:K,x:se-ve.left,y:pe-ve.top,type:ne}]),setTimeout(()=>d(V=>V.filter(we=>we.id!==K)),600)},J=(se,pe,ne)=>{const ke=u.current,ve=l.current;if(!ke||!ve)return;const K=ke.getBoundingClientRect(),V=ve.getBoundingClientRect(),we=ke.naturalWidth||K.width,be=ke.naturalHeight||K.height,Q=we/be,Me=K.width/K.height;let Oe,Pe,Ke,Qe;Q>Me?(Oe=K.width,Pe=K.width/Q,Ke=0,Qe=(K.height-Pe)/2):(Pe=K.height,Oe=K.height*Q,Ke=(K.width-Oe)/2,Qe=0);const Ge=K.left-V.left+Ke+Oe*se,ut=K.top-V.top+Qe+Pe*pe,it=++b.current;d(ht=>[...ht,{id:it,x:Ge,y:ut,type:ne}]),setTimeout(()=>d(ht=>ht.filter(ze=>ze.id!==it)),600)},Z=async se=>{var ne;const pe=X(se.clientX,se.clientY);if(pe){m(`Click: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),he(se.clientX,se.clientY,"left"),(ne=c.current)==null||ne.focus();try{const ke=await e("input_click",{nx:pe.nx,ny:pe.ny});ke!=null&&ke.success||s(`❌ Click failed: ${ke==null?void 0:ke.error}`)}catch(ke){s(`❌ Click error: ${ke.message||ke}`)}}},ue=async(se,pe,ne,ke=0)=>{try{await e("input_key",{type:ne?"char":"keyDown",key:se,code:pe,text:ne?se:void 0,unmodifiedText:ne?se:void 0,modifiers:ke})}catch(ve){s(`❌ Key error: ${ve.message||ve}`)}},de=async se=>{if(se.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(se.key)&&se.preventDefault();let ne=0;se.altKey&&(ne|=1),se.ctrlKey&&(ne|=2),se.metaKey&&(ne|=4),se.shiftKey&&(ne|=8),m(`Key: ${se.key}`),await ue(se.key,se.code,se.key.length===1,ne)},z=async se=>{if(se.key==="Enter"){if(se.nativeEvent.isComposing)return;if(f){const pe=f;g(""),m(`IME Sent: ${pe}`);try{const ne=await e("input_type",{text:pe});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 ue("Enter","Enter",!1)}};o.useEffect(()=>{const se=c.current;if(!se)return;const pe=ne=>{var ke;if((ke=u.current)!=null&&ke.contains(ne.target)){ne.preventDefault();const ve=Date.now();if(ve-R.current<40)return;R.current=ve;const K=X(ne.clientX,ne.clientY);if(!K)return;m(`Scroll: ${Math.round(ne.deltaY)}`),e("input_wheel",{nx:K.nx,ny:K.ny,deltaX:Math.round(ne.deltaX),deltaY:Math.round(ne.deltaY)}).catch(()=>{})}};return se.addEventListener("wheel",pe,{passive:!1}),()=>se.removeEventListener("wheel",pe)},[e]);const{cursorPos:ye,handleToggleInputMode:ie,handleZoomReset:le}=bu({containerRef:c,viewportRef:l,imgRef:u,inputMode:I,setInputMode:j,minZoom:ce,zoomRef:U,panXRef:N,panYRef:D,setPanX:B,setPanY:C,setZoom:M,lastWheelTimeRef:R,onAction:e,setLastActionStatus:m,spawnRippleFromNormalized:J,clampPan:Se,isMobile:k,mobileFillZoom:v});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:de,onContextMenu:se=>se.preventDefault(),onFocus:()=>w(!0),onBlur:()=>w(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[q?t.jsx("img",{ref:u,src:q,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${T}%, ${H}%)`,transformOrigin:"center center",cursor:I==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:Z,onContextMenu:se=>se.preventDefault(),onDragStart:se=>se.preventDefault()}):t.jsx(hu,{waitingLabel:W,waitingHint:ae,transportType:i}),I==="mouse"&&q&&t.jsx(pu,{cursorPos:ye,viewportRef:l,imgRef:u}),A.map(se=>{const ne={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[se.type];return t.jsxs("div",{style:{position:"absolute",left:se.x,top:se.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${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}})]},se.id)})]}),t.jsx(fu,{inputMode:I,onToggleInputMode:ie,isImeOpen:S,setIsImeOpen:_,isMenuOpen:y,setIsMenuOpen:h,imeText:f,setImeText:g,handleImeSubmit:z,isConnActive:Y,zoom:L,isMobile:k,mobileFillZoom:v,onZoomOut:()=>M(se=>Math.max(.5,se-.25)),onZoomReset:le,onZoomIn:()=>M(se=>Math.min(5,se+.25)),transportType:i,screenshotUsage:a,lastActionStatus:p}),t.jsx("style",{children:`
|
|
2
|
+
var dd=Object.defineProperty;var ud=(e,s,r)=>s in e?dd(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Ye=(e,s,r)=>ud(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as Ta,a as La,b as Ki,c as Bi,u as Vs,R as at,d as pr,t as md,e as pd,D as fd,f as ua,g as ma,h as _a,i as hd,k as xd,B as bd,l as gd,m as cs,N as pa,n as yd}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 vd(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 Ks=vd();function Ao(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 wd(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function jd(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 ar(e,s){const r=wd(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:jd(e.activeChat,s==null?void 0:s.activeChat),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),summaryMetadata:e.summaryMetadata??(s==null?void 0:s.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash),unread:e.unread??(s==null?void 0:s.unread),lastSeenAt:e.lastSeenAt??(s==null?void 0:s.lastSeenAt),inboxBucket:e.inboxBucket??(s==null?void 0:s.inboxBucket),completionMarker:e.completionMarker??(s==null?void 0:s.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(s==null?void 0:s.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(s==null?void 0:s.surfaceHidden),resume:e.resume??(s==null?void 0:s.resume),runtimeKey:e.runtimeKey??(s==null?void 0:s.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(s==null?void 0:s.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(s==null?void 0:s.runtimeWorkspaceLabel)}}function Mo(e,s){if(!(s!=null&&s.length))return e;if(!(e!=null&&e.length))return s;const r=new Map(e.map(n=>[n.id,n]));return s.map(n=>{const a=r.get(n.id);return a?ar(n,a):n})}const Oi=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}),Wi=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function To(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 Pn(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 on(e){return Array.isArray(e)?e.map(on):!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,on(r)]))}function kd(e,s){try{return JSON.stringify(on(e))===JSON.stringify(on(s))}catch{return!1}}function Lr(e,s,r){return kd(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function Sd(e,s,r){var u,p,m,f,g,w,A;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 y=To(d),h=To(b);if(y>h){const S=(u=d.chats)!=null&&u.length?d.chats:b.chats,_=Mo(b.childSessions,d.childSessions),k=Pn(b,d,{...b,...d,chats:S,childSessions:_,_lastUpdate:n});i.set(d.id,Lr(b,k,n))}else if(y<h){const S={};if(d.status&&d.status!==b.status&&(S.status=d.status),d.cdpConnected!==void 0&&(S.cdpConnected=d.cdpConnected),(p=d.chats)!=null&&p.length&&!((m=b.chats)!=null&&m.length)&&(S.chats=d.chats),d.machineNickname!==void 0&&d.machineNickname!==b.machineNickname&&(S.machineNickname=d.machineNickname),d.version!==void 0&&(S.version=d.version),d.serverVersion!==void 0&&(S.serverVersion=d.serverVersion),d.versionMismatch===!0&&(S.versionMismatch=!0),Object.keys(S).length>0){const _=Pn(b,d,{...b,...S,_lastUpdate:b._lastUpdate});i.set(d.id,Lr(b,_,n))}else Lr(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const S=d.timestamp||n,_=b._lastUpdate||b.timestamp||0;if(S>=_){const k=(f=d.chats)!=null&&f.length?d.chats:b.chats,I=Mo(b.childSessions,d.childSessions),j=Pn(b,d,{...b,...d,chats:k,childSessions:I,_lastUpdate:n});i.set(d.id,Lr(b,j,n))}else(g=d.chats)!=null&&g.length&&!((w=b.chats)!=null&&w.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||((A=d.id)==null?void 0:A.split(":")[0]);b&&l.add(b)}for(const[d,b]of i){const y=b.daemonId||d.split(":")[0];if(!l.has(y))continue;if(a.has(y)&&!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 Nd(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 Cd({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((y,h)=>{n(S=>{let _=!1;const k=S.map(I=>I.id!==y||I.chats===h?I:(_=!0,{...I,chats:h}));return _?k:S})},[]),g=o.useCallback((y,h)=>{n(S=>{const _=S.length===0?y:Sd(y,S,h),k=!Nd(S,_);return k&&Ks.record({kind:"dashboard.entries_applied",payload:{incoming:Ao(y),next:Ao(_)}}),k?_:S})},[]),w=o.useCallback(()=>i(!0),[]),A=o.useMemo(()=>({injectEntries:g,markLoaded:w,getIdes:()=>m.current}),[g,w]),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(Wi.Provider,{value:A,children:t.jsx(Oi.Provider,{value:b,children:e})})}function js(){return o.useContext(Oi)}function cn(){return o.useContext(Wi)}function Hi(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),g=new AbortController,w=setTimeout(()=>g.abort(),15e3);try{const A=await fetch(f,{...u,headers:p,signal:g.signal});if(A.status===401)throw n==null||n(),new Error("Unauthorized");if(!A.ok){const d=await A.json().catch(()=>({error:A.statusText}));throw new Error(d.error||`API Error: ${A.status}`)}return A.json()}finally{clearTimeout(w)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,p={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),execTerminal:(l,u,p)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:p})}),sendAgentMessage:(l,u,p)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:p})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,p)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:p?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,p={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Id=Hi({baseUrl:"http://localhost:3847"}),Ad=o.createContext(Id);function Md({client:e,children:s}){return t.jsx(Ad.Provider,{value:e,children:s})}const Td={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Fi=o.createContext(Td);function Ld({value:e,children:s}){return t.jsx(Fi.Provider,{value:e,children:s})}function Pt(){return o.useContext(Fi)}function _d(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 Rd(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Ui(e){return e?_d([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Rd(e.content)]):""}const He={size:18};function zi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Qt({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),t.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),t.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),t.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function Pa({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"9",cy:"7",r:"4"}),t.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),t.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Pd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Dd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function Vi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),t.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),t.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),t.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Ed({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 bn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Gi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function $d({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Zt({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Rt({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Da({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t.jsx("polyline",{points:"14 2 14 8 20 8"}),t.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),t.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Kd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Bs({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function Gs({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"23 4 23 10 17 10"}),t.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function ks({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function fr({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M12 22v-5"}),t.jsx("path",{d:"M9 8V2"}),t.jsx("path",{d:"M15 8V2"}),t.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function qi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"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 Yi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),t.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),t.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Xi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Bd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 gn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Od({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Ea({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Wd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function At({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Hd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Fd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Ud({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 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 zd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"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 yn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Vd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Gd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function qd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"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 Yd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),t.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Xd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Jd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Qd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Zd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}function eu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function tu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 su({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),t.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function ru({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"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 Lo(e){return!!e&&typeof e=="object"&&"text"in e}function $a(e,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(i=>typeof i=="string"?i:Lo(i)?String(i.text||""):"").join(r):Lo(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Os(e){return $a(e,{normalizeWhitespace:!0})}const Dn=new Map;function _o(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function nu(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${Ui(s)}`}function Ro(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function Ji(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function au(e,s,r){return Number(e.receivedAt||r[_s(e,s)]||0)||0}function Qi(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function ou(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function _r(e,s){if(!e)return s;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||s}catch{return e.split(/[\\/]/).filter(Boolean).pop()||s}}function En(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 Po(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):Qi(e)?t.jsx(Ta,{remarkPlugins:[La,Ki,Bi],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Rr({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:Po(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=En(r);return a?t.jsx("img",{src:a,alt:_r(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=En(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=En(r);return a?t.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:_r(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||_r(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=_r(r.resource.uri,"resource");if(r.resource.text)return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[t.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),Po(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return t.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function _s(e,s){const r=e,n=$a(e.content,{joiner:`
|
|
3
|
+
`});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${s}`].filter(Boolean).join("|")}const iu=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(Ta,{remarkPlugins:[La],children:s.text}),t.jsx("span",{className:"action-time",children:Ji(s.timestamp)})]})},(e,s)=>e.log===s.log),cu=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var I,j,v;const u=(s.role||"").toLowerCase(),p=u==="user"||u==="human",m=s.kind||(u==="tool"?"tool":"standard"),f=ou(s.content)?s.content:null,g=!!(f!=null&&f.some(x=>x.type!=="text")),w=$a(s.content,{joiner:`
|
|
4
|
+
`});if(m==="thought"){const x=typeof((I=s.meta)==null?void 0:I.label)=="string"?s.meta.label:"Thought";return t.jsxs("div",{className:"self-start chat-msg-thought",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx(Ud,{size:13}),t.jsx("span",{children:x})]}),t.jsx("div",{className:"chat-msg-body",children:w})]})}if(m==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),g&&f?t.jsx("div",{className:"tool-text w-full",children:t.jsx(Rr,{parts:f,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(m==="terminal"){const x=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",E=typeof((v=s.meta)==null?void 0:v.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:x}),t.jsx("span",{children:E})]}),g&&f?t.jsx("div",{className:"chat-msg-body",children:t.jsx(Rr,{parts:f,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:w})]})}if(m==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:g&&f?t.jsx(Rr,{parts:f,renderAsPreformatted:!1}):w.slice(0,100)});const A=s.meta,b=(typeof(A==null?void 0:A.renderMode)=="string"?A.renderMode.trim():"")==="preformatted",y=w,h=!1,S=y,_=b,k=!_&&Qi(S);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(y||g||p)&&t.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${y||g?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:p?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Ji(r)})]}),(y||g)&&t.jsx("div",{className:"chat-markdown",children:g&&f?t.jsx(Rr,{parts:f,renderAsPreformatted:_}):_?t.jsx("pre",{className:"chat-preformatted",children:S}):k?t.jsx(Ta,{remarkPlugins:[La,Ki,Bi],children:S}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:S})}),h]})})},(e,s)=>e.message===s.message&&e.receivedAt===s.receivedAt&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isTextExpanded===s.isTextExpanded),lu=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:g,hiddenLiveCount:w=0,loadError:A,scrollToBottomRequestNonce:d},b){const y=o.useRef(null),h=o.useRef(null),S=o.useRef(null),_=o.useRef(0),k=o.useRef(""),I=o.useRef(!1),j=o.useRef(null),v=o.useRef(!1),x=o.useRef(null),E=o.useRef(!1),[L,M]=o.useState(new Set),T=o.useRef(!1),B=o.useRef(!1),H=()=>{const X=y.current;return X?X.scrollHeight-X.scrollTop-X.clientHeight<200:!0},C=o.useCallback((X="auto")=>{const he=y.current;he&&he.scrollTo({top:he.scrollHeight,behavior:X})},[]),R=o.useCallback(()=>{var ue;const X=y.current,he=(ue=window.getSelection)==null?void 0:ue.call(window);if(!X||!he||he.rangeCount===0||he.isCollapsed){E.current=!1;return}const J=he.anchorNode,Z=he.focusNode;E.current=!!(J&&Z&&X.contains(J)&&X.contains(Z))},[]),U=nu(s),N=o.useCallback(()=>{const X=y.current;!X||!l||Dn.set(l,{top:X.scrollTop,fromBottom:Math.max(0,X.scrollHeight-X.scrollTop-X.clientHeight),messageFingerprint:U})},[l,U]),D=o.useCallback((X="auto")=>{j.current!=null&&cancelAnimationFrame(j.current),j.current=requestAnimationFrame(()=>{j.current=null,C(X)})},[C]);o.useEffect(()=>{const X=!I.current,he=k.current!==l;if(k.current=l,X||he){if(I.current=!0,T.current=!1,v.current=!0,!E.current){const Z=l?Dn.get(l):null;Z&&_o(Z,U)?requestAnimationFrame(()=>{const ue=y.current;ue&&(Ro(ue,Z),B.current=!0)}):D("auto")}_.current=s.length;return}s.length>_.current?!T.current&&!E.current&&D("auto"):H()&&!T.current&&!E.current&&D("auto"),_.current=s.length},[U,l,c,s.length,D]),o.useEffect(()=>{d&&(T.current=!1,v.current=!0,B.current=!0,x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{v.current=!1,x.current=null},180),E.current||D("auto"))},[D,d]),o.useEffect(()=>()=>{N(),j.current!=null&&cancelAnimationFrame(j.current),x.current!=null&&window.clearTimeout(x.current)},[N]),o.useEffect(()=>{const X=h.current;if(!X)return;const he=()=>{x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{v.current=!1,x.current=null},180)},J=new ResizeObserver(()=>{v.current&&(E.current||(D("auto"),he()))});return J.observe(X),()=>{J.disconnect(),x.current!=null&&(window.clearTimeout(x.current),x.current=null)}},[D,l]),o.useImperativeHandle(b,()=>({scrollToBottom:(X="smooth")=>{C(X)}}),[C]),o.useEffect(()=>{const X=y.current;if(!X)return;let he;const J=()=>{clearTimeout(he),he=setTimeout(()=>{T.current=!H(),N()},50)};return X.addEventListener("scroll",J,{passive:!0}),()=>{X.removeEventListener("scroll",J),clearTimeout(he)}},[N]),o.useEffect(()=>(document.addEventListener("selectionchange",R),()=>document.removeEventListener("selectionchange",R)),[R]);const Y=o.useRef(0),q=o.useRef(!1);o.useEffect(()=>{const X=y.current;if(!X||!q.current||Y.current===0)return;const he=X.scrollHeight-Y.current;he>0&&(X.scrollTop=he),N(),Y.current=0,q.current=!1},[s.length,N]),o.useEffect(()=>{if(B.current||!l)return;const X=Dn.get(l),he=y.current;if(!(!X||!he)){if(!_o(X,U)){C("auto"),B.current=!0;return}Ro(he,X),B.current=!0}},[l,U,s.length,C]);const W=()=>{const X=y.current;X&&(Y.current=X.scrollHeight),q.current=!0,m==null||m()},ae=o.useMemo(()=>{const X=s.map((ue,de)=>({type:"message",data:ue,index:de,ts:au(ue,de,u)}));if(!r||r.length===0)return X;const he=[...r].sort((ue,de)=>ue.timestamp-de.timestamp).map((ue,de)=>({type:"action",data:ue,index:de,ts:ue.timestamp})),J=[];let Z=0;for(const ue of X){for(;Z<he.length&&ue.ts>0&&he[Z].ts<ue.ts;)J.push(he[Z++]);J.push(ue)}for(;Z<he.length;)J.push(he[Z++]);return J},[s,r,u]),ce=w>0||!!g,Se=w>0?`↑ Show ${Math.min(w,80)} earlier messages${w>80?` (${w} hidden)`:""}`:A?`↻ ${A}`:"↑ Load older messages";return t.jsx("div",{ref:y,"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..."}),ce&&!f&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:W,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${A&&w===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:Se})}),ae.length===0&&!ce&&(p||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ae.map(X=>{if(X.type==="action"){const ye=X.data;return t.jsx(iu,{log:ye},`action-${X.index}`)}const he=X.data,J=X.index,Z=_s(he,J),ue=he.receivedAt||u[Z],de=`${l}-${Z}`,z=L.has(de);return t.jsx(cu,{message:he,receivedAt:ue,agentName:n,userName:a,isCliMode:i,isTextExpanded:z,onToggleTextExpanded:()=>M(ye=>{const ie=new Set(ye);return z?ie.delete(de):ie.add(de),ie})},`msg-${Z}`)}),c&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:S})]})})}),du=o.memo(lu,(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),uu="modulepreload",mu=function(e){return"/"+e},Do={},pu=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=mu(u),u in Do)return;Do[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":uu,p||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),p)return new Promise((g,w)=>{f.addEventListener("load",g),f.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})};let Eo=!1;const Zi=o.forwardRef(({onInput:e,fontSize:s=13,readOnly:r=!1,sizingMode:n="measured"},a)=>{const i=o.useRef(null),[c,l]=o.useState(null),u=o.useRef([]),p=o.useRef(!1),m=o.useRef(!1),f=o.useRef(!1),g=()=>{const w=i.current;if(w){p.current&&(w.clear(),p.current=!1);for(const A of u.current)w.write(A);u.current=[],m.current&&(w.fit(),m.current=!1),f.current&&(w.bumpResize(),f.current=!1)}};return o.useImperativeHandle(a,()=>({write:w=>{i.current?i.current.write(w):u.current.push(w)},clear:()=>{i.current?i.current.clear():(u.current=[],p.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(u.current=[],p.current=!0)},resize:(w,A)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(w,A)},fit:()=>{i.current?i.current.fit():m.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():f.current=!0}}),[]),o.useEffect(()=>{if(!c)return;const w=requestAnimationFrame(()=>{g()});return()=>cancelAnimationFrame(w)},[c]),o.useEffect(()=>{let w=!1;return pu(()=>import("./terminal-2SYILvaH.js"),__vite__mapDeps([0,1,2])).then(A=>{Eo||(Eo=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),w||l(()=>A.GhosttyTerminalView)}).catch(A=>{console.error("[CliTerminal] failed to load terminal renderer",A)}),()=>{w=!0}},[]),c?t.jsx(c,{ref:i,onInput:e,fontSize:s,readOnly:r,sizingMode:n,className:"w-full h-full rounded-lg overflow-hidden"}):t.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Zi.displayName="CliTerminal";function Pr({label:e,value:s,sub:r,icon:n}){return t.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[t.jsx("span",{className:"text-base flex items-center",children:n}),t.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),t.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function $o({value:e,max:s,label:r,color:n="#8b5cf6",detail:a,compact:i=!1}){const c=s>0?Math.min(Math.round(e/s*100),100):0,l=c>85?"#ef4444":c>60?"var(--status-warning)":n;return i?t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-0.5",children:[t.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),t.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${c}%`,background:l}})})]}):t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-1.5",children:[t.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),t.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[c,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${c}%`,background:`linear-gradient(90deg, ${l}, ${l}cc)`}})}),a&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function fu({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,g,w;u>p?(m=a.width,f=a.width/u,g=0,w=(a.height-f)/2):(f=a.height,m=a.height*u,g=(a.width-m)/2,w=0);const A=a.left-i.left+g+m*e.nx,d=a.top-i.top+w+f*e.ny,b=Math.max(8,Math.min(i.width-8,A)),y=Math.max(8,Math.min(i.height-8,d));return t.jsxs("div",{style:{position:"absolute",left:b-8,top:y-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 hu({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:g,onZoomOut:w,onZoomReset:A,onZoomIn:d,transportType:b,screenshotUsage:y,lastActionStatus:h}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:S=>S.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[t.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[t.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),t.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("div",{onClick:()=>{n(S=>!S),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&t.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:t.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:S=>S.stopPropagation(),onChange:S=>l(S.target.value),onKeyDown:S=>{u(S)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),t.jsx("div",{className:"relative",children:t.jsx("div",{onClick:()=>{i(S=>!S),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⚙️"})})}),t.jsx("div",{className:"w-px h-[18px] bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:p?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:p?"Connected":"WS"})]}),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"}),y&&y.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),h&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:h})]})]}),a&&t.jsxs("div",{onTouchStart:S=>S.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",m<=(f?g:1)+.01?f?"FILL":"FIT":`${Math.round(m*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:S=>{S.stopPropagation(),w()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),t.jsx("button",{onClick:S=>{S.stopPropagation(),A()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:f?"FILL":"FIT"}),t.jsx("button",{onClick:S=>{S.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 xu({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 bu(){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 Ko(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 wr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!bu())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,Ko(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,Ko(s[c])]))}),r.current=s})}function gu({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:g,onAction:w,setLastActionStatus:A,spawnRippleFromNormalized:d,clampPan:b,isMobile:y,mobileFillZoom:h}){const[S,_]=o.useState(null),k=o.useRef(null),I=o.useRef(null),j=o.useRef(null),v=o.useRef(!1),x=o.useRef(null),E=o.useRef(0),L=o.useRef(null),M=o.useRef(1),T=o.useRef({x:0,y:0}),B=o.useRef(!1),H=o.useRef(n),C=o.useRef(w),R=30,U=550,N=18,D=60,Y=400,q=12,W=()=>{if(k.current)return;const Se={nx:.5,ny:.5};k.current=Se,_(Se)};return o.useEffect(()=>{H.current=n,n==="mouse"&&W()},[n]),o.useEffect(()=>{C.current=w},[w]),o.useEffect(()=>{const Se=e.current;if(!Se)return;const X=z=>{if(!r.current)return null;const ye=r.current.getBoundingClientRect();return!ye.width||!ye.height?null:{nx:Math.max(0,Math.min(1,(z.clientX-ye.left)/ye.width)),ny:Math.max(0,Math.min(1,(z.clientY-ye.top)/ye.height))}},he=(z,ye)=>{if(!r.current)return{dnx:0,dny:0};const ie=r.current,le=ie.getBoundingClientRect(),se=ie.naturalWidth||le.width,pe=ie.naturalHeight||le.height,ne=se/pe,ke=le.width/le.height;let ve,K;return ne>ke?(ve=le.width,K=le.width/ne):(K=le.height,ve=le.height*ne),{dnx:z/ve,dny:ye/K}},J=(z,ye,ie)=>{if(ie<=1.05)return;const le=-(z-.5)*100,se=-(ye-.5)*100,pe=b(le,se,ie);(Math.abs(pe.x-l.current)>.1||Math.abs(pe.y-u.current)>.1)&&(p(pe.x),m(pe.y),l.current=pe.x,u.current=pe.y)},Z=z=>{const ye=s.current;if(ye&&z.target instanceof Node&&ye.contains(z.target))z.preventDefault();else return;if(z.touches.length===1){const ie=z.touches[0];I.current={x:ie.clientX,y:ie.clientY,time:Date.now()},j.current={x:ie.clientX,y:ie.clientY},B.current||(v.current=!1),x.current=setTimeout(()=>{if(!v.current&&!B.current)if(v.current=!0,H.current==="mouse"){const le=k.current||{nx:.5,ny:.5};A("Right Click"),d(le.nx,le.ny,"right"),C.current("input_click",{...le,button:"right"}).catch(()=>{})}else{const le=X(ie);le&&(A("Right Click"),d(le.nx,le.ny,"right"),C.current("input_click",{...le,button:"right"}).catch(()=>{}))}},500);return}if(z.touches.length===2){x.current&&clearTimeout(x.current),v.current=!0,B.current=!0;const ie=z.touches[1].clientX-z.touches[0].clientX,le=z.touches[1].clientY-z.touches[0].clientY;L.current=Math.sqrt(ie*ie+le*le),M.current=c.current,T.current={x:(z.touches[0].clientX+z.touches[1].clientX)/2,y:(z.touches[0].clientY+z.touches[1].clientY)/2}}},ue=z=>{const ye=s.current;if(ye&&z.target instanceof Node&&ye.contains(z.target)&&z.preventDefault(),z.touches.length===1&&j.current){const ie=z.touches[0],le=ie.clientX-j.current.x,se=ie.clientY-j.current.y;if(!v.current&&I.current){const pe=ie.clientX-I.current.x,ne=ie.clientY-I.current.y;Math.sqrt(pe*pe+ne*ne)>8&&(v.current=!0,x.current&&clearTimeout(x.current))}if(v.current)if(H.current==="mouse"){const pe=he(le,se),ne=k.current||{nx:.5,ny:.5},ke=Math.max(0,Math.min(1,ne.nx+pe.dnx)),ve=Math.max(0,Math.min(1,ne.ny+pe.dny));k.current={nx:ke,ny:ve},_({nx:ke,ny:ve}),A(`Cursor: ${Math.round(ke*100)}%, ${Math.round(ve*100)}%`),J(ke,ve,c.current);const K=Date.now();K-g.current>=30&&(g.current=K,C.current("input_mouseMoved",{nx:ke,ny:ve}).catch(()=>{}))}else if(c.current>1){const pe=s.current;if(pe){const ne=pe.clientWidth,ke=pe.clientHeight,ve=l.current+le/ne*100,K=u.current+se/ke*100,V=b(ve,K,c.current);p(V.x),m(V.y),l.current=V.x,u.current=V.y}}else{const pe=X(ie);if(pe){const ne=Date.now();ne-g.current>=40&&(g.current=ne,A("Scroll"),C.current("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(-le*2.5),deltaY:Math.round(-se*2.5)}).catch(()=>{}))}}j.current={x:ie.clientX,y:ie.clientY};return}if(z.touches.length===2&&L.current!==null){const ie=z.touches[1].clientX-z.touches[0].clientX,le=z.touches[1].clientY-z.touches[0].clientY,pe=Math.sqrt(ie*ie+le*le)/L.current,ne=(z.touches[0].clientX+z.touches[1].clientX)/2,ke=(z.touches[0].clientY+z.touches[1].clientY)/2,ve=ne-T.current.x,K=ke-T.current.y,V=Math.abs(pe-1)>.03;if(H.current==="mouse"){if(V){const we=Math.max(i,Math.min(5,M.current*pe));f(we),c.current=we}else if(Math.abs(ve)>2||Math.abs(K)>2){const we=k.current||{nx:.5,ny:.5},be=Date.now();be-g.current>=30&&(g.current=be,A("Scroll"),C.current("input_wheel",{nx:we.nx,ny:we.ny,deltaX:Math.round(-ve*3),deltaY:Math.round(-K*3)}).catch(()=>{}))}}else{const we=Math.max(i,Math.min(5,M.current*pe));f(we),c.current=we;const be=s.current;if(be&&we>1){const Q=be.clientWidth,Me=be.clientHeight,Oe=l.current+ve/Q*100,Pe=u.current+K/Me*100,Ke=b(Oe,Pe,we);p(Ke.x),m(Ke.y),l.current=Ke.x,u.current=Ke.y}}T.current={x:ne,y:ke}}},de=z=>{var ye;if(x.current&&clearTimeout(x.current),L.current=null,z.touches.length===1&&B.current){const ie=z.touches[0];I.current={x:ie.clientX,y:ie.clientY,time:Date.now()},j.current={x:ie.clientX,y:ie.clientY},v.current=!0;return}if(z.touches.length===0){if(B.current){B.current=!1,v.current=!1;return}if(z.changedTouches.length===1){const ie=z.changedTouches[0],le=Date.now(),se=le-(((ye=I.current)==null?void 0:ye.time)||0),pe=I.current?ie.clientX-I.current.x:0,ne=I.current?ie.clientY-I.current.y:0,ke=Math.sqrt(pe*pe+ne*ne);if(H.current==="mouse"){if(se<R||se>U||ke>N){v.current=!1;return}const ve=k.current||X(ie);ve&&(A(`Click: ${Math.round(ve.nx*100)}%, ${Math.round(ve.ny*100)}%`),d(ve.nx,ve.ny,"left"),C.current("input_click",{...ve}).catch(()=>{}))}else{if(v.current){v.current=!1;return}if(se<D||se>Y||ke>q){v.current=!1;return}const ve=X(ie);if(!ve)return;le-E.current<300?(A("Double tap"),d(ve.nx,ve.ny,"double"),C.current("input_click",{...ve,clickCount:2}).catch(()=>{}),E.current=0):(A(`Tap: ${Math.round(ve.nx*100)}%, ${Math.round(ve.ny*100)}%`),d(ve.nx,ve.ny,"left"),C.current("input_click",{...ve}).catch(()=>{}),E.current=le)}}v.current=!1}};return Se.addEventListener("touchstart",Z,{passive:!1}),Se.addEventListener("touchmove",ue,{passive:!1}),Se.addEventListener("touchend",de,{passive:!1}),()=>{Se.removeEventListener("touchstart",Z),Se.removeEventListener("touchmove",ue),Se.removeEventListener("touchend",de),x.current&&clearTimeout(x.current)}},[e,s,r,i,c,l,u,p,m,f,g,A,d,b]),{cursorPos:S,cursorPosRef:k,handleToggleInputMode:()=>{a(Se=>{const X=Se==="touch"?"mouse":"touch";return X==="mouse"&&W(),X})},handleZoomReset:()=>{const Se=y?h:1;f(Se),c.current=Se,p(0),m(0),l.current=0,u.current=0}}}function ec({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,g]=o.useState(""),[,w]=o.useState(!1),[A,d]=o.useState([]),b=o.useRef(0),[y,h]=o.useState(!1),[S,_]=o.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[I,j]=o.useState(k?"mouse":"touch"),[v,x]=o.useState(1),E=o.useRef(!1),[L,M]=o.useState(1),[T,B]=o.useState(0),[H,C]=o.useState(0);wr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:I,zoom:L,panX:T,panY:H,isMenuOpen:y,isImeOpen:S});const R=o.useRef(0),U=o.useRef(L),N=o.useRef(T),D=o.useRef(H);o.useEffect(()=>{U.current=L},[L]),o.useEffect(()=>{N.current=T},[T]),o.useEffect(()=>{D.current=H},[H]),o.useEffect(()=>{var se;(se=c.current)==null||se.focus()},[]);const Y=r==="connected",q=n,W=Y?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ae=Y?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!k||E.current||!q)return;const se=u.current,pe=l.current;if(!se||!pe)return;const ne=()=>{const ke=pe.clientWidth,ve=pe.clientHeight,K=se.naturalWidth,V=se.naturalHeight;if(!K||!V||!ke||!ve)return;const we=Math.min(ke/K,ve/V),Q=Math.max(ke/K,ve/V)/we;Q>1.01&&(x(Q),M(Q),U.current=Q),E.current=!0};se.complete&&se.naturalWidth?ne():se.addEventListener("load",ne,{once:!0})},[q,k]);const ce=.5;o.useEffect(()=>{L<=ce&&(B(0),C(0))},[L,ce]);const Se=(se,pe,ne)=>{if(ne<=ce)return{x:0,y:0};const ke=(ne-1)/(2*ne)*100,ve=(ne-1)/(2*ne)*100;return{x:Math.max(-ke,Math.min(ke,se)),y:Math.max(-ve,Math.min(ve,pe))}},X=(se,pe)=>{if(!u.current)return null;const ne=u.current.getBoundingClientRect();return!ne.width||!ne.height?null:{nx:Math.max(0,Math.min(1,(se-ne.left)/ne.width)),ny:Math.max(0,Math.min(1,(pe-ne.top)/ne.height))}},he=(se,pe,ne)=>{const ke=l.current;if(!ke)return;const ve=ke.getBoundingClientRect(),K=++b.current;d(V=>[...V,{id:K,x:se-ve.left,y:pe-ve.top,type:ne}]),setTimeout(()=>d(V=>V.filter(we=>we.id!==K)),600)},J=(se,pe,ne)=>{const ke=u.current,ve=l.current;if(!ke||!ve)return;const K=ke.getBoundingClientRect(),V=ve.getBoundingClientRect(),we=ke.naturalWidth||K.width,be=ke.naturalHeight||K.height,Q=we/be,Me=K.width/K.height;let Oe,Pe,Ke,Qe;Q>Me?(Oe=K.width,Pe=K.width/Q,Ke=0,Qe=(K.height-Pe)/2):(Pe=K.height,Oe=K.height*Q,Ke=(K.width-Oe)/2,Qe=0);const Ge=K.left-V.left+Ke+Oe*se,ut=K.top-V.top+Qe+Pe*pe,it=++b.current;d(ht=>[...ht,{id:it,x:Ge,y:ut,type:ne}]),setTimeout(()=>d(ht=>ht.filter(ze=>ze.id!==it)),600)},Z=async se=>{var ne;const pe=X(se.clientX,se.clientY);if(pe){m(`Click: ${Math.round(pe.nx*100)}%, ${Math.round(pe.ny*100)}%`),he(se.clientX,se.clientY,"left"),(ne=c.current)==null||ne.focus();try{const ke=await e("input_click",{nx:pe.nx,ny:pe.ny});ke!=null&&ke.success||s(`❌ Click failed: ${ke==null?void 0:ke.error}`)}catch(ke){s(`❌ Click error: ${ke.message||ke}`)}}},ue=async(se,pe,ne,ke=0)=>{try{await e("input_key",{type:ne?"char":"keyDown",key:se,code:pe,text:ne?se:void 0,unmodifiedText:ne?se:void 0,modifiers:ke})}catch(ve){s(`❌ Key error: ${ve.message||ve}`)}},de=async se=>{if(se.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(se.key)&&se.preventDefault();let ne=0;se.altKey&&(ne|=1),se.ctrlKey&&(ne|=2),se.metaKey&&(ne|=4),se.shiftKey&&(ne|=8),m(`Key: ${se.key}`),await ue(se.key,se.code,se.key.length===1,ne)},z=async se=>{if(se.key==="Enter"){if(se.nativeEvent.isComposing)return;if(f){const pe=f;g(""),m(`IME Sent: ${pe}`);try{const ne=await e("input_type",{text:pe});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 ue("Enter","Enter",!1)}};o.useEffect(()=>{const se=c.current;if(!se)return;const pe=ne=>{var ke;if((ke=u.current)!=null&&ke.contains(ne.target)){ne.preventDefault();const ve=Date.now();if(ve-R.current<40)return;R.current=ve;const K=X(ne.clientX,ne.clientY);if(!K)return;m(`Scroll: ${Math.round(ne.deltaY)}`),e("input_wheel",{nx:K.nx,ny:K.ny,deltaX:Math.round(ne.deltaX),deltaY:Math.round(ne.deltaY)}).catch(()=>{})}};return se.addEventListener("wheel",pe,{passive:!1}),()=>se.removeEventListener("wheel",pe)},[e]);const{cursorPos:ye,handleToggleInputMode:ie,handleZoomReset:le}=gu({containerRef:c,viewportRef:l,imgRef:u,inputMode:I,setInputMode:j,minZoom:ce,zoomRef:U,panXRef:N,panYRef:D,setPanX:B,setPanY:C,setZoom:M,lastWheelTimeRef:R,onAction:e,setLastActionStatus:m,spawnRippleFromNormalized:J,clampPan:Se,isMobile:k,mobileFillZoom:v});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:de,onContextMenu:se=>se.preventDefault(),onFocus:()=>w(!0),onBlur:()=>w(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[q?t.jsx("img",{ref:u,src:q,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${T}%, ${H}%)`,transformOrigin:"center center",cursor:I==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:Z,onContextMenu:se=>se.preventDefault(),onDragStart:se=>se.preventDefault()}):t.jsx(xu,{waitingLabel:W,waitingHint:ae,transportType:i}),I==="mouse"&&q&&t.jsx(fu,{cursorPos:ye,viewportRef:l,imgRef:u}),A.map(se=>{const ne={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[se.type];return t.jsxs("div",{style:{position:"absolute",left:se.x,top:se.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${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}})]},se.id)})]}),t.jsx(hu,{inputMode:I,onToggleInputMode:ie,isImeOpen:S,setIsImeOpen:_,isMenuOpen:y,setIsMenuOpen:h,imeText:f,setImeText:g,handleImeSubmit:z,isConnActive:Y,zoom:L,isMobile:k,mobileFillZoom:v,onZoomOut:()=>M(se=>Math.max(.5,se-.25)),onZoomReset:le,onZoomIn:()=>M(se=>Math.min(5,se+.25)),transportType:i,screenshotUsage:a,lastActionStatus:p}),t.jsx("style",{children:`
|
|
5
5
|
@keyframes slideUp {
|
|
6
6
|
from { opacity: 0; transform: translateY(6px); }
|
|
7
7
|
to { opacity: 1; transform: translateY(0); }
|
|
@@ -24,56 +24,56 @@ var ld=Object.defineProperty;var dd=(e,s,r)=>s in e?ld(e,s,{enumerable:!0,config
|
|
|
24
24
|
50% { transform: translateY(-7px); }
|
|
25
25
|
100% { transform: translateY(0px); }
|
|
26
26
|
}
|
|
27
|
-
`})]})}function It(e){return(typeof e=="string"?e.trim():"")||void 0}function Jt(e,s){const r=It(s);return r?`${e}:${r}`:void 0}function ss(e,s,r){const n=Jt(s,r),a=It(r);n&&e.push(n),a&&e.push(a)}function Rs(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function ec(e){return It(e.providerSessionId)||It(e.sessionId)||It(e.tabKey)||It(e.routeId)}function Ka(e){return Rs([It(e.providerSessionId),It(e.sessionId)])}function rs(e){const s=[];return ss(s,"provider",e.providerSessionId),ss(s,"session",e.sessionId),ss(s,"tab",e.tabKey),ss(s,"route",e.routeId),Rs(s)}function gu(e){const s=[];return It(e.providerSessionId)?(ss(s,"provider",e.providerSessionId),Rs(s)):It(e.sessionId)?(ss(s,"session",e.sessionId),Rs(s)):It(e.tabKey)?(ss(s,"tab",e.tabKey),Rs(s)):It(e.routeId)?(ss(s,"route",e.routeId),Rs(s)):[]}function Ba(e){return Jt("provider",e.providerSessionId)||Jt("session",e.sessionId)||Jt("tab",e.tabKey)||Jt("route",e.routeId)||"unknown:"}function jr(e){return Ka(e)[0]}function tc(e){const s=It(e.providerSessionId),r=It(e.sessionId),n=It(e.tabKey),a=It(e.routeId),i=[Jt("provider",s),Jt("session",r),Jt("tab",n),Jt("route",a)].filter(u=>typeof u=="string"),c=rs({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=Ba({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:ec({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:jr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function hr(e,s){const r=tc(e);return gu(s).some(n=>r.lookupKeys.includes(n))}function vn(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 sc=e=>vn(e);function yu(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function qs(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:a}}function vu(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...yu(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 ln(e,s){if(e.sessionId){const r=s.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function wn(e,s,r){const n=ln(e,s),a=qs(e),i=rs(e).map(A=>{var d;return(d=r==null?void 0:r.notificationStateBySessionId)==null?void 0:d.get(A)}).find(A=>!!A),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,w=!!(n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:w,requiresAction:m,isWorking:f,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:p,inboxBucket:m?"needs_attention":f?"working":w?"task_complete":"idle"}}function wu(e,s,r){return wn(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation,notificationStateBySessionId:r==null?void 0:r.notificationStateBySessionId}).unread}function rc({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!qs(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),s(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return t.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&t.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[t.jsx(ks,{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),g=r===l,w=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:w,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"font-extrabold":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!g?"opacity-40":"opacity-100"} ${w?"cursor-not-allowed":"cursor-pointer"}`,style: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:g?"⏳ ...":c(l)},u)})})]})]})}const Oa="adhdev_controls_bar_visible",fa="adhdev:controlsbarvisibilitychange";function $n(e){if(!e)return!1;try{return e.getItem(Oa)==="1"}catch{return!1}}function Bo(e,s){if(s)try{s.setItem(Oa,e?"1":"0")}catch{}}function Oo(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(fa,{detail:{visible:e}}))}function nc(){const[e,s]=o.useState(()=>typeof window>"u"?!1:$n(window.localStorage));o.useEffect(()=>{const a=c=>{const l=c.detail;if(typeof(l==null?void 0:l.visible)=="boolean"){s(l.visible);return}s($n(window.localStorage))},i=c=>{c.key===Oa&&s($n(window.localStorage))};return window.addEventListener(fa,a),window.addEventListener("storage",i),()=>{window.removeEventListener(fa,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{s(a),typeof window<"u"&&Bo(a,window.localStorage),Oo(a)},[]),n=o.useCallback(()=>{s(a=>{const i=!a;return typeof window<"u"&&Bo(i,window.localStorage),Oo(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var ju=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function ku(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function Ct(e,s){if(ku(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":ju.has(r)?"generating":r==="error"?"error":r==="stopped"?"stopped":r==="starting"?"starting":r==="panel_hidden"?"panel_hidden":r==="not_monitored"?"not_monitored":r==="disconnected"?"disconnected":"idle"}function ac(e){return Ct(e)==="generating"}function ot(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function Su(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 Kn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function jn(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 Nu(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 Cu(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Iu(e){return Nu(e.trim().replace(/\.local$/i,""))}function Au(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function oc(e,s={}){var a,i;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(i=e.system)==null?void 0:i.hostname].find(c=>typeof c=="string"&&c.trim().length>0&&!Cu(c));if(r&&r!=="Unknown")return Iu(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function _t(e,s={}){return Au(e)||oc(e,s)}function ic(e){return!e||!Array.isArray(e.items)?[]:e.items.map(s=>String((s==null?void 0:s.value)||(s==null?void 0:s.shortValue)||"").trim()).filter(Boolean)}function cc(e,s,r={}){const n=String(s).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function Ss(e,s){return ic(e).join(" · ")}function xr(e){return e.transport==="pty"}function Ps(e){return e.transport==="acp"}function Mu(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 Wo(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 Tu(e){return Ct(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Lu(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=Ct(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 _u(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 Ru(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&&_u(s.receivedAt)||0}function Pu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ha(e){return Math.max(Pu(e),Ru(e.activeChat))}function Du(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 Wa(e,s){return Du(ha(e),ha(s),_t(e,{fallbackId:e.id}),_t(s,{fallbackId:s.id}),e.id,s.id)}const lc="adhdev_notification_prefs",Ho={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Eu(){try{const e=localStorage.getItem(lc);if(e){const s=JSON.parse(e);return{...Ho,...s}}}catch{}return{...Ho}}function $u(e){try{localStorage.setItem(lc,JSON.stringify(e))}catch{}}let Xt=Eu(),Jr=[];function Ku(){Jr.forEach(e=>e())}function Bu(e){Xt={...Xt,...e},$u(Xt),Ku()}function Ou(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Jr.push(r),()=>{Jr=Jr.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{Bu(r)},[]);return[{...Xt},s]}function ir(e){if(!Xt.globalEnabled)return!1;switch(e){case"disconnect":return Xt.disconnectAlert;case"completion":return Xt.completionAlert;case"approval":return Xt.approvalAlert;case"browser":return Xt.browserNotifications;default:return!0}}const Wu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function dc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function uc(){return"Notification"in window&&Notification.permission==="granted"}let ls=null;async function Hu(){if(ls!==null)return ls;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ls=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ls=!!await e.pushManager.getSubscription(),ls):(ls=!1,!1)}catch{return ls=!1,!1}}function xa(e,s,r){if(uc())try{const n=new Notification(e,{body:s,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function Fu(e,s={}){const r={...Wu,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Hu().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,p)=>{const m=Date.now();m-a.current<r.throttleMs||(a.current=m,xa(l,u,p))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!uc())&&ir("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,Ct(u.status,{activeModal:u.activeModal}));return}for(const u of e){const p=n.current.get(u.id),m=Ct(u.status,{activeModal:u.activeModal}),f=u.name||u.id;if(r.onApproval&&ir("approval")&&m==="waiting_approval"&&p!=="waiting_approval"){const g=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,g.slice(0,120),`approval-${u.id}`)}r.onComplete&&ir("completion")&&ac(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 Uu=/^(run|approve|accept|yes|allow|always)/,zu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Vu=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ha(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Gu(e){const s=Ha(e).toLowerCase();return Uu.test(s)?"primary":Vu.test(s)?"danger":"default"}function qu(e){return zu.test(Ha(e).toLowerCase())?"approve":"reject"}function Yu(e){return e.map((s,r)=>({label:Ha(s),variant:Gu(s),action:qu(s),button:s,buttonIndex:r}))}function Xu(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 Ju(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Qu(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 Zu{constructor(){Ye(this,"dedupMap",new Map);Ye(this,"DEDUP_WINDOW_MS",5e3);Ye(this,"DEDUP_MAX_SIZE",50);Ye(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ye(this,"toastCallbacks",[]);Ye(this,"systemMessageCallbacks",[]);Ye(this,"clearSystemMessageCallbacks",[]);Ye(this,"resolveActionFn",null);Ye(this,"viewRequestRespondFn",null);Ye(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:s,type:r,timestamp:a,duration:5e3,...n})}emitSystemMessage(s,r){for(const n of this.systemMessageCallbacks)n(s,r)}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(s){if(s.daemonId){const a=this.ides.find(i=>i.id===s.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var A,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=_t(f,{fallbackId:f.id});b&&(m=!p||p==="adhdev-daemon"?b:`${b}/${m}`)}let g="",w="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";g=`✅ ${m} agent task completed${b}`,w="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(g=`⚡ ${m} approval needed`,w="warning",n&&!((A=s.modalButtons)!=null&&A.length)&&this.emitSystemMessage(n,{role:"system",timestamp:a,content:Xu(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 y=this.resolveActionFn,h=Yu(s.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{y(b,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),S=Ju(m,s.modalMessage,g),_=Date.now();this.emitToast({id:_,message:S,type:w,timestamp:_,targetKey:n||b,actions:h,duration:15e3}),g=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";g=`⚠️ ${m} agent is taking a long time${b}`,w="warning",ir("browser")&&!document.hasFocus()&&xa(`⚠️ ${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",y=s.requestId,h=s.orgId;if(g=`👁️ ${b} wants to view your session`,w="warning",y&&h&&this.viewRequestRespondFn){const S=Date.now(),_=Qu(h,y,this.viewRequestRespondFn,(k,I)=>console.error(`[EventManager] ${k} view request failed:`,I));this.emitToast({id:S,message:g,type:w,timestamp:S,actions:_,duration:3e4}),g=""}ir("browser")&&!document.hasFocus()&&xa("👁️ View Request",`${b} wants to view your session`,`view-request-${y}`)}else s.event==="team:view_request_approved"?(g="✅ View request approved",w="success"):s.event==="team:view_request_rejected"&&(g=`❌ ${s.targetName||"Team member"} declined your view request`,w="warning");if(g){const b=Date.now();this.emitToast({id:b,message:g,type:w,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const st=new Zu,Fo=new Map;function Ws(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ds(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function em(e){return!Ws(e)||!Ws(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function Dr(e){return!Ws(e)||!Ws(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function Qs(e){if(!(!Ws(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function Er(e){return Ws(e)&&e.success===!1}function tm(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";st.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";st.showToast(n.notification.body,a)}}}function sm(e,s){return e&&Ds(e.currentValue)?e.currentValue:s}function rm(e,s){return Ds(s)?Ds(e)?typeof e=="string"&&e.trim()==="":!0:!1}function nm(e,s){var i,c;if((s.now??Date.now())<s.localOverrideUntil){const l=s.localValues[e];if(Ds(l))return l}const n=(i=s.controlValues)==null?void 0:i[e];if(Ds(n))return n;const a=(c=s.defaultValues)==null?void 0:c[e];return Ds(a)?a:void 0}function Qr(e,s){return e.options||s[e.id]||[]}const am=new Set(["antigravity","claude-code-vscode","codex"]);function om(e,s,r){return r.id==="new_session"&&am.has(s)}function Fa(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!om(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Bn(e,s){return{value:s}}function im(e,s,r){var a;return r?((a=Qr(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const cm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function lm({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=Pt(),u=`${e}:${s||n}`,p=cm[n]||"#94a3b8",[m,f]=o.useState({}),g=o.useRef({}),w=o.useRef(c);g.current=m,w.current=c;const A=o.useRef(0),d={};for(const R of i||[])R.defaultValue!==void 0&&(d[R.id]=R.defaultValue);const b={...d,...c||{},...Date.now()<A.current?m:{}};o.useEffect(()=>{c&&Date.now()>A.current&&f({})},[c]);const[y,h]=o.useState(Fo.get(u)||{}),[S,_]=o.useState(null),[k,I]=o.useState(null),j=o.useCallback(async(R,U={})=>{const N={...U,...s&&{targetSessionId:s}};return await l(e,R,N)},[e,s,l]),v=o.useCallback(async(R,U={})=>{const N=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await j("invoke_provider_script",{...N,scriptName:R,...U})},[j,n,r,s]),x=o.useCallback((R,U,N)=>{const D=sm(N,U);f(Y=>({...Y,[R.id]:D})),tm(N==null?void 0:N.effects)},[]),E=o.useCallback((R,U)=>{f(N=>{const D={...N};return U===void 0?delete D[R.id]:D[R.id]=U,D}),A.current=0},[]);if(!i||i.length===0)return null;const L=Fa(i,{hostIdeType:r,providerType:n});if(L.length===0)return null;const M=async R=>{if(S===R.id){_(null);return}if(Qr(R,y).length>0){_(R.id);return}if(R.dynamic&&R.listScript){I(R.id);try{const N=await v(R.listScript,{}),D=em(N);if(!D){const W=Qs(N);W&&st.showToast(W,"warning");return}const Y=D.options;h(W=>{const ae={...W,[R.id]:Y};return Fo.set(u,ae),ae});const q=nm(R.id,{localOverrideUntil:A.current,localValues:g.current,controlValues:w.current,defaultValues:d});if(rm(q,D.currentValue)){const W=D.currentValue;f(ae=>({...ae,[R.id]:W}))}_(R.id)}catch(N){const D=N instanceof Error?N.message:`Could not load ${R.label}`;st.showToast(D,"warning")}finally{I(null)}}},T=async(R,U)=>{_(null);const N=(c==null?void 0:c[R.id])??d[R.id];f(D=>({...D,[R.id]:U})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const D=await v(R.setScript,Bn(R,U)),Y=Dr(D);if(Y&&!Y.ok||Er(D))throw new Error((Y==null?void 0:Y.error)||Qs(D)||`Could not update ${R.label}`);x(R,U,Y)}catch(D){E(R,N);const Y=D instanceof Error?D.message:`Could not update ${R.label}`;st.showToast(Y,"warning")}},B=async R=>{const U=Qr(R,y).map(ae=>ae.value);if(U.length===0)return;const N=String(b[R.id]||""),Y=(U.indexOf(N)+1)%U.length,q=U[Y];if(typeof q!="string")return;const W=(c==null?void 0:c[R.id])??d[R.id];f(ae=>({...ae,[R.id]:q})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const ae=await v(R.setScript,Bn(R,q)),ce=Dr(ae);if(ce&&!ce.ok||Er(ae))throw new Error((ce==null?void 0:ce.error)||Qs(ae)||`Could not update ${R.label}`);x(R,q,ce)}catch(ae){E(R,W);const ce=ae instanceof Error?ae.message:`Could not update ${R.label}`;st.showToast(ce,"warning")}},H=async R=>{const N=!b[R.id],D=(c==null?void 0:c[R.id])??d[R.id];f(Y=>({...Y,[R.id]:N})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const Y=await v(R.setScript,Bn(R,N)),q=Dr(Y);if(q&&!q.ok||Er(Y))throw new Error((q==null?void 0:q.error)||Qs(Y)||`Could not update ${R.label}`);x(R,N,q)}catch(Y){E(R,D);const q=Y instanceof Error?Y.message:`Could not update ${R.label}`;st.showToast(q,"warning")}},C=async R=>{if(!R.invokeScript)return;if(R.confirmMessage){const N=[R.confirmTitle,R.confirmMessage,R.confirmLabel].filter(Y=>typeof Y=="string"&&Y.trim().length>0);if(!window.confirm(N.join(`
|
|
27
|
+
`})]})}function It(e){return(typeof e=="string"?e.trim():"")||void 0}function Jt(e,s){const r=It(s);return r?`${e}:${r}`:void 0}function ss(e,s,r){const n=Jt(s,r),a=It(r);n&&e.push(n),a&&e.push(a)}function Rs(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function tc(e){return It(e.providerSessionId)||It(e.sessionId)||It(e.tabKey)||It(e.routeId)}function Ka(e){return Rs([It(e.providerSessionId),It(e.sessionId)])}function rs(e){const s=[];return ss(s,"provider",e.providerSessionId),ss(s,"session",e.sessionId),ss(s,"tab",e.tabKey),ss(s,"route",e.routeId),Rs(s)}function yu(e){const s=[];return It(e.providerSessionId)?(ss(s,"provider",e.providerSessionId),Rs(s)):It(e.sessionId)?(ss(s,"session",e.sessionId),Rs(s)):It(e.tabKey)?(ss(s,"tab",e.tabKey),Rs(s)):It(e.routeId)?(ss(s,"route",e.routeId),Rs(s)):[]}function Ba(e){return Jt("provider",e.providerSessionId)||Jt("session",e.sessionId)||Jt("tab",e.tabKey)||Jt("route",e.routeId)||"unknown:"}function jr(e){return Ka(e)[0]}function sc(e){const s=It(e.providerSessionId),r=It(e.sessionId),n=It(e.tabKey),a=It(e.routeId),i=[Jt("provider",s),Jt("session",r),Jt("tab",n),Jt("route",a)].filter(u=>typeof u=="string"),c=rs({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=Ba({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:tc({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:jr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function hr(e,s){const r=sc(e);return yu(s).some(n=>r.lookupKeys.includes(n))}function vn(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 rc=e=>vn(e);function vu(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function qs(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:a}}function wu(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...vu(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 ln(e,s){if(e.sessionId){const r=s.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function wn(e,s,r){const n=ln(e,s),a=qs(e),i=rs(e).map(A=>{var d;return(d=r==null?void 0:r.notificationStateBySessionId)==null?void 0:d.get(A)}).find(A=>!!A),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,w=!!(n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:w,requiresAction:m,isWorking:f,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:p,inboxBucket:m?"needs_attention":f?"working":w?"task_complete":"idle"}}function ju(e,s,r){return wn(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation,notificationStateBySessionId:r==null?void 0:r.notificationStateBySessionId}).unread}function nc({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!qs(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),s(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return t.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&t.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[t.jsx(ks,{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),g=r===l,w=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:w,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"font-extrabold":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!g?"opacity-40":"opacity-100"} ${w?"cursor-not-allowed":"cursor-pointer"}`,style: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:g?"⏳ ...":c(l)},u)})})]})]})}const Oa="adhdev_controls_bar_visible",fa="adhdev:controlsbarvisibilitychange";function $n(e){if(!e)return!1;try{return e.getItem(Oa)==="1"}catch{return!1}}function Bo(e,s){if(s)try{s.setItem(Oa,e?"1":"0")}catch{}}function Oo(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(fa,{detail:{visible:e}}))}function ac(){const[e,s]=o.useState(()=>typeof window>"u"?!1:$n(window.localStorage));o.useEffect(()=>{const a=c=>{const l=c.detail;if(typeof(l==null?void 0:l.visible)=="boolean"){s(l.visible);return}s($n(window.localStorage))},i=c=>{c.key===Oa&&s($n(window.localStorage))};return window.addEventListener(fa,a),window.addEventListener("storage",i),()=>{window.removeEventListener(fa,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{s(a),typeof window<"u"&&Bo(a,window.localStorage),Oo(a)},[]),n=o.useCallback(()=>{s(a=>{const i=!a;return typeof window<"u"&&Bo(i,window.localStorage),Oo(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var ku=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Su(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function Ct(e,s){if(Su(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":ku.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 oc(e){return Ct(e)==="generating"}function ot(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function Nu(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 Kn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function jn(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 Cu(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 Iu(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Au(e){return Cu(e.trim().replace(/\.local$/i,""))}function Mu(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function ic(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&&!Iu(c));if(r&&r!=="Unknown")return Au(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function _t(e,s={}){return Mu(e)||ic(e,s)}function cc(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 lc(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 Ss(e,s){return cc(e).join(" · ")}function xr(e){return e.transport==="pty"}function Ps(e){return e.transport==="acp"}function Tu(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 Wo(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 Lu(e){return Ct(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function _u(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=Ct(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 Ru(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 Pu(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&&Ru(s.receivedAt)||0}function Du(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ha(e){return Math.max(Du(e),Pu(e.activeChat))}function Eu(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 Wa(e,s){return Eu(ha(e),ha(s),_t(e,{fallbackId:e.id}),_t(s,{fallbackId:s.id}),e.id,s.id)}const dc="adhdev_notification_prefs",Ho={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function $u(){try{const e=localStorage.getItem(dc);if(e){const s=JSON.parse(e);return{...Ho,...s}}}catch{}return{...Ho}}function Ku(e){try{localStorage.setItem(dc,JSON.stringify(e))}catch{}}let Xt=$u(),Jr=[];function Bu(){Jr.forEach(e=>e())}function Ou(e){Xt={...Xt,...e},Ku(Xt),Bu()}function Wu(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Jr.push(r),()=>{Jr=Jr.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{Ou(r)},[]);return[{...Xt},s]}function ir(e){if(!Xt.globalEnabled)return!1;switch(e){case"disconnect":return Xt.disconnectAlert;case"completion":return Xt.completionAlert;case"approval":return Xt.approvalAlert;case"browser":return Xt.browserNotifications;default:return!0}}const Hu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function uc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function mc(){return"Notification"in window&&Notification.permission==="granted"}let ls=null;async function Fu(){if(ls!==null)return ls;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ls=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ls=!!await e.pushManager.getSubscription(),ls):(ls=!1,!1)}catch{return ls=!1,!1}}function xa(e,s,r){if(mc())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 Uu(e,s={}){const r={...Hu,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Fu().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,p)=>{const m=Date.now();m-a.current<r.throttleMs||(a.current=m,xa(l,u,p))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!mc())&&ir("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,Ct(u.status,{activeModal:u.activeModal}));return}for(const u of e){const p=n.current.get(u.id),m=Ct(u.status,{activeModal:u.activeModal}),f=u.name||u.id;if(r.onApproval&&ir("approval")&&m==="waiting_approval"&&p!=="waiting_approval"){const g=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,g.slice(0,120),`approval-${u.id}`)}r.onComplete&&ir("completion")&&oc(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 zu=/^(run|approve|accept|yes|allow|always)/,Vu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Gu=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ha(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function qu(e){const s=Ha(e).toLowerCase();return zu.test(s)?"primary":Gu.test(s)?"danger":"default"}function Yu(e){return Vu.test(Ha(e).toLowerCase())?"approve":"reject"}function Xu(e){return e.map((s,r)=>({label:Ha(s),variant:qu(s),action:Yu(s),button:s,buttonIndex:r}))}function Ju(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 Qu(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Zu(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 em{constructor(){Ye(this,"dedupMap",new Map);Ye(this,"DEDUP_WINDOW_MS",5e3);Ye(this,"DEDUP_MAX_SIZE",50);Ye(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ye(this,"toastCallbacks",[]);Ye(this,"systemMessageCallbacks",[]);Ye(this,"clearSystemMessageCallbacks",[]);Ye(this,"resolveActionFn",null);Ye(this,"viewRequestRespondFn",null);Ye(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:s,type:r,timestamp:a,duration:5e3,...n})}emitSystemMessage(s,r){for(const n of this.systemMessageCallbacks)n(s,r)}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(s){if(s.daemonId){const a=this.ides.find(i=>i.id===s.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var A,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=_t(f,{fallbackId:f.id});b&&(m=!p||p==="adhdev-daemon"?b:`${b}/${m}`)}let g="",w="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";g=`✅ ${m} agent task completed${b}`,w="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(g=`⚡ ${m} approval needed`,w="warning",n&&!((A=s.modalButtons)!=null&&A.length)&&this.emitSystemMessage(n,{role:"system",timestamp:a,content:Ju(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 y=this.resolveActionFn,h=Xu(s.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{y(b,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),S=Qu(m,s.modalMessage,g),_=Date.now();this.emitToast({id:_,message:S,type:w,timestamp:_,targetKey:n||b,actions:h,duration:15e3}),g=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";g=`⚠️ ${m} agent is taking a long time${b}`,w="warning",ir("browser")&&!document.hasFocus()&&xa(`⚠️ ${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",y=s.requestId,h=s.orgId;if(g=`👁️ ${b} wants to view your session`,w="warning",y&&h&&this.viewRequestRespondFn){const S=Date.now(),_=Zu(h,y,this.viewRequestRespondFn,(k,I)=>console.error(`[EventManager] ${k} view request failed:`,I));this.emitToast({id:S,message:g,type:w,timestamp:S,actions:_,duration:3e4}),g=""}ir("browser")&&!document.hasFocus()&&xa("👁️ View Request",`${b} wants to view your session`,`view-request-${y}`)}else s.event==="team:view_request_approved"?(g="✅ View request approved",w="success"):s.event==="team:view_request_rejected"&&(g=`❌ ${s.targetName||"Team member"} declined your view request`,w="warning");if(g){const b=Date.now();this.emitToast({id:b,message:g,type:w,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const st=new em,Fo=new Map;function Ws(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ds(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function tm(e){return!Ws(e)||!Ws(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function Dr(e){return!Ws(e)||!Ws(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function Qs(e){if(!(!Ws(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function Er(e){return Ws(e)&&e.success===!1}function sm(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";st.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";st.showToast(n.notification.body,a)}}}function rm(e,s){return e&&Ds(e.currentValue)?e.currentValue:s}function nm(e,s){return Ds(s)?Ds(e)?typeof e=="string"&&e.trim()==="":!0:!1}function am(e,s){var i,c;if((s.now??Date.now())<s.localOverrideUntil){const l=s.localValues[e];if(Ds(l))return l}const n=(i=s.controlValues)==null?void 0:i[e];if(Ds(n))return n;const a=(c=s.defaultValues)==null?void 0:c[e];return Ds(a)?a:void 0}function Qr(e,s){return e.options||s[e.id]||[]}const om=new Set(["antigravity","claude-code-vscode","codex"]);function im(e,s,r){return r.id==="new_session"&&om.has(s)}function Fa(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!im(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function Bn(e,s){return{value:s}}function cm(e,s,r){var a;return r?((a=Qr(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const lm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function dm({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=Pt(),u=`${e}:${s||n}`,p=lm[n]||"#94a3b8",[m,f]=o.useState({}),g=o.useRef({}),w=o.useRef(c);g.current=m,w.current=c;const A=o.useRef(0),d={};for(const R of i||[])R.defaultValue!==void 0&&(d[R.id]=R.defaultValue);const b={...d,...c||{},...Date.now()<A.current?m:{}};o.useEffect(()=>{c&&Date.now()>A.current&&f({})},[c]);const[y,h]=o.useState(Fo.get(u)||{}),[S,_]=o.useState(null),[k,I]=o.useState(null),j=o.useCallback(async(R,U={})=>{const N={...U,...s&&{targetSessionId:s}};return await l(e,R,N)},[e,s,l]),v=o.useCallback(async(R,U={})=>{const N=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await j("invoke_provider_script",{...N,scriptName:R,...U})},[j,n,r,s]),x=o.useCallback((R,U,N)=>{const D=rm(N,U);f(Y=>({...Y,[R.id]:D})),sm(N==null?void 0:N.effects)},[]),E=o.useCallback((R,U)=>{f(N=>{const D={...N};return U===void 0?delete D[R.id]:D[R.id]=U,D}),A.current=0},[]);if(!i||i.length===0)return null;const L=Fa(i,{hostIdeType:r,providerType:n});if(L.length===0)return null;const M=async R=>{if(S===R.id){_(null);return}if(Qr(R,y).length>0){_(R.id);return}if(R.dynamic&&R.listScript){I(R.id);try{const N=await v(R.listScript,{}),D=tm(N);if(!D){const W=Qs(N);W&&st.showToast(W,"warning");return}const Y=D.options;h(W=>{const ae={...W,[R.id]:Y};return Fo.set(u,ae),ae});const q=am(R.id,{localOverrideUntil:A.current,localValues:g.current,controlValues:w.current,defaultValues:d});if(nm(q,D.currentValue)){const W=D.currentValue;f(ae=>({...ae,[R.id]:W}))}_(R.id)}catch(N){const D=N instanceof Error?N.message:`Could not load ${R.label}`;st.showToast(D,"warning")}finally{I(null)}}},T=async(R,U)=>{_(null);const N=(c==null?void 0:c[R.id])??d[R.id];f(D=>({...D,[R.id]:U})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const D=await v(R.setScript,Bn(R,U)),Y=Dr(D);if(Y&&!Y.ok||Er(D))throw new Error((Y==null?void 0:Y.error)||Qs(D)||`Could not update ${R.label}`);x(R,U,Y)}catch(D){E(R,N);const Y=D instanceof Error?D.message:`Could not update ${R.label}`;st.showToast(Y,"warning")}},B=async R=>{const U=Qr(R,y).map(ae=>ae.value);if(U.length===0)return;const N=String(b[R.id]||""),Y=(U.indexOf(N)+1)%U.length,q=U[Y];if(typeof q!="string")return;const W=(c==null?void 0:c[R.id])??d[R.id];f(ae=>({...ae,[R.id]:q})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const ae=await v(R.setScript,Bn(R,q)),ce=Dr(ae);if(ce&&!ce.ok||Er(ae))throw new Error((ce==null?void 0:ce.error)||Qs(ae)||`Could not update ${R.label}`);x(R,q,ce)}catch(ae){E(R,W);const ce=ae instanceof Error?ae.message:`Could not update ${R.label}`;st.showToast(ce,"warning")}},H=async R=>{const N=!b[R.id],D=(c==null?void 0:c[R.id])??d[R.id];f(Y=>({...Y,[R.id]:N})),A.current=Date.now()+5e3;try{if(!R.setScript)return;const Y=await v(R.setScript,Bn(R,N)),q=Dr(Y);if(q&&!q.ok||Er(Y))throw new Error((q==null?void 0:q.error)||Qs(Y)||`Could not update ${R.label}`);x(R,N,q)}catch(Y){E(R,D);const q=Y instanceof Error?Y.message:`Could not update ${R.label}`;st.showToast(q,"warning")}},C=async R=>{if(!R.invokeScript)return;if(R.confirmMessage){const N=[R.confirmTitle,R.confirmMessage,R.confirmLabel].filter(Y=>typeof Y=="string"&&Y.trim().length>0);if(!window.confirm(N.join(`
|
|
29
29
|
|
|
30
|
-
`)))return}const U=(c==null?void 0:c[R.id])??d[R.id];try{const N=await v(R.invokeScript),D=Dr(N);if(D&&!D.ok||Er(N))throw new Error((D==null?void 0:D.error)||Qs(N)||`Could not run ${R.label}`);D&&x(R,U??!0,D)}catch(N){E(R,U);const D=N instanceof Error?N.message:`Could not run ${R.label}`;st.showToast(D,"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:"│"}),L.map(R=>{const U=String(b[R.id]||""),N=im(R,y,U),D=S===R.id,Y=k===R.id,q=Qr(R,y);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:D?`${p}55`:"transparent",border:"1px solid",color:U?"var(--text-primary)":"var(--text-muted)"},onClick:()=>M(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),Y?"...":N||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),D&&q.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>_(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] 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()}),q.map(W=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:W.value===U?`${p}18`:"transparent",color:W.value===U?p:"var(--text-secondary)",fontWeight:W.value===U?600:400,borderLeft:W.value===U?`2px solid ${p}`:"2px solid transparent"},title:W.description||W.label,onMouseEnter:ae=>{ae.currentTarget.style.background=`${p}12`},onMouseLeave:ae=>{ae.currentTarget.style.background=W.value===U?`${p}18`:"transparent"},onClick:()=>T(R,W.value),children:W.label},W.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:U?"var(--text-primary)":"var(--text-muted)"},onClick:()=>B(R),title:`Click to cycle: ${q.map(W=>W.label).join(" → ")}`,children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),N||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:U?`${p}44`:"transparent",background:U?`${p}14`:"var(--surface-tertiary)",color:U?p:"var(--text-muted)"},onClick:()=>H(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:()=>C(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.resultDisplay==="inline"&&U?`${R.label}: ${U}`: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:U?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),U?`${R.label}: ${U}`:R.label]},R.id);default:return null}})]})}function dm({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:p}=nc(),m=Fa(l,{hostIdeType:a,providerType:i});return!e||s||m.length===0||!p?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(lm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:m,controlValues:u})})}function mc({hasDraft:e,isBusy:s=!1}){return!e||s}const um=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1}){const p=o.useRef(null),[m,f]=o.useState(""),{isVisible:g,toggleVisibility:w}=nc();o.useEffect(()=>{f("")},[s]),o.useEffect(()=>{var d;l&&((d=p.current)==null||d.focus())},[s,l]);const A=async()=>{const d=m.trim();if(!d||a)return;await c(d)!==!1&&f("")};return t.jsxs("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[t.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&t.jsx("button",{type:"button",onClick:w,"aria-label":g?"Hide controls":"Show controls","aria-pressed":g,title:g?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:t.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[t.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:p,type:"text",placeholder:i||`Send message to ${r}...`,value:m,onChange:d=>f(d.target.value),onPaste:d=>{const b=d.clipboardData.getData("text");b&&f(y=>y+b),d.preventDefault()},onKeyDown:d=>{if(d.key==="Enter"){if(d.nativeEvent.isComposing){d.preventDefault();return}d.preventDefault(),A()}},onBlur:d=>{if(window.innerWidth<768){const b=d.relatedTarget;if((b==null?void 0:b.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{A()},disabled:mc({hasDraft:!!m.trim(),isBusy:a}),className:`w-10 h-10 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:"18",height:"18",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"})})})]}),i&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),tt=e=>e.transport==="pty",Hs=(e,s)=>tt(e)?e.mode||"terminal":"chat",pc=(e,s)=>tt(e)&&Hs(e)==="terminal",Ze=e=>e.transport==="acp";function ns(e){return e.streamSource!=="agent-stream"}function is(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function fc(e){return e.machineName||""}function kr(e){return is(e)}function Bt(e){return e.agentType||""}function dn(e){return e.hostIdeType||""}function Ua(e){return e.displayPrimary||e.agentName||"Agent"}function hc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function mm(e){return e.lastMessagePreview||e.displaySecondary||""}function xc(e){return[e.displaySecondary,fc(e)].filter(Boolean)}function Fs(e){return e.agentName||ot(Bt(e))}function pm(e){var s,r;if(!ns(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return ot(dn(e)||Bt(e))}function bc(e){return ns(e)?e.sessionId:e.nativeSessionId}function Uo(e){return ns(e)?"native":e.tabKey}function fm(e){return e.sessionId}function hm(e,s){if(s)return ns(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function xm(e,s){const r=Bt(e),n=ns(e),a=tt(e)||Ze(e),i=n?a?Fs(e)||(s==null?void 0:s.cliName)||ot(dn(e)||r):s!=null&&s.type?ot(s.type):ot(dn(e)||r):Fs(e);return{isNativeConversation:n,isCli:tt(e),isAcp:Ze(e),isCliTerminal:pc(e),providerType:r,displayLabel:i,targetEntry:hm(e,s)}}function bm(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function ps(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||bm(s==null?void 0:s.receivedAt)||0}function ba(e,s=0){return ps(e)||e.lastUpdated||s||0}function gc(e){return ps(e)||e.lastUpdated||0}function yc(e,s,r=gc){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 ga(e){var r;const s=Ct(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function gm(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!ga(e)&&!e.title.trim()}function ym(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(ga(r))-Number(ga(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:yc(s,r)})[0]||null}function Wt(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=ym(a);return n?i&&gm(n)?i:n:i||r[0]||null}function as(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function za(e){return jr(e)||e.tabKey||e.routeId||null}function vc(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=Wt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?za(a):null}function wc({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Vs(),c=is(e),l=fc(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=Fs(e),g=pm(e),w=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),A=o.useCallback(()=>{if(r){r();return}const d=za(e);d&&i(as(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:A,title:g,children:[t.jsx(Rt,{size:12}),t.jsx("span",{children:g})]}):t.jsxs("span",{className:"conversation-meta-chip",title:g,children:[t.jsx(Rt,{size:12}),t.jsx("span",{children:g})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(fr,{size:12}),t.jsx("span",{children:f})]}),m&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(fr,{size:12}),t.jsx("span",{children:f})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:l,children:[t.jsx(Qt,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(Qt,{size:12}),t.jsx("span",{children:l})]}))]})}function On(e,s){return`${e}:${s}`}function vm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function $r(e,s){vm()&&console.debug(`[subscription-manager] ${e}`,s)}class wm{constructor(){Ye(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=On(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),$r("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((p=s.sendData)==null?void 0:p.call(s,r,n))??!1}const u=()=>{var g;const 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};$r("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(g=s.sendData)==null||g.call(s,r,f)};return u.initialSendAccepted=l,u}publish(s){const r=On(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Ks.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),Ks.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=On(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;$r("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);$r("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}}const os=new wm;function jm(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function km(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 un(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}=km(u),f=jm(i,n),g=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=p.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),A=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},...g&&{machine:g,platform:g.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},cdpConnected:w.some(b=>!!b.cdpConnected)});for(const b of w){const y=f.get(b.id),h=ar(b,y),S=(m.get(b.id)||[]).map(_=>ar(_,f.get(_.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.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:S,agents:S.map(_=>({id:_.id,name:_.providerName||_.providerType,type:_.providerType,status:_.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l})}for(const b of A){const y=f.get(b.id),h=ar(b,y);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.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||(y==null?void 0:y.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isCli:!0})}for(const b of d){const y=f.get(b.id),h=ar(b,y);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.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,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const Wn=new Map,Hn=new Map,Fn=new Set,cr=new Map,Sm=1200;function Nm(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 zo(e,s){const r=cr.get(e);!r||r.size===0||(cr.delete(e),r.forEach(n=>n(s)))}function Cm(e,s){return new Promise(r=>{const n=cr.get(e)||new Set;cr.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&cr.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function Sr(){const{sendCommand:e,sendData:s}=Pt(),{injectEntries:r,getIdes:n}=cn();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=Hn.get(a)||0;if(!(i!=null&&i.force)&&Fn.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=Wn.get(a);if(u)return u;const p=(async()=>{if(s&&!Fn.has(a)&&(Fn.add(a),os.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},d=>{const b=n(),y=b.find(S=>S.id===a),h=un(d.status,{daemonId:a,existingDaemon:y,existingEntries:b,timestamp:d.timestamp});h.length>0&&r(h),Hn.set(a,Date.now()),zo(a,!0)}),!(i!=null&&i.force)&&await Cm(a,Sm)))return;const m=await e(a,"get_status_metadata"),f=Nm(m);if(!f)return;const g=n(),w=g.find(d=>d.id===a),A=un(f,{daemonId:a,existingDaemon:w,existingEntries:g,timestamp:f.timestamp||Date.now()});A.length>0&&r(A,{authoritativeDaemonIds:[a]}),Hn.set(a,Date.now()),zo(a,!0)})().finally(()=>{Wn.delete(a)});return Wn.set(a,p),p},[n,r,e,s])}function Gt(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function Va(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=Os(e.content),i=Os(s.content);if(!a||!i||!(a===i||br(a,i)||br(i,a)))return!1;const l=Gt(e),u=Gt(s);return l&&u?Math.abs(l-u)<=15e3:!!e._localId!=!!s._localId}function Vo(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),Gt(e)&&(s+=1),s}function Ns(e){return Os(e==null?void 0:e.content)}function br(e,s){if(!e||!s||e.length<=s.length)return!1;const r=Math.max(12,Math.min(80,Math.floor(e.length*.4)));return s.length<r?!1:e.startsWith(s)||e.includes(s)}function Im(e,s){const r=Ns(e),n=Ns(s);return!r||!n||r===n?null:br(r,n)?e:br(n,r)?s:null}function Am(e,s){const r=Im(e,s);if(r)return r;const n=Vo(e),a=Vo(s);return a!==n?a>n?s:e:Ns(s).length>=Ns(e).length?s:e}function Mm(e){return!!e&&!!(e.id||e._localId||e._turnKey)}function lr(e){if(!e)return[];const s=[],r=l=>{l&&s.push(l)};e.id&&r(`id:${String(e.id)}`),e._localId&&r(`local:${String(e._localId)}`),e._turnKey&&r(`turn:${String(e._turnKey)}`);const n=String(e.role||"").toLowerCase(),a=Ns(e),i=Gt(e),c=i?Math.round(i/15e3):0;return n&&a&&(r(`content:${n}:${a}`),r(`preview:${n}:${a.slice(0,120)}:${c}`)),s}function fs(e,s=Va){const r=[],n=new Map,a=(c,l)=>{for(const u of lr(c)){const p=n.get(u);p?p.push(l):n.set(u,[l])}},i=(c,l)=>{for(const u of lr(c)){const p=n.get(u);if(!p)continue;const m=p.filter(f=>f!==l);m.length>0?n.set(u,m):n.delete(u)}};for(const c of e){const l=new Set;for(const m of lr(c)){const f=n.get(m);f&&f.forEach(g=>l.add(g))}const u=l.size>0?Array.from(l).sort((m,f)=>m-f).find(m=>s(r[m],c)):Mm(c)?-1:r.findIndex(m=>s(m,c));if(u!==void 0&&u>=0){const m=Am(r[u],c);m!==r[u]&&(i(r[u],u),r.splice(u,1,m),a(m,u));continue}const p=r.length;r.push(c),a(c,p)}return r}function Tm(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:fs([...r,...n])}function Go(e){return[...e].sort((s,r)=>{const n=Gt(s),a=Gt(r);return n&&a&&n!==a?n-a:0})}function qo(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=>Va(i,n));return a>=0?(r.splice(a,1),!1):!0})}function Lm(e,s,r=Va){const n=new Map,a=i=>{for(const c of lr(i)){const l=n.get(c);l?l.push(i):n.set(c,[i])}};return s.forEach(a),e.filter(i=>{const c=Ns(i),l=String((i==null?void 0:i.role)||"").toLowerCase(),u=Gt(i),p=new Set;for(const f of lr(i)){const g=n.get(f);g&&g.forEach(w=>p.add(w))}return!(p.size>0?Array.from(p):s).some(f=>{if(r(i,f))return!0;const g=String((f==null?void 0:f.role)||"").toLowerCase();if(!c||!l||l!==g)return!1;const w=Ns(f);if(!br(w,c)&&w!==c)return!1;const A=Gt(f);return u&&A?Math.abs(u-A)<=15e3:!0})})}function Es(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:tt(e)||Ze(e)?{agentType:Bt(e)}:e.streamSource==="agent-stream"?{agentType:Bt(e)}:s}function gr(e){return e?kr(e):""}function Zs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Ga(e){if(!e)return null;if(Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return"Resolve the pending approval prompt before sending another message.";switch(e.status){case"waiting_approval":case"waiting_for_user_input":return"Resolve the pending approval prompt before sending another message.";default:return null}}function _m(e){const s=e instanceof Error?e.message:String(e||""),r=s.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":s||"Unable to send message right now."}const Rm=60,Pm=1e3;function jc(e={}){return e.isCliLike?Pm:Rm}function Dm(e={}){return jc(e)}const Nr=60,qa=12e4,Em=new Set(["generating","waiting_approval","starting","streaming","working"]),Yo=new Map;function kc(e,s){return`${e}::${s}`}function ya(e=Nr){return{liveMessages:[],cursor:Nc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Sc(e){return Fi(e)}function Nc(e,s=Nr){return{knownMessageCount:e.length,lastMessageSignature:Sc(e[e.length-1]),tailLimit:s}}function Kr(e,s){const r=e[e.length-1];if(!r)return"empty:";let n="";try{n=JSON.stringify(r.content??"")}catch{n=String(r.content??"")}return["",e.length,String(r.id||""),String(r.index??""),String(r.receivedAt??r.timestamp??""),n].join("|")}function $m(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return fs([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return fs([...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 fs([...e.slice(0,a),...r])}return r}default:return r}}class Km{constructor(s){Ye(this,"manager");Ye(this,"sendData");Ye(this,"daemonId");Ye(this,"sessionId");Ye(this,"historySessionId");Ye(this,"subscriptionKey");Ye(this,"snapshot");Ye(this,"transportSubscription",null);Ye(this,"listeners",new Set);Ye(this,"retainCount",0);Ye(this,"loadHistoryPromise",null);Ye(this,"pendingDisconnectTimer",null);this.manager=s.manager||os,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=ya(Math.max(0,s.tailLimit??Nr))}updateOptions(s){if(s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId),s.tailLimit!==void 0){const r=Math.max(0,s.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length);this.snapshot={...this.snapshot,cursor:{...this.snapshot.cursor,knownMessageCount:n,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=fs([...r,...this.snapshot.liveMessages]);if(n.length<r.length)return;const a=Nc(n,this.snapshot.cursor.tailLimit);Kr(this.snapshot.liveMessages)===Kr(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.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await s(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}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.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){const r=$m(this.snapshot.liveMessages,s),n={knownMessageCount:r.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:Sc(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};Kr(this.snapshot.liveMessages)===Kr(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 Cc(e){const s=kc(e.daemonId,e.sessionId),r=Yo.get(s);if(r)return r.updateOptions(e),r;const n=new Km(e);return Yo.set(s,n),n}function Bm(e,s){return{...e,loadHistoryPage:s}}function Om(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Wm(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(Em.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=s.now??Date.now(),a=Math.max(0,Number(s.recentActivityMs??qa)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=a:Array.isArray(e.messages)&&e.messages.length>0}function Hm(e=qa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Fm(e,s={}){const r=new Set,n=[];for(const a of e){if(!Wm(a,s))continue;const i=kr(a),c=a.sessionId||"";if(!i||!c)continue;const l=kc(i,c);if(r.has(l))continue;r.add(l);const u=jr(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Om),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Um(e,s){const{sendData:r,sendCommand:n}=Pt(),a=(s==null?void 0:s.enabled)!==!1,i=kr(e),c=e.sessionId||"",l=jr(e)||c,u=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??Nr),m=o.useMemo(()=>!a||!i||!c?null:Cc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:p}),[i,a,l,r,c,u,p]),[f,g]=o.useState(()=>(m==null?void 0:m.getSnapshot())||ya(p));o.useEffect(()=>{if(!m){g(ya(p));return}m.retain(),g(m.getSnapshot());const A=m.subscribe(d=>{g(d)});return()=>{A(),m.release()}},[m,p]),o.useEffect(()=>{m&&(m.hydrateLiveMessages(e.messages),g(m.getSnapshot()))},[e.messages,m]);const w=o.useCallback(async()=>{!m||!i||!c||await m.loadHistoryPage(async()=>{const A=e.agentType,d=await n(i,"chat_history",{agentType:A,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(()=>Bm(f,w),[w,f])}function zm(e,s){const{sendData:r}=Pt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??Nr),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??qa)),c=Hm(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const m=setInterval(()=>{u(f=>f+1)},c);return()=>{clearInterval(m)}},[e.length,n,c]);const p=o.useMemo(()=>Fm(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||p.descriptors.length===0)return;const m=p.descriptors.map(f=>Cc({...f,sendData:r,tailLimit:a}));return m.forEach(f=>f.retain()),()=>{m.forEach(f=>f.release())}},[p.signature,n,r,a])}function Vm(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Gm(e){return Vm(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const qm=60;function va({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:p=!1,scrollToBottomRequestNonce:m,isInputActive:f=!0}){var ce,Se,X,he,J;const g=o.useRef(new Map),w=Sr();wr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const A=at.useMemo(()=>qs(e),[e.status,e.connectionState]),d=o.useMemo(()=>xm(e,s),[e,s]),b=o.useMemo(()=>{var Z;return Fa((Z=d.targetEntry)==null?void 0:Z.providerControls,{hostIdeType:e.hostIdeType,providerType:d.providerType})},[e.hostIdeType,d.providerType,(ce=d.targetEntry)==null?void 0:ce.providerControls]),y=jc({isCliLike:d.isCli||d.isAcp}),h=Dm({isCliLike:d.isCli||d.isAcp}),S=Um(e,{enabled:!!e.sessionId,tailLimit:h}),[_,k]=o.useState(y),I=e.tabKey,j=S.historyMessages,v=S.hasMoreHistory,x=S.historyError,E=Tm(S.liveMessages,e.messages);o.useEffect(()=>{k(y)},[y,I]);const L=Math.max(0,E.length-_),M=Ua(e),T=kr(e),B=Gm(e),H=Ga(e),C=a||H,R=!!H,[U,N]=o.useState(!1);o.useEffect(()=>{const Z=d.targetEntry;T&&(!Z||Z.providerControls===void 0||Z.controlValues===void 0)&&w(T,{minFreshMs:3e4}).catch(()=>{})},[T,d.isAcp,(Se=d.targetEntry)==null?void 0:Se.providerControls,(X=d.targetEntry)==null?void 0:X.controlValues,w]);const D=o.useCallback(async()=>{if(!U){if(E.length>_){k(Z=>Math.min(E.length,Z+qm));return}N(!0);try{await S.loadHistoryPage()}finally{N(!1)}}},[S,U,E.length,_]),{allMessages:Y,receivedAtMap:q}=o.useMemo(()=>{const Z=L>0?E.slice(-_):E;if(j.length===0){const ye=Go(fs(Z)),ie={};return ye.forEach((le,se)=>{const pe=`${e.tabKey}:${_s(le,se)}`;let ne=Gt(le)||g.current.get(pe)||0;ne||(ne=Date.now(),g.current.set(pe,ne)),ie[_s(le,se)]=ne}),{allMessages:ye,receivedAtMap:ie}}const ue=Lm(j,Z),de=Go(fs([...ue,...Z])),z={};return de.forEach((ye,ie)=>{const le=`${e.tabKey}:${_s(ye,ie)}`;let se=Gt(ye)||g.current.get(le)||0;se||(se=Date.now(),g.current.set(le,se)),z[_s(ye,ie)]=se}),{allMessages:de,receivedAtMap:z}},[e.tabKey,L,j,E,_]),W=o.useMemo(()=>l.filter(Z=>Z.routeId===e.tabKey).sort((Z,ue)=>Z.timestamp-ue.timestamp),[l,e.tabKey]),ae=o.useMemo(()=>{if(E.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((A.isGenerating||e.status==="streaming")&&N(!1),e.status==="not_monitored"&&B)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(fr,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bs,{size:14})," Open ",M," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&B)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(Gi,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bs,{size:14})," Open ",M," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!U)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,B,i,c,U,E.length,M,A.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[p&&t.jsx(wc,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(lu,{messages:Y,actionLogs:W,agentName:Fs(e)||M||"Agent",userName:u,isCliMode:d.isCli||d.isAcp,isWorking:A.isGenerating,contextKey:e.tabKey,receivedAtMap:q,onLoadMore:D,isLoadingMore:U,hasMoreHistory:v,hiddenLiveCount:L,loadError:x??void 0,emptyState:ae,scrollToBottomRequestNonce:m}),t.jsx(dm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:d.providerType,displayLabel:d.displayLabel,controls:(he=d.targetEntry)==null?void 0:he.providerControls,controlValues:(J=d.targetEntry)==null?void 0:J.controlValues,isActive:f,isCliTerminal:d.isCliTerminal}),!d.isCliTerminal&&t.jsx(um,{contextKey:e.tabKey,panelLabel:M,isSending:n,isBusy:R,statusMessage:C,onSend:r,isActive:f,showControlsToggle:b.length>0})]})}let Ic=js;function Ac(){return Ic()}class Ym{constructor(){Ye(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(a=>a(...r))}}let Mc=new Ym;class Xm{sendPtyInput(s,r,n){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let ft=new Xm;function Jm(e){e.dashboardWS&&(Mc=e.dashboardWS),e.connectionManager&&(ft=e.connectionManager),e.useDaemonsHook&&(Ic=e.useDaemonsHook)}const Tc=.6,Qm=1.15;function Zm(e,s={}){const r=typeof s.minScale=="number"?s.minScale:Tc;return!Number.isFinite(e)||e<=0?1:e<=480?r:1}function lt(e){return Ua(e)}function Cs(e){return xc(e).join(" · ")}function Lc(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=Os(s==null?void 0:s.content);return r||(e.title?e.title:Cs(e)||"No messages yet")}function _c(e,s){const{isReconnecting:r,isConnecting:n}=qs(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function ep(e,s){const r=["Chat",...xc(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function hs(e){return _c(e)||Cs(e)}function tp(e){return`${lt(e)} · ${Lc(e)}`}function sp(e){const s=dn(e),r=s?ot(s):Fs(e);return`${lt(e)} — ${r||"Agent"}`}function rp(e){return Fs(e)||"CLI"}function Rc(e){return hc(e)}function Pc(e){return e?`Remote · ${lt(e)||e.workspaceName||"Session"}`:"Remote"}function np({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0}){var q;const{ides:l}=js(),u=o.useRef(null),{sendData:p}=Pt(),[m,f]=o.useState(""),[g,w]=o.useState(!1),[A,d]=o.useState(1),b=o.useRef(!1),y=o.useRef(0),h=o.useRef(!1),S=o.useRef(""),_=o.useRef(null),k=o.useRef(!1),I=o.useRef(null),j=e.tabKey,v=e.sessionId||"",x=e.daemonId||((q=e.routeId)==null?void 0:q.split(":")[0])||e.routeId||"",E=l.find(W=>W.id===x&&W.type==="adhdev-daemon"),L=(E==null?void 0:E.terminalSizingMode)==="fit"?"fit":"measured",M=Ga(e),T=i||M,B=Tc,H=Qm,C=()=>typeof window>"u"?1:Zm(window.innerWidth||0,{minScale:B}),R=()=>{var W,ae;y.current=0,h.current=!1,S.current="",_.current=null,k.current=!1,I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),w(!1),(ae=(W=r.current)==null?void 0:W.reset)==null||ae.call(W)},U=()=>{var W,ae;y.current=0,h.current=!1,S.current="",_.current=null,k.current=!1,I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),w(!0),(ae=(W=r.current)==null?void 0:W.reset)==null||ae.call(W)},N=()=>{var ae;if(I.current=null,!c)return;const W=S.current;W&&(S.current="",(ae=r.current)==null||ae.write(W))},D=W=>{W&&(S.current+=W,c&&I.current===null&&(I.current=requestAnimationFrame(N)))},Y=(W,ae=0,ce,Se)=>{var X,he,J,Z,ue;ae>0&&y.current>=ae||ae===0&&h.current||(y.current=ae,w(!0),typeof ce=="number"&&typeof Se=="number"&&ce>0&&Se>0&&((he=(X=r.current)==null?void 0:X.resize)==null||he.call(X,ce,Se)),(Z=(J=r.current)==null?void 0:J.reset)==null||Z.call(J),W&&((ue=r.current)==null||ue.write(W)))};return o.useEffect(()=>{R()},[v]),o.useEffect(()=>{var ae;if(!v)return;const W=((ae=ft.onRuntimeEvent)==null?void 0:ae.call(ft,v,ce=>{if(!(!ce||ce.sessionId!==v)){if(ce.type==="runtime_snapshot"){if(!c){_.current={text:ce.text||"",seq:ce.seq||0,cols:ce.cols,rows:ce.rows};return}Y(ce.text||"",ce.seq||0,ce.cols,ce.rows);return}if(ce.type==="session_output"){h.current=!0,typeof ce.seq=="number"&&(y.current=Math.max(y.current,ce.seq)),g||w(!0),typeof ce.data=="string"&&D(ce.data);return}if(ce.type==="session_cleared"){if(!c){k.current=!0,S.current="",_.current=null;return}U()}}}))||(()=>{});return()=>{W()}},[x,v,r,c,g]),o.useEffect(()=>{var ae,ce,Se;if(!v)return;x&&((ae=ft.getState)==null?void 0:ae.call(ft,x))==="connected"&&(w(!0),(ce=ft.requestRuntimeSnapshot)==null||ce.call(ft,x,v).catch(()=>{}));const W=(Se=ft.onStateChange)==null?void 0:Se.call(ft,(X,he)=>{var J;X!==x||he!=="connected"||(w(!0),(J=ft.requestRuntimeSnapshot)==null||J.call(ft,x,v).catch(()=>{}))});return()=>{W==null||W()}},[x,v,r]),o.useEffect(()=>{s&&R()},[s,j,r]),o.useEffect(()=>{f("")},[e.tabKey]),o.useEffect(()=>{const W=()=>{b.current||d(C())};return W(),window.addEventListener("resize",W),()=>window.removeEventListener("resize",W)},[]),o.useEffect(()=>{var ae;if(!c){(ae=u.current)==null||ae.blur();return}k.current&&(k.current=!1,U());const W=_.current;W&&(_.current=null,Y(W.text,W.seq,W.cols,W.rows)),S.current&&I.current===null&&(I.current=requestAnimationFrame(N)),requestAnimationFrame(()=>{var ce;(ce=r.current)==null||ce.bumpResize()})},[c]),o.useEffect(()=>()=>{I.current!==null&&(cancelAnimationFrame(I.current),I.current=null)},[]),o.useEffect(()=>{const W=ae=>{var Se;const ce=ae.detail;ce!=null&&ce.sessionId&&ce.sessionId!==v||g&&((Se=r.current)==null||Se.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",W),()=>{window.removeEventListener("adhdev:fit-cli-terminal",W)}},[g,v,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(W=>Math.max(B,Number((W-.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(W=>Math.min(H,Number((W+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-x-auto overflow-y-hidden rounded-lg overscroll-contain",children:t.jsx("div",{style:{width:`${100/A}%`,height:`${100/A}%`,transform:`scale(${A})`,transformOrigin:"top left"},children:t.jsx(Qi,{ref:r,readOnly:!g||!c,sizingMode:L,onInput:W=>{g&&(p==null||p(x,{type:"pty_input",sessionId:v,targetSessionId:v,data:W}))}})})}),!g&&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.jsxs("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:u,type:"text",placeholder:T||`Send message to ${lt(e)}...`,value:m,disabled:!g||!c,onChange:W=>f(W.target.value),onPaste:W=>{const ae=W.clipboardData.getData("text");ae&&f(ce=>ce+ae),W.preventDefault()},onKeyDown:W=>{if(W.key!=="Enter")return;if(W.nativeEvent.isComposing){W.preventDefault();return}W.preventDefault();const ae=m.trim();!g||!ae||M||n(ae).then(ce=>{ce!==!1&&f("")})},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 W=m.trim();!g||!W||M||n(W).then(ae=>{ae!==!1&&f("")})},disabled:!g||!c||mc({hasDraft:!!m.trim(),isBusy:!!M}),className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!M?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!M?{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"})})})]}),T&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:T})]})]})}function ap({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 op({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 Ya({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(gn,{size:n}):t.jsx(Zt,{size:n})})}function Xo({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Jo({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=vn(e.updatedAt),l=!e.readAt;return t.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[s?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",s]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?t.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),t.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function ip({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetCliViewMode:p,onHideConversation:m,hiddenConversations:f=[],onShowConversation:g,onShowAllHidden:w,onResetPanelsToMain:A,inboxOpen:d,onInboxOpenChange:b,hiddenOpen:y,onHiddenOpenChange:h,onOpenNewSession:S,actionShortcuts:_,notifications:k,notificationUnreadCount:I,onOpenNotification:j,onMarkNotificationRead:v,onMarkNotificationUnread:x,onDeleteNotification:E}){const{ides:L,p2pStates:M={}}=js(),T=!!e&&tt(e)&&!Ze(e),B=!!e&&Ze(e),H=u||(e?pc(e)?"terminal":"chat":null),[C,R]=o.useState(!1),U=o.useRef(null),N=o.useRef(null),D=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",Y=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",q=L.filter(z=>z.type==="adhdev-daemon"),W=Object.values(M),ae=W.filter(z=>z==="connected").length,ce=W.filter(z=>z==="connecting"||z==="new"||z==="checking").length,X=r!=="connected"||q.length===0?null:ce>0&&ae===0?"P2P connecting...":ae>0&&s===0?"Waiting for IDE...":null,he=o.useMemo(()=>k.filter(z=>!z.readAt),[k]),J=o.useMemo(()=>k.filter(z=>!!z.readAt),[k]),Z=o.useMemo(()=>he.slice(0,9),[he]),ue=I;o.useEffect(()=>{if(!d)return;const z=ye=>{var ie;(ie=U.current)!=null&&ie.contains(ye.target)||b(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[d,b]),o.useEffect(()=>{if(!y)return;const z=ye=>{var ie;(ie=N.current)!=null&&ie.contains(ye.target)||h(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[y,h]),o.useEffect(()=>{if(!y&&!d)return;const z=ye=>{if(!ye.altKey)return;const ie=ye.code.match(/^Digit([1-9])$/);if(!ie)return;const le=Number(ie[1])-1,se=y?f[le]:void 0,pe=d?Z[le]:void 0;if(!(!se&&!pe)){if(ye.preventDefault(),ye.stopPropagation(),se){g==null||g(se),h(!1);return}pe&&(j(pe),b(!1))}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[f,y,d,Z,h,b,j,g]);const de=z=>{if(!z)return;const ye=a.find(ie=>ie.tabKey===z);ye&&(m==null||m(ye))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(Zt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?lt(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:Y}})})]}),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:Y}}),X&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",X]}),S&&t.jsx("button",{type:"button",onClick:S,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(Od,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(T||B||!Ze(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:Cs(e)||lt(e),children:lt(e)}),(T||B)&&l&&t.jsxs(t.Fragment,{children:[T&&p&&H&&t.jsx(Ya,{mode:H,onChange:p,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:B?"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(At,{size:14})})]}),!Ze(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Da,{size:14})}),!T&&!Ze(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Rt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:U,children:[t.jsxs("div",{className:`dashboard-header-hidden${C?" is-drop-target":""}`,ref:N,onDragEnter:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),R(!0))},onDragOver:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),z.dataTransfer.dropEffect="move",R(!0))},onDragLeave:z=>{z.currentTarget.contains(z.relatedTarget)||R(!1)},onDrop:z=>{const ye=z.dataTransfer.getData("text/tab-key");z.preventDefault(),R(!1),de(ye)},children:[t.jsxs("button",{type:"button",onClick:()=>h(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${_!=null&&_.toggleHiddenTabs?` (${_.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(qi,{size:16}),f.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:f.length})]}),y&&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(Xo,{value:_==null?void 0:_.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[A&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:A,children:"Reset panels"}),f.length>0&&w&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{w(),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(Xo,{value:_==null?void 0:_.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:lt(e)})]}),f.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:f.map(z=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{g==null||g(z),h(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:lt(z)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[f.indexOf(z)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",f.indexOf(z)+1]}):null,Cs(z)]})]},z.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(yn,{size:16}),ue>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:ue})]}),d&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[he.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),he.map(z=>t.jsx(Jo,{notification:z,shortcutIndex:Z.indexOf(z)>=0?Z.indexOf(z)+1:void 0,onOpen:()=>j(z),onMarkRead:()=>v(z.id),onMarkUnread:()=>x(z.id),onDelete:()=>E(z.id)},z.id))]}),J.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),J.map(z=>t.jsx(Jo,{notification:z,onOpen:()=>j(z),onMarkRead:()=>v(z.id),onMarkUnread:()=>x(z.id),onDelete:()=>E(z.id)},z.id))]}),k.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function jt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function cp(e,s){return String(e||"")!==String(s||"")}function lp(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
|
|
31
|
-
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!
|
|
32
|
-
`).includes(a)))}function dp(e,s="recent"){const r=e.slice();return r.sort((n,a)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(s==="messages"){const i=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(i!==0)return i}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function Dc(e,s={}){return dp(lp(e,s),s.sortMode||"recent")}function mn(e){return e?"Resume saved history":"Start fresh"}function Xa(e){return e?"Resuming saved history…":"Starting fresh…"}function up(){return"Start fresh"}function Ec(e,s=!1){return e==="cli"?mn(s):e==="ide"?"Start IDE":"Start ACP session"}function $c(e,s=!1){return e==="cli"?Xa(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function mp(){return"Recover hosted runtime"}function pp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function fp(){return"Open saved history"}function hp(){return"Saved History"}function Ja(){return"Use saved history when you want continuity in the same provider conversation."}function xp(){return"No saved history found yet."}function bp(){return"Refresh saved history"}function gp(){return"Refreshing saved history…"}function xs(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function bs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Us(e){return e==="start-fresh"?"Start fresh":"Restart"}function zs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Qa(e){return`Resume saved history with ${e}?`}function Za(){return"Review or change the target workspace before resuming saved history."}function yp(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function eo({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:g,onResumeSavedSession:w}){var v;const A=s.find(x=>x.id===e.routeId),d=(A==null?void 0:A.chats)||[],b=(v=A==null?void 0:A.activeChat)==null?void 0:v.id,y=tt(e)&&!Ze(e),[h,S]=o.useState(()=>jt()),_=l||h,k=x=>{if(u){u(x);return}S(x)},I=o.useMemo(()=>Dc(a,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.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:y?hp():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:sp(e)}),y&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ja()})]}),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(At,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&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"}),y?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:_.textQuery,onChange:x=>k({..._,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:_.workspaceQuery,onChange:x=>k({..._,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:_.modelQuery,onChange:x=>k({..._,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:_.sortMode,onChange:x=>k({..._,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:_.resumableOnly,onChange:x=>k({..._,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),I.map(x=>{const E=e.providerSessionId===x.providerSessionId,L=E||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{L||!w||w(x)},disabled:L,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${L?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${E?"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:yp(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",Ss(x.summaryMetadata)?` · ${Ss(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:E?"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)),(y&&!i&&I.length===0||!y&&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(Ud,{size:32})}),t.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":xp():"No recent chat sessions found."})]}),y&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:gp()})})]}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:t.jsx("button",{onClick:g,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Gs,{size:13})," ",y?bp():"Refresh History"]})})})]})]});return typeof document>"u"?j:pr.createPortal(j,document.body)}const Qo={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function Kc({toasts:e,onDismiss:s,onClickToast:r}){return t.jsx("div",{className:"fixed right-4 z-[9999] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(n=>{const a=Qo[n.type]||Qo.info;return t.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[t.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),t.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(At,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>t.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:l=>{l.stopPropagation(),i.onClick(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const vp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function wp(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function jp(e){return e.sessionId||e.instanceId||e.agentType}function Un(e,s){return e||s}function Zo(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 Bc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=_t(r,{fallbackId:r.id}));return s}function Oc(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 to(e,s,r={}){return kp(e,s,Oc(e,r))}function kp(e,s,r={}){var f,g,w,A,d,b;const n=[],a=r.machineName,i=r.connectionState,c=wp(e),l=Mu(e.type,{agentName:e.cliName}),u=tt(e)||Ze(e)?l:ot(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var h,S;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||ot(y.providerType),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((h=y.activeChat)==null?void 0:h.messages)||[],activeModal:((S=y.activeChat)==null?void 0:S.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,surfaceHidden:y.surfaceHidden}}):[],m=vp(e);if(m){const y=e.sessionId||e.instanceId,h=l,S=(f=e.activeChat)==null?void 0:f.activeModal,_=S&&Array.isArray(S.buttons)&&S.buttons.length>0,k=Ct((g=e.activeChat)==null?void 0:g.status,{activeModal:(w=e.activeChat)==null?void 0:w.activeModal})||Ct((d=(A=e.agents)==null?void 0:A[0])==null?void 0:d.status)||"idle",I=e.activeChat||{title:"",messages:[]};let j=I.title&&String(I.title).trim()?String(I.title).trim():"";const v=(b=e.activeChat)==null?void 0:b.id,x=e.chats;if(v&&Array.isArray(x)&&x.length>0){const H=x.find(C=>C.id===v||C.id&&String(C.id)===String(v));H!=null&&H.title&&String(H.title).trim()&&(j=String(H.title).trim())}const E=(tt(e)||Ze(e),e.type),L=(tt(e)||Ze(e))&&Wo(j,h,E)?"":j,M=I.messages||[],T=Zo(s,[e.id,y]),B=qo(M,T);n.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:tt(e)?e.mode||"terminal":"chat",agentName:h,agentType:E,status:k,title:L,messages:[...M,...B],resume:e.resume,hostIdeType:!tt(e)&&!Ze(e)?e.type:void 0,workspaceName:c,displayPrimary:L||c||(tt(e)?e.mode==="chat"?h:"Terminal":h),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:_?S.buttons:void 0,modalMessage:_?S.message:void 0,streamSource:"native",tabKey:Un(y,e.id),machineName:a,connectionState:i})}if(m&&(tt(e)||Ze(e)))return n;for(const y of p){const h=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,S=Tu(y),_=jp(y),k=`${e.id}:${_}`,I=y.title&&String(y.title).trim()||"",j=Wo(I,y.agentName,y.agentType)?"":I,v=y.messages||[],x=Zo(s,[k,y.sessionId,y.instanceId]),E=qo(v,x);(y.transport==="cdp-webview"||y.sessionId||y.providerSessionId||v.length>0||E.length>0||h||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(S))&&n.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:S,title:j,messages:[...v,...E],hostIdeType:e.type,workspaceName:c,displayPrimary:j||c||y.agentName||u,displaySecondary:`${u} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,modalButtons:h?y.activeModal.buttons:void 0,modalMessage:h?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Un(y.sessionId||y.instanceId,k),machineName:a,connectionState:i})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Un(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function Sp(e){const s=e.split(":");return s.length>=3&&(s[1]==="ide"||s[1]==="cli"||s[1]==="acp")?{daemonId:s[0],targetSessionId:s.slice(2).join(":")||void 0}:{daemonId:e}}function Np(e,s){const r=Sp(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Wc=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],Hc=[{id:"aider-cli",name:"Aider",icon:"🛠️"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"gemini-cli",name:"Gemini CLI",icon:"✨"},{id:"github-copilot-cli",name:"GitHub Copilot CLI",icon:"🤖"},{id:"goose-cli",name:"Goose",icon:"🪿"},{id:"opencode-cli",name:"OpenCode CLI",icon:"🧩"}],Fc=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],Cp=Wc,Ip=Hc,Ap=Fc;function Is(...e){return ud(md(e))}function Mp({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:Is("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 Uc({icon:e,title:s,subtitle:r,badge:n,actions:a,widthClassName:i="max-w-6xl",contentClassName:c,children:l}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(Mp,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:Is("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Lt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:Is("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function zc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:Is("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Tp={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},Lp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Br({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:Is("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Tp[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:Lp[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const _p={online:"bg-green-500/10 text-green-400 border-green-500/30",idle:"bg-yellow-500/10 text-yellow-400 border-yellow-500/30",busy:"bg-orange-500/10 text-orange-400 border-orange-500/30",error:"bg-red-500/10 text-red-400 border-red-500/30",offline:"bg-gray-500/10 text-text-secondary border-gray-500/30"},Rp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Pp({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:Is("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",_p[e],r),children:[t.jsx("span",{className:Is("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Rp[e])}),n]})}const wa="adhdev:themechange";function Dp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ts(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ls(e){return e==="system"?Dp():e}function Vc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Zr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(wa,{detail:{preference:e,theme:s}}))}function Ep(){const e=Ts(),s=Ls(e);Vc(s),Zr(e,s)}function so(){const[e,s]=o.useState(Ts),[r,n]=o.useState(()=>Ls(Ts()));o.useEffect(()=>{Vc(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),Zr("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:Ts()),n(f==="dark"||f==="light"?f:Ls(Ts()))},l=u=>{if(u.key!=="theme")return;const p=Ts(),m=Ls(p);s(p),n(m)};return window.addEventListener(wa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(wa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=Ls(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Zr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=Ls(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Zr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const ei={dark:"Dark",light:"Light",system:"System"};function $p({collapsed:e}){const{preference:s,cycleTheme:r}=so(),n=s==="dark"?t.jsx(Vd,{size:16}):s==="light"?t.jsx(zd,{size:16}):t.jsx(Gd,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ei[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:ei[s]})]})}function us({label:e,description:s,checked:r,disabled:n,onChange:a,extra:i}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,t.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[t.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),t.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Kp({onPrefChange:e}){const[s,r]=Ou(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(yn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:c=>i("globalEnabled",c)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:c=>i("browserNotifications",c)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{dc().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(qd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Yd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(fr,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function pn(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Bp(e,s){const r=pn(e),n=pn(s);if(!r||!n)return e.localeCompare(s);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function Gc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function dr(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Bp(r,s)>=0)return!1;const n=pn(r),a=pn(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Op(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function zn(e,s){return e instanceof Error?e.message:s}function Wp({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?t.jsx(zc,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:s||"Install ADHDev on a machine and sign in to connect it here."}):t.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>t.jsx(Fp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function ti({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 pr.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),t.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function Hp(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Cp,...Ip,...Ap].find(a=>a.id===s||s.includes(a.id)||a.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Fp({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var B,H;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,m]=o.useState(null),[f,g]=o.useState("idle"),[w,A]=o.useState(""),d=e.version||null,b=((B=e.machine)==null?void 0:B.platform)||((H=e.system)==null?void 0:H.platform)||"",y=_t(e,{fallbackId:e.id}),h=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",S=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),_=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),k=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),I=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const C=Op(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),u(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),u(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(C.error||"Upgrade failed"))}catch(C){c("error"),u(zn(C,"Connection lost during upgrade"))}}},v=async()=>{if(m(null),!!n){g("loading");try{await n(e.id),g("done"),A("Machine disconnected.")}catch(C){g("error"),A(zn(C,"Failed to disconnect"))}}},x=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){g("error"),A(zn(C,"Failed to revoke token"))}}},E="0.8.86",L=Gc(e,E),M=dr(e,E),T=S.length+_.length+k.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:y}),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] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!L&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&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${E}`,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${E}`}`}`}),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(Pp,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[I&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&T>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),T>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[S.map(C=>{const R=Hp(C.type),U=C.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:R.icon}),t.jsx("span",{children:R.name}),U!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${U?"bg-green-400":"animate-pulse"}`,style:U?void 0:{background:"var(--status-warning)"},title:U?"CDP connected":"CDP connecting..."})]},C.id)}),_.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:C.cliName||"CLI"})]},C.id)),k.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&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:w||l})]}),p==="disconnect"&&t.jsx(ti,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
|
|
30
|
+
`)))return}const U=(c==null?void 0:c[R.id])??d[R.id];try{const N=await v(R.invokeScript),D=Dr(N);if(D&&!D.ok||Er(N))throw new Error((D==null?void 0:D.error)||Qs(N)||`Could not run ${R.label}`);D&&x(R,U??!0,D)}catch(N){E(R,U);const D=N instanceof Error?N.message:`Could not run ${R.label}`;st.showToast(D,"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:"│"}),L.map(R=>{const U=String(b[R.id]||""),N=cm(R,y,U),D=S===R.id,Y=k===R.id,q=Qr(R,y);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:D?`${p}55`:"transparent",border:"1px solid",color:U?"var(--text-primary)":"var(--text-muted)"},onClick:()=>M(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),Y?"...":N||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),D&&q.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>_(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] 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()}),q.map(W=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:W.value===U?`${p}18`:"transparent",color:W.value===U?p:"var(--text-secondary)",fontWeight:W.value===U?600:400,borderLeft:W.value===U?`2px solid ${p}`:"2px solid transparent"},title:W.description||W.label,onMouseEnter:ae=>{ae.currentTarget.style.background=`${p}12`},onMouseLeave:ae=>{ae.currentTarget.style.background=W.value===U?`${p}18`:"transparent"},onClick:()=>T(R,W.value),children:W.label},W.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:U?"var(--text-primary)":"var(--text-muted)"},onClick:()=>B(R),title:`Click to cycle: ${q.map(W=>W.label).join(" → ")}`,children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),N||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:U?`${p}44`:"transparent",background:U?`${p}14`:"var(--surface-tertiary)",color:U?p:"var(--text-muted)"},onClick:()=>H(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:()=>C(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.resultDisplay==="inline"&&U?`${R.label}: ${U}`: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:U?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),U?`${R.label}: ${U}`:R.label]},R.id);default:return null}})]})}function um({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:p}=ac(),m=Fa(l,{hostIdeType:a,providerType:i});return!e||s||m.length===0||!p?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(dm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:m,controlValues:u})})}function pc({hasDraft:e,isBusy:s=!1}){return!e||s}const mm=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1}){const p=o.useRef(null),[m,f]=o.useState(""),{isVisible:g,toggleVisibility:w}=ac();o.useEffect(()=>{f("")},[s]),o.useEffect(()=>{var d;l&&((d=p.current)==null||d.focus())},[s,l]);const A=async()=>{const d=m.trim();if(!d||a)return;await c(d)!==!1&&f("")};return t.jsxs("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[t.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&t.jsx("button",{type:"button",onClick:w,"aria-label":g?"Hide controls":"Show controls","aria-pressed":g,title:g?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:t.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[t.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:p,type:"text",placeholder:i||`Send message to ${r}...`,value:m,onChange:d=>f(d.target.value),onPaste:d=>{const b=d.clipboardData.getData("text");b&&f(y=>y+b),d.preventDefault()},onKeyDown:d=>{if(d.key==="Enter"){if(d.nativeEvent.isComposing){d.preventDefault();return}d.preventDefault(),A()}},onBlur:d=>{if(window.innerWidth<768){const b=d.relatedTarget;if((b==null?void 0:b.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{A()},disabled:pc({hasDraft:!!m.trim(),isBusy:a}),className:`w-10 h-10 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:"18",height:"18",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"})})})]}),i&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),tt=e=>e.transport==="pty",Hs=(e,s)=>tt(e)?e.mode||"terminal":"chat",fc=(e,s)=>tt(e)&&Hs(e)==="terminal",Ze=e=>e.transport==="acp";function ns(e){return e.streamSource!=="agent-stream"}function is(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function hc(e){return e.machineName||""}function kr(e){return is(e)}function Bt(e){return e.agentType||""}function dn(e){return e.hostIdeType||""}function Ua(e){return e.displayPrimary||e.agentName||"Agent"}function xc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function pm(e){return e.lastMessagePreview||e.displaySecondary||""}function bc(e){return[e.displaySecondary,hc(e)].filter(Boolean)}function Fs(e){return e.agentName||ot(Bt(e))}function fm(e){var s,r;if(!ns(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return ot(dn(e)||Bt(e))}function gc(e){return ns(e)?e.sessionId:e.nativeSessionId}function Uo(e){return ns(e)?"native":e.tabKey}function hm(e){return e.sessionId}function xm(e,s){if(s)return ns(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function bm(e,s){const r=Bt(e),n=ns(e),a=tt(e)||Ze(e),i=n?a?Fs(e)||(s==null?void 0:s.cliName)||ot(dn(e)||r):s!=null&&s.type?ot(s.type):ot(dn(e)||r):Fs(e);return{isNativeConversation:n,isCli:tt(e),isAcp:Ze(e),isCliTerminal:fc(e),providerType:r,displayLabel:i,targetEntry:xm(e,s)}}function gm(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function ps(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||gm(s==null?void 0:s.receivedAt)||0}function ba(e,s=0){return ps(e)||e.lastUpdated||s||0}function yc(e){return ps(e)||e.lastUpdated||0}function vc(e,s,r=yc){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 ga(e){var r;const s=Ct(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function ym(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!ga(e)&&!e.title.trim()}function vm(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(ga(r))-Number(ga(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:vc(s,r)})[0]||null}function Wt(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=vm(a);return n?i&&ym(n)?i:n:i||r[0]||null}function as(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function za(e){return jr(e)||e.tabKey||e.routeId||null}function wc(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=Wt(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?za(a):null}function jc({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Vs(),c=is(e),l=hc(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=Fs(e),g=fm(e),w=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),A=o.useCallback(()=>{if(r){r();return}const d=za(e);d&&i(as(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:A,title:g,children:[t.jsx(Rt,{size:12}),t.jsx("span",{children:g})]}):t.jsxs("span",{className:"conversation-meta-chip",title:g,children:[t.jsx(Rt,{size:12}),t.jsx("span",{children:g})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(fr,{size:12}),t.jsx("span",{children:f})]}),m&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(fr,{size:12}),t.jsx("span",{children:f})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:l,children:[t.jsx(Qt,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(Qt,{size:12}),t.jsx("span",{children:l})]}))]})}function On(e,s){return`${e}:${s}`}function wm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function $r(e,s){wm()&&console.debug(`[subscription-manager] ${e}`,s)}class jm{constructor(){Ye(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=On(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),$r("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((p=s.sendData)==null?void 0:p.call(s,r,n))??!1}const u=()=>{var g;const 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};$r("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(g=s.sendData)==null||g.call(s,r,f)};return u.initialSendAccepted=l,u}publish(s){const r=On(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Ks.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),Ks.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=On(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;$r("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);$r("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}}const os=new jm;function km(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function Sm(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 un(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}=Sm(u),f=km(i,n),g=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=p.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),A=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},...g&&{machine:g,platform:g.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},cdpConnected:w.some(b=>!!b.cdpConnected)});for(const b of w){const y=f.get(b.id),h=ar(b,y),S=(m.get(b.id)||[]).map(_=>ar(_,f.get(_.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.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:S,agents:S.map(_=>({id:_.id,name:_.providerName||_.providerType,type:_.providerType,status:_.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l})}for(const b of A){const y=f.get(b.id),h=ar(b,y);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.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||(y==null?void 0:y.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isCli:!0})}for(const b of d){const y=f.get(b.id),h=ar(b,y);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.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,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const Nm=15e3,Cm=6e4,Im=1200,zo=12,Am=8e3,Mm=4e3,Wn=new Map,Hn=new Map,Fn=new Set,cr=new Map;function Tm(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 Vo(e,s){const r=cr.get(e);!r||r.size===0||(cr.delete(e),r.forEach(n=>n(s)))}function Lm(e,s){return new Promise(r=>{const n=cr.get(e)||new Set;cr.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&cr.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function Sr(){const{sendCommand:e,sendData:s}=Pt(),{injectEntries:r,getIdes:n}=cn();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??Cm,l=Hn.get(a)||0;if(!(i!=null&&i.force)&&Fn.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=Wn.get(a);if(u)return u;const p=(async()=>{if(s&&!Fn.has(a)&&(Fn.add(a),os.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},d=>{const b=n(),y=b.find(S=>S.id===a),h=un(d.status,{daemonId:a,existingDaemon:y,existingEntries:b,timestamp:d.timestamp});h.length>0&&r(h),Hn.set(a,Date.now()),Vo(a,!0)}),!(i!=null&&i.force)&&await Lm(a,Im)))return;const m=await e(a,"get_status_metadata"),f=Tm(m);if(!f)return;const g=n(),w=g.find(d=>d.id===a),A=un(f,{daemonId:a,existingDaemon:w,existingEntries:g,timestamp:f.timestamp||Date.now()});A.length>0&&r(A,{authoritativeDaemonIds:[a]}),Hn.set(a,Date.now()),Vo(a,!0)})().finally(()=>{Wn.delete(a)});return Wn.set(a,p),p},[n,r,e,s])}function Gt(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function Va(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=Os(e.content),i=Os(s.content);if(!a||!i||!(a===i||br(a,i)||br(i,a)))return!1;const l=Gt(e),u=Gt(s);return l&&u?Math.abs(l-u)<=15e3:!!e._localId!=!!s._localId}function Go(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),Gt(e)&&(s+=1),s}function Ns(e){return Os(e==null?void 0:e.content)}function br(e,s){if(!e||!s||e.length<=s.length)return!1;const r=Math.max(12,Math.min(80,Math.floor(e.length*.4)));return s.length<r?!1:e.startsWith(s)||e.includes(s)}function _m(e,s){const r=Ns(e),n=Ns(s);return!r||!n||r===n?null:br(r,n)?e:br(n,r)?s:null}function Rm(e,s){const r=_m(e,s);if(r)return r;const n=Go(e),a=Go(s);return a!==n?a>n?s:e:Ns(s).length>=Ns(e).length?s:e}function Pm(e){return!!e&&!!(e.id||e._localId||e._turnKey)}function lr(e){if(!e)return[];const s=[],r=l=>{l&&s.push(l)};e.id&&r(`id:${String(e.id)}`),e._localId&&r(`local:${String(e._localId)}`),e._turnKey&&r(`turn:${String(e._turnKey)}`);const n=String(e.role||"").toLowerCase(),a=Ns(e),i=Gt(e),c=i?Math.round(i/15e3):0;return n&&a&&(r(`content:${n}:${a}`),r(`preview:${n}:${a.slice(0,120)}:${c}`)),s}function fs(e,s=Va){const r=[],n=new Map,a=(c,l)=>{for(const u of lr(c)){const p=n.get(u);p?p.push(l):n.set(u,[l])}},i=(c,l)=>{for(const u of lr(c)){const p=n.get(u);if(!p)continue;const m=p.filter(f=>f!==l);m.length>0?n.set(u,m):n.delete(u)}};for(const c of e){const l=new Set;for(const m of lr(c)){const f=n.get(m);f&&f.forEach(g=>l.add(g))}const u=l.size>0?Array.from(l).sort((m,f)=>m-f).find(m=>s(r[m],c)):Pm(c)?-1:r.findIndex(m=>s(m,c));if(u!==void 0&&u>=0){const m=Rm(r[u],c);m!==r[u]&&(i(r[u],u),r.splice(u,1,m),a(m,u));continue}const p=r.length;r.push(c),a(c,p)}return r}function Dm(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:fs([...r,...n])}function qo(e){return[...e].sort((s,r)=>{const n=Gt(s),a=Gt(r);return n&&a&&n!==a?n-a:0})}function Yo(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=>Va(i,n));return a>=0?(r.splice(a,1),!1):!0})}function Em(e,s,r=Va){const n=new Map,a=i=>{for(const c of lr(i)){const l=n.get(c);l?l.push(i):n.set(c,[i])}};return s.forEach(a),e.filter(i=>{const c=Ns(i),l=String((i==null?void 0:i.role)||"").toLowerCase(),u=Gt(i),p=new Set;for(const f of lr(i)){const g=n.get(f);g&&g.forEach(w=>p.add(w))}return!(p.size>0?Array.from(p):s).some(f=>{if(r(i,f))return!0;const g=String((f==null?void 0:f.role)||"").toLowerCase();if(!c||!l||l!==g)return!1;const w=Ns(f);if(!br(w,c)&&w!==c)return!1;const A=Gt(f);return u&&A?Math.abs(u-A)<=15e3:!0})})}function Es(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:tt(e)||Ze(e)?{agentType:Bt(e)}:e.streamSource==="agent-stream"?{agentType:Bt(e)}:s}function gr(e){return e?kr(e):""}function Zs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Ga(e){if(!e)return null;if(Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return"Resolve the pending approval prompt before sending another message.";switch(e.status){case"waiting_approval":case"waiting_for_user_input":return"Resolve the pending approval prompt before sending another message.";default:return null}}function $m(e){const s=e instanceof Error?e.message:String(e||""),r=s.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":s||"Unable to send message right now."}const Km=60,Bm=1e3;function kc(e={}){return e.isCliLike?Bm:Km}function Om(e={}){return kc(e)}const Nr=60,qa=12e4,Wm=new Set(["generating","waiting_approval","starting","streaming","working"]),Xo=new Map;function Sc(e,s){return`${e}::${s}`}function ya(e=Nr){return{liveMessages:[],cursor:Cc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Nc(e){return Ui(e)}function Cc(e,s=Nr){return{knownMessageCount:e.length,lastMessageSignature:Nc(e[e.length-1]),tailLimit:s}}function Kr(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 Hm(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return fs([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return fs([...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 fs([...e.slice(0,a),...r])}return r}default:return r}}class Fm{constructor(s){Ye(this,"manager");Ye(this,"sendData");Ye(this,"daemonId");Ye(this,"sessionId");Ye(this,"historySessionId");Ye(this,"subscriptionKey");Ye(this,"snapshot");Ye(this,"transportSubscription",null);Ye(this,"listeners",new Set);Ye(this,"retainCount",0);Ye(this,"loadHistoryPromise",null);Ye(this,"pendingDisconnectTimer",null);this.manager=s.manager||os,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=ya(Math.max(0,s.tailLimit??Nr))}updateOptions(s){if(s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId),s.tailLimit!==void 0){const r=Math.max(0,s.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length);this.snapshot={...this.snapshot,cursor:{...this.snapshot.cursor,knownMessageCount:n,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=fs([...r,...this.snapshot.liveMessages]);if(n.length<r.length)return;const a=Cc(n,this.snapshot.cursor.tailLimit);Kr(this.snapshot.liveMessages)===Kr(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.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await s(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}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.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){const r=Hm(this.snapshot.liveMessages,s),n={knownMessageCount:r.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:Nc(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};Kr(this.snapshot.liveMessages)===Kr(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 Ic(e){const s=Sc(e.daemonId,e.sessionId),r=Xo.get(s);if(r)return r.updateOptions(e),r;const n=new Fm(e);return Xo.set(s,n),n}function Um(e,s){return{...e,loadHistoryPage:s}}function zm(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Vm(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(Wm.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=s.now??Date.now(),a=Math.max(0,Number(s.recentActivityMs??qa)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=a:Array.isArray(e.messages)&&e.messages.length>0}function Gm(e=qa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function qm(e,s={}){const r=new Set,n=[];for(const a of e){if(!Vm(a,s))continue;const i=kr(a),c=a.sessionId||"";if(!i||!c)continue;const l=Sc(i,c);if(r.has(l))continue;r.add(l);const u=jr(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(zm),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Ym(e,s){const{sendData:r,sendCommand:n}=Pt(),a=(s==null?void 0:s.enabled)!==!1,i=kr(e),c=e.sessionId||"",l=jr(e)||c,u=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??Nr),m=o.useMemo(()=>!a||!i||!c?null:Ic({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:p}),[i,a,l,r,c,u,p]),[f,g]=o.useState(()=>(m==null?void 0:m.getSnapshot())||ya(p));o.useEffect(()=>{if(!m){g(ya(p));return}m.retain(),g(m.getSnapshot());const A=m.subscribe(d=>{g(d)});return()=>{A(),m.release()}},[m,p]),o.useEffect(()=>{m&&(m.hydrateLiveMessages(e.messages),g(m.getSnapshot()))},[e.messages,m]);const w=o.useCallback(async()=>{!m||!i||!c||await m.loadHistoryPage(async()=>{const A=e.agentType,d=await n(i,"chat_history",{agentType:A,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(()=>Um(f,w),[w,f])}function Xm(e,s){const{sendData:r}=Pt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??Nr),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??qa)),c=Gm(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const m=setInterval(()=>{u(f=>f+1)},c);return()=>{clearInterval(m)}},[e.length,n,c]);const p=o.useMemo(()=>qm(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||p.descriptors.length===0)return;const m=p.descriptors.map(f=>Ic({...f,sendData:r,tailLimit:a}));return m.forEach(f=>f.retain()),()=>{m.forEach(f=>f.release())}},[p.signature,n,r,a])}function Jm(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Qm(e){return Jm(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Zm=60;function va({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:p=!1,scrollToBottomRequestNonce:m,isInputActive:f=!0}){var ce,Se,X,he,J;const g=o.useRef(new Map),w=Sr();wr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const A=at.useMemo(()=>qs(e),[e.status,e.connectionState]),d=o.useMemo(()=>bm(e,s),[e,s]),b=o.useMemo(()=>{var Z;return Fa((Z=d.targetEntry)==null?void 0:Z.providerControls,{hostIdeType:e.hostIdeType,providerType:d.providerType})},[e.hostIdeType,d.providerType,(ce=d.targetEntry)==null?void 0:ce.providerControls]),y=kc({isCliLike:d.isCli||d.isAcp}),h=Om({isCliLike:d.isCli||d.isAcp}),S=Ym(e,{enabled:!!e.sessionId,tailLimit:h}),[_,k]=o.useState(y),I=e.tabKey,j=S.historyMessages,v=S.hasMoreHistory,x=S.historyError,E=Dm(S.liveMessages,e.messages);o.useEffect(()=>{k(y)},[y,I]);const L=Math.max(0,E.length-_),M=Ua(e),T=kr(e),B=Qm(e),H=Ga(e),C=a||H,R=!!H,[U,N]=o.useState(!1);o.useEffect(()=>{const Z=d.targetEntry;T&&(!Z||Z.providerControls===void 0||Z.controlValues===void 0)&&w(T,{minFreshMs:3e4}).catch(()=>{})},[T,d.isAcp,(Se=d.targetEntry)==null?void 0:Se.providerControls,(X=d.targetEntry)==null?void 0:X.controlValues,w]);const D=o.useCallback(async()=>{if(!U){if(E.length>_){k(Z=>Math.min(E.length,Z+Zm));return}N(!0);try{await S.loadHistoryPage()}finally{N(!1)}}},[S,U,E.length,_]),{allMessages:Y,receivedAtMap:q}=o.useMemo(()=>{const Z=L>0?E.slice(-_):E;if(j.length===0){const ye=qo(fs(Z)),ie={};return ye.forEach((le,se)=>{const pe=`${e.tabKey}:${_s(le,se)}`;let ne=Gt(le)||g.current.get(pe)||0;ne||(ne=Date.now(),g.current.set(pe,ne)),ie[_s(le,se)]=ne}),{allMessages:ye,receivedAtMap:ie}}const ue=Em(j,Z),de=qo(fs([...ue,...Z])),z={};return de.forEach((ye,ie)=>{const le=`${e.tabKey}:${_s(ye,ie)}`;let se=Gt(ye)||g.current.get(le)||0;se||(se=Date.now(),g.current.set(le,se)),z[_s(ye,ie)]=se}),{allMessages:de,receivedAtMap:z}},[e.tabKey,L,j,E,_]),W=o.useMemo(()=>l.filter(Z=>Z.routeId===e.tabKey).sort((Z,ue)=>Z.timestamp-ue.timestamp),[l,e.tabKey]),ae=o.useMemo(()=>{if(E.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((A.isGenerating||e.status==="streaming")&&N(!1),e.status==="not_monitored"&&B)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(fr,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bs,{size:14})," Open ",M," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&B)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(qi,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bs,{size:14})," Open ",M," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!U)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,B,i,c,U,E.length,M,A.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[p&&t.jsx(jc,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(du,{messages:Y,actionLogs:W,agentName:Fs(e)||M||"Agent",userName:u,isCliMode:d.isCli||d.isAcp,isWorking:A.isGenerating,contextKey:e.tabKey,receivedAtMap:q,onLoadMore:D,isLoadingMore:U,hasMoreHistory:v,hiddenLiveCount:L,loadError:x??void 0,emptyState:ae,scrollToBottomRequestNonce:m}),t.jsx(um,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:d.providerType,displayLabel:d.displayLabel,controls:(he=d.targetEntry)==null?void 0:he.providerControls,controlValues:(J=d.targetEntry)==null?void 0:J.controlValues,isActive:f,isCliTerminal:d.isCliTerminal}),!d.isCliTerminal&&t.jsx(mm,{contextKey:e.tabKey,panelLabel:M,isSending:n,isBusy:R,statusMessage:C,onSend:r,isActive:f,showControlsToggle:b.length>0})]})}let Ac=js;function Mc(){return Ac()}class ep{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 Tc=new ep;class tp{sendPtyInput(s,r,n){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let ft=new tp;function sp(e){e.dashboardWS&&(Tc=e.dashboardWS),e.connectionManager&&(ft=e.connectionManager),e.useDaemonsHook&&(Ac=e.useDaemonsHook)}const Lc=.6,rp=1.15;function np(e,s={}){const r=typeof s.minScale=="number"?s.minScale:Lc;return!Number.isFinite(e)||e<=0?1:e<=480?r:1}function lt(e){return Ua(e)}function Cs(e){return bc(e).join(" · ")}function _c(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=Os(s==null?void 0:s.content);return r||(e.title?e.title:Cs(e)||"No messages yet")}function Rc(e,s){const{isReconnecting:r,isConnecting:n}=qs(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function ap(e,s){const r=["Chat",...bc(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function hs(e){return Rc(e)||Cs(e)}function op(e){return`${lt(e)} · ${_c(e)}`}function ip(e){const s=dn(e),r=s?ot(s):Fs(e);return`${lt(e)} — ${r||"Agent"}`}function cp(e){return Fs(e)||"CLI"}function Pc(e){return xc(e)}function Dc(e){return e?`Remote · ${lt(e)||e.workspaceName||"Session"}`:"Remote"}function lp({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0}){var q;const{ides:l}=js(),u=o.useRef(null),{sendData:p}=Pt(),[m,f]=o.useState(""),[g,w]=o.useState(!1),[A,d]=o.useState(1),b=o.useRef(!1),y=o.useRef(0),h=o.useRef(!1),S=o.useRef(""),_=o.useRef(null),k=o.useRef(!1),I=o.useRef(null),j=e.tabKey,v=e.sessionId||"",x=e.daemonId||((q=e.routeId)==null?void 0:q.split(":")[0])||e.routeId||"",E=l.find(W=>W.id===x&&W.type==="adhdev-daemon"),L=(E==null?void 0:E.terminalSizingMode)==="fit"?"fit":"measured",M=Ga(e),T=i||M,B=Lc,H=rp,C=()=>typeof window>"u"?1:np(window.innerWidth||0,{minScale:B}),R=()=>{var W,ae;y.current=0,h.current=!1,S.current="",_.current=null,k.current=!1,I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),w(!1),(ae=(W=r.current)==null?void 0:W.reset)==null||ae.call(W)},U=()=>{var W,ae;y.current=0,h.current=!1,S.current="",_.current=null,k.current=!1,I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),w(!0),(ae=(W=r.current)==null?void 0:W.reset)==null||ae.call(W)},N=()=>{var ae;if(I.current=null,!c)return;const W=S.current;W&&(S.current="",(ae=r.current)==null||ae.write(W))},D=W=>{W&&(S.current+=W,c&&I.current===null&&(I.current=requestAnimationFrame(N)))},Y=(W,ae=0,ce,Se)=>{var X,he,J,Z,ue;ae>0&&y.current>=ae||ae===0&&h.current||(y.current=ae,w(!0),typeof ce=="number"&&typeof Se=="number"&&ce>0&&Se>0&&((he=(X=r.current)==null?void 0:X.resize)==null||he.call(X,ce,Se)),(Z=(J=r.current)==null?void 0:J.reset)==null||Z.call(J),W&&((ue=r.current)==null||ue.write(W)))};return o.useEffect(()=>{R()},[v]),o.useEffect(()=>{var ae;if(!v)return;const W=((ae=ft.onRuntimeEvent)==null?void 0:ae.call(ft,v,ce=>{if(!(!ce||ce.sessionId!==v)){if(ce.type==="runtime_snapshot"){if(!c){_.current={text:ce.text||"",seq:ce.seq||0,cols:ce.cols,rows:ce.rows};return}Y(ce.text||"",ce.seq||0,ce.cols,ce.rows);return}if(ce.type==="session_output"){h.current=!0,typeof ce.seq=="number"&&(y.current=Math.max(y.current,ce.seq)),g||w(!0),typeof ce.data=="string"&&D(ce.data);return}if(ce.type==="session_cleared"){if(!c){k.current=!0,S.current="",_.current=null;return}U()}}}))||(()=>{});return()=>{W()}},[x,v,r,c,g]),o.useEffect(()=>{var ae,ce,Se;if(!v)return;x&&((ae=ft.getState)==null?void 0:ae.call(ft,x))==="connected"&&(w(!0),(ce=ft.requestRuntimeSnapshot)==null||ce.call(ft,x,v).catch(()=>{}));const W=(Se=ft.onStateChange)==null?void 0:Se.call(ft,(X,he)=>{var J;X!==x||he!=="connected"||(w(!0),(J=ft.requestRuntimeSnapshot)==null||J.call(ft,x,v).catch(()=>{}))});return()=>{W==null||W()}},[x,v,r]),o.useEffect(()=>{s&&R()},[s,j,r]),o.useEffect(()=>{f("")},[e.tabKey]),o.useEffect(()=>{const W=()=>{b.current||d(C())};return W(),window.addEventListener("resize",W),()=>window.removeEventListener("resize",W)},[]),o.useEffect(()=>{var ae;if(!c){(ae=u.current)==null||ae.blur();return}k.current&&(k.current=!1,U());const W=_.current;W&&(_.current=null,Y(W.text,W.seq,W.cols,W.rows)),S.current&&I.current===null&&(I.current=requestAnimationFrame(N)),requestAnimationFrame(()=>{var ce;(ce=r.current)==null||ce.bumpResize()})},[c]),o.useEffect(()=>()=>{I.current!==null&&(cancelAnimationFrame(I.current),I.current=null)},[]),o.useEffect(()=>{const W=ae=>{var Se;const ce=ae.detail;ce!=null&&ce.sessionId&&ce.sessionId!==v||g&&((Se=r.current)==null||Se.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",W),()=>{window.removeEventListener("adhdev:fit-cli-terminal",W)}},[g,v,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(W=>Math.max(B,Number((W-.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(W=>Math.min(H,Number((W+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-x-auto overflow-y-hidden rounded-lg overscroll-contain",children:t.jsx("div",{style:{width:`${100/A}%`,height:`${100/A}%`,transform:`scale(${A})`,transformOrigin:"top left"},children:t.jsx(Zi,{ref:r,readOnly:!g||!c,sizingMode:L,onInput:W=>{g&&(p==null||p(x,{type:"pty_input",sessionId:v,targetSessionId:v,data:W}))}})})}),!g&&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.jsxs("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:u,type:"text",placeholder:T||`Send message to ${lt(e)}...`,value:m,disabled:!g||!c,onChange:W=>f(W.target.value),onPaste:W=>{const ae=W.clipboardData.getData("text");ae&&f(ce=>ce+ae),W.preventDefault()},onKeyDown:W=>{if(W.key!=="Enter")return;if(W.nativeEvent.isComposing){W.preventDefault();return}W.preventDefault();const ae=m.trim();!g||!ae||M||n(ae).then(ce=>{ce!==!1&&f("")})},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 W=m.trim();!g||!W||M||n(W).then(ae=>{ae!==!1&&f("")})},disabled:!g||!c||pc({hasDraft:!!m.trim(),isBusy:!!M}),className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!M?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!M?{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"})})})]}),T&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:T})]})]})}function dp({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 up({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 Ya({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(gn,{size:n}):t.jsx(Zt,{size:n})})}function Jo({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Qo({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=vn(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 mp({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:g,onShowAllHidden:w,onResetPanelsToMain:A,inboxOpen:d,onInboxOpenChange:b,hiddenOpen:y,onHiddenOpenChange:h,onOpenNewSession:S,actionShortcuts:_,notifications:k,notificationUnreadCount:I,onOpenNotification:j,onMarkNotificationRead:v,onMarkNotificationUnread:x,onDeleteNotification:E}){const{ides:L,p2pStates:M={}}=js(),T=!!e&&tt(e)&&!Ze(e),B=!!e&&Ze(e),H=u||(e?fc(e)?"terminal":"chat":null),[C,R]=o.useState(!1),U=o.useRef(null),N=o.useRef(null),D=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",Y=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",q=L.filter(z=>z.type==="adhdev-daemon"),W=Object.values(M),ae=W.filter(z=>z==="connected").length,ce=W.filter(z=>z==="connecting"||z==="new"||z==="checking").length,X=r!=="connected"||q.length===0?null:ce>0&&ae===0?"P2P connecting...":ae>0&&s===0?"Waiting for IDE...":null,he=o.useMemo(()=>k.filter(z=>!z.readAt),[k]),J=o.useMemo(()=>k.filter(z=>!!z.readAt),[k]),Z=o.useMemo(()=>he.slice(0,9),[he]),ue=I;o.useEffect(()=>{if(!d)return;const z=ye=>{var ie;(ie=U.current)!=null&&ie.contains(ye.target)||b(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[d,b]),o.useEffect(()=>{if(!y)return;const z=ye=>{var ie;(ie=N.current)!=null&&ie.contains(ye.target)||h(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[y,h]),o.useEffect(()=>{if(!y&&!d)return;const z=ye=>{if(!ye.altKey)return;const ie=ye.code.match(/^Digit([1-9])$/);if(!ie)return;const le=Number(ie[1])-1,se=y?f[le]:void 0,pe=d?Z[le]:void 0;if(!(!se&&!pe)){if(ye.preventDefault(),ye.stopPropagation(),se){g==null||g(se),h(!1);return}pe&&(j(pe),b(!1))}};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[f,y,d,Z,h,b,j,g]);const de=z=>{if(!z)return;const ye=a.find(ie=>ie.tabKey===z);ye&&(m==null||m(ye))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(Zt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?lt(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:Y}})})]}),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:Y}}),X&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",X]}),S&&t.jsx("button",{type:"button",onClick:S,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(Wd,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(T||B||!Ze(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:Cs(e)||lt(e),children:lt(e)}),(T||B)&&l&&t.jsxs(t.Fragment,{children:[T&&p&&H&&t.jsx(Ya,{mode:H,onChange:p,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:B?"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(At,{size:14})})]}),!Ze(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Da,{size:14})}),!T&&!Ze(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Rt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:U,children:[t.jsxs("div",{className:`dashboard-header-hidden${C?" is-drop-target":""}`,ref:N,onDragEnter:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),R(!0))},onDragOver:z=>{z.dataTransfer.types.includes("text/tab-key")&&(z.preventDefault(),z.dataTransfer.dropEffect="move",R(!0))},onDragLeave:z=>{z.currentTarget.contains(z.relatedTarget)||R(!1)},onDrop:z=>{const ye=z.dataTransfer.getData("text/tab-key");z.preventDefault(),R(!1),de(ye)},children:[t.jsxs("button",{type:"button",onClick:()=>h(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${_!=null&&_.toggleHiddenTabs?` (${_.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(Yi,{size:16}),f.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:f.length})]}),y&&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(Jo,{value:_==null?void 0:_.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[A&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:A,children:"Reset panels"}),f.length>0&&w&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{w(),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(Jo,{value:_==null?void 0:_.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:lt(e)})]}),f.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:f.map(z=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{g==null||g(z),h(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:lt(z)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[f.indexOf(z)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",f.indexOf(z)+1]}):null,Cs(z)]})]},z.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(yn,{size:16}),ue>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:ue})]}),d&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[he.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),he.map(z=>t.jsx(Qo,{notification:z,shortcutIndex:Z.indexOf(z)>=0?Z.indexOf(z)+1:void 0,onOpen:()=>j(z),onMarkRead:()=>v(z.id),onMarkUnread:()=>x(z.id),onDelete:()=>E(z.id)},z.id))]}),J.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),J.map(z=>t.jsx(Qo,{notification:z,onOpen:()=>j(z),onMarkRead:()=>v(z.id),onMarkUnread:()=>x(z.id),onDelete:()=>E(z.id)},z.id))]}),k.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function jt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function pp(e,s){return String(e||"")!==String(s||"")}function fp(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&&!cc(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
32
|
+
`).includes(a)))}function hp(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 Ec(e,s={}){return hp(fp(e,s),s.sortMode||"recent")}function mn(e){return e?"Resume saved history":"Start fresh"}function Xa(e){return e?"Resuming saved history…":"Starting fresh…"}function xp(){return"Start fresh"}function $c(e,s=!1){return e==="cli"?mn(s):e==="ide"?"Start IDE":"Start ACP session"}function Kc(e,s=!1){return e==="cli"?Xa(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function bp(){return"Recover hosted runtime"}function gp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function yp(){return"Open saved history"}function vp(){return"Saved History"}function Ja(){return"Use saved history when you want continuity in the same provider conversation."}function wp(){return"No saved history found yet."}function jp(){return"Refresh saved history"}function kp(){return"Refreshing saved history…"}function xs(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function bs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Us(e){return e==="start-fresh"?"Start fresh":"Restart"}function zs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Qa(e){return`Resume saved history with ${e}?`}function Za(){return"Review or change the target workspace before resuming saved history."}function Sp(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 eo({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:g,onResumeSavedSession:w}){var v;const A=s.find(x=>x.id===e.routeId),d=(A==null?void 0:A.chats)||[],b=(v=A==null?void 0:A.activeChat)==null?void 0:v.id,y=tt(e)&&!Ze(e),[h,S]=o.useState(()=>jt()),_=l||h,k=x=>{if(u){u(x);return}S(x)},I=o.useMemo(()=>Ec(a,{textQuery:_.textQuery,workspaceQuery:_.workspaceQuery,modelQuery:_.modelQuery,resumableOnly:_.resumableOnly,sortMode:_.sortMode}),[_.modelQuery,_.resumableOnly,_.sortMode,_.textQuery,_.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:y?vp():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:ip(e)}),y&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ja()})]}),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(At,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!y&&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"}),y?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:_.textQuery,onChange:x=>k({..._,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:_.workspaceQuery,onChange:x=>k({..._,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:_.modelQuery,onChange:x=>k({..._,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:_.sortMode,onChange:x=>k({..._,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:_.resumableOnly,onChange:x=>k({..._,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),I.map(x=>{const E=e.providerSessionId===x.providerSessionId,L=E||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{L||!w||w(x)},disabled:L,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${L?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${E?"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:Sp(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",Ss(x.summaryMetadata)?` · ${Ss(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:E?"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)),(y&&!i&&I.length===0||!y&&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(zd,{size:32})}),t.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":wp():"No recent chat sessions found."})]}),y&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:kp()})})]}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:t.jsx("button",{onClick:g,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Gs,{size:13})," ",y?jp():"Refresh History"]})})})]})]});return typeof document>"u"?j:pr.createPortal(j,document.body)}const Zo={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 Bc({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=Zo[n.type]||Zo.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(At,{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 Np=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Cp(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Ip(e){return e.sessionId||e.instanceId||e.agentType}function Un(e,s){return e||s}function ei(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 Oc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=_t(r,{fallbackId:r.id}));return s}function Wc(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 to(e,s,r={}){return Ap(e,s,Wc(e,r))}function Ap(e,s,r={}){var f,g,w,A,d,b;const n=[],a=r.machineName,i=r.connectionState,c=Cp(e),l=Tu(e.type,{agentName:e.cliName}),u=tt(e)||Ze(e)?l:ot(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var h,S;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||ot(y.providerType),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((h=y.activeChat)==null?void 0:h.messages)||[],activeModal:((S=y.activeChat)==null?void 0:S.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,surfaceHidden:y.surfaceHidden}}):[],m=Np(e);if(m){const y=e.sessionId||e.instanceId,h=l,S=(f=e.activeChat)==null?void 0:f.activeModal,_=S&&Array.isArray(S.buttons)&&S.buttons.length>0,k=Ct((g=e.activeChat)==null?void 0:g.status,{activeModal:(w=e.activeChat)==null?void 0:w.activeModal})||Ct((d=(A=e.agents)==null?void 0:A[0])==null?void 0:d.status)||"idle",I=e.activeChat||{title:"",messages:[]};let j=I.title&&String(I.title).trim()?String(I.title).trim():"";const v=(b=e.activeChat)==null?void 0:b.id,x=e.chats;if(v&&Array.isArray(x)&&x.length>0){const H=x.find(C=>C.id===v||C.id&&String(C.id)===String(v));H!=null&&H.title&&String(H.title).trim()&&(j=String(H.title).trim())}const E=(tt(e)||Ze(e),e.type),L=(tt(e)||Ze(e))&&Wo(j,h,E)?"":j,M=I.messages||[],T=ei(s,[e.id,y]),B=Yo(M,T);n.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:tt(e)?e.mode||"terminal":"chat",agentName:h,agentType:E,status:k,title:L,messages:[...M,...B],resume:e.resume,hostIdeType:!tt(e)&&!Ze(e)?e.type:void 0,workspaceName:c,displayPrimary:L||c||(tt(e)?e.mode==="chat"?h:"Terminal":h),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:_?S.buttons:void 0,modalMessage:_?S.message:void 0,streamSource:"native",tabKey:Un(y,e.id),machineName:a,connectionState:i})}if(m&&(tt(e)||Ze(e)))return n;for(const y of p){const h=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,S=Lu(y),_=Ip(y),k=`${e.id}:${_}`,I=y.title&&String(y.title).trim()||"",j=Wo(I,y.agentName,y.agentType)?"":I,v=y.messages||[],x=ei(s,[k,y.sessionId,y.instanceId]),E=Yo(v,x);(y.transport==="cdp-webview"||y.sessionId||y.providerSessionId||v.length>0||E.length>0||h||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(S))&&n.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:S,title:j,messages:[...v,...E],hostIdeType:e.type,workspaceName:c,displayPrimary:j||c||y.agentName||u,displaySecondary:`${u} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,modalButtons:h?y.activeModal.buttons:void 0,modalMessage:h?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Un(y.sessionId||y.instanceId,k),machineName:a,connectionState:i})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Un(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function Mp(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 Tp(e,s){const r=Mp(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Hc=[{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:"🏄"}],Fc=[{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:"🧩"}],Uc=[{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:"🟠"}],Lp=Hc,_p=Fc,Rp=Uc;function Is(...e){return md(pd(e))}function Pp({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:Is("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 zc({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(Pp,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:Is("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Lt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:Is("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 Vc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:Is("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Dp={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},Ep={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Br({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:Is("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Dp[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:Ep[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}const $p={online:"bg-green-500/10 text-green-400 border-green-500/30",idle:"bg-yellow-500/10 text-yellow-400 border-yellow-500/30",busy:"bg-orange-500/10 text-orange-400 border-orange-500/30",error:"bg-red-500/10 text-red-400 border-red-500/30",offline:"bg-gray-500/10 text-text-secondary border-gray-500/30"},Kp={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Bp({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:Is("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",$p[e],r),children:[t.jsx("span",{className:Is("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Kp[e])}),n]})}const wa="adhdev:themechange";function Op(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ts(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ls(e){return e==="system"?Op():e}function Gc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Zr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(wa,{detail:{preference:e,theme:s}}))}function Wp(){const e=Ts(),s=Ls(e);Gc(s),Zr(e,s)}function so(){const[e,s]=o.useState(Ts),[r,n]=o.useState(()=>Ls(Ts()));o.useEffect(()=>{Gc(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),Zr("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:Ts()),n(f==="dark"||f==="light"?f:Ls(Ts()))},l=u=>{if(u.key!=="theme")return;const p=Ts(),m=Ls(p);s(p),n(m)};return window.addEventListener(wa,c),window.addEventListener("storage",l),()=>{window.removeEventListener(wa,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=Ls(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Zr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=Ls(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Zr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const ti={dark:"Dark",light:"Light",system:"System"};function Hp({collapsed:e}){const{preference:s,cycleTheme:r}=so(),n=s==="dark"?t.jsx(Gd,{size:16}):s==="light"?t.jsx(Vd,{size:16}):t.jsx(qd,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ti[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:ti[s]})]})}function us({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 Fp({onPrefChange:e}){const[s,r]=Wu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(yn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:c=>i("globalEnabled",c)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:c=>i("browserNotifications",c)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{uc().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Yd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Xd,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(fr,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function pn(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Up(e,s){const r=pn(e),n=pn(s);if(!r||!n)return e.localeCompare(s);for(let a=0;a<3;a+=1){if(r[a]<n[a])return-1;if(r[a]>n[a])return 1}return 0}function qc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function dr(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Up(r,s)>=0)return!1;const n=pn(r),a=pn(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function zp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function zn(e,s){return e instanceof Error?e.message:s}function Vp({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(Vc,{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(qp,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function si({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 pr.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 Gp(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Lp,..._p,...Rp].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 qp({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var B,H;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,m]=o.useState(null),[f,g]=o.useState("idle"),[w,A]=o.useState(""),d=e.version||null,b=((B=e.machine)==null?void 0:B.platform)||((H=e.system)==null?void 0:H.platform)||"",y=_t(e,{fallbackId:e.id}),h=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",S=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),_=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),k=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),I=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const C=zp(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),u(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),u(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(C.error||"Upgrade failed"))}catch(C){c("error"),u(zn(C,"Connection lost during upgrade"))}}},v=async()=>{if(m(null),!!n){g("loading");try{await n(e.id),g("done"),A("Machine disconnected.")}catch(C){g("error"),A(zn(C,"Failed to disconnect"))}}},x=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),A("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){g("error"),A(zn(C,"Failed to revoke token"))}}},E="0.8.88",L=qc(e,E),M=dr(e,E),T=S.length+_.length+k.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:y}),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] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!L&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&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${E}`,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${E}`}`}`}),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(Bp,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[I&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&T>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),T>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[S.map(C=>{const R=Gp(C.type),U=C.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:R.icon}),t.jsx("span",{children:R.name}),U!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${U?"bg-green-400":"animate-pulse"}`,style:U?void 0:{background:"var(--status-warning)"},title:U?"CDP connected":"CDP connecting..."})]},C.id)}),_.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:C.cliName||"CLI"})]},C.id)),k.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&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:w||l})]}),p==="disconnect"&&t.jsx(si,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
|
|
33
33
|
|
|
34
34
|
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
35
35
|
|
|
36
|
-
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:v,onCancel:()=>m(null)}),p==="revoke"&&t.jsx(
|
|
36
|
+
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:v,onCancel:()=>m(null)}),p==="revoke"&&t.jsx(si,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
|
|
37
37
|
|
|
38
38
|
This will:
|
|
39
39
|
• Immediately disconnect the machine
|
|
40
40
|
• Delete the machine registration
|
|
41
41
|
• Require restarting ADHDev on that machine
|
|
42
42
|
|
|
43
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>m(null)})]})}const Up=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function zp(){const{preference:e,setPreference:s}=so();return t.jsx("div",{className:"flex gap-2",children:Up.map(r=>t.jsxs("button",{onClick:()=>s(r.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===r.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===r.id?{color:"var(--accent-on-primary)"}:void 0,children:[t.jsx("span",{children:r.icon}),r.label]},r.id))})}function Vp(e){const s=e.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function Gp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Vn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function si(e){const{r:s,g:r,b:n}=Gp(e);return .2126*Vn(s)+.7152*Vn(r)+.0722*Vn(n)}function ri(e,s){const r=si(e),n=si(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function qc(e){const s=Vp(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return ri(s,r)>=ri(s,n)?r:n}const ja={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},ka={bgPrimary:"#fff8ee",bgSecondary:"#fff1de",surfacePrimary:"#ffffff",textPrimary:"#24160f",textSecondary:"#6f6255",textMuted:"#938374",borderSubtle:"#e7d3ba",borderDefault:"#d7b892",accentColor:"#d97706",userBubble:"#f59e0b",userText:"#1a1a1a",assistantBubble:"#fffaf4",assistantText:"#24160f",containerBg:"#fff8ee",sendButton:"#d97706",inputBorder:"#d7b892",bubbleRadius:16},qp=[{id:"midnight",name:"Midnight",description:"Classic violet theme",preview:{dark:{userBubble:"#8b5cf6",assistantBubble:"#18181d",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0f0f13",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#7c3aed",assistantBubble:"#ffffff",assistantBorder:"1px solid rgba(0,0,0,0.08)",containerBg:"#f0f1f5",textColor:"#52525b"}}},{id:"ember",name:"Ember",description:"Default landing-inspired amber theme",preview:{dark:{userBubble:"#f59e0b",assistantBubble:"#111726",assistantBorder:"1px solid rgba(255,255,255,0.08)",containerBg:"#0a0e1a",textColor:"#9ca3af"},light:{userBubble:"#f59e0b",assistantBubble:"#fffaf4",assistantBorder:"1px solid rgba(146,64,14,0.10)",containerBg:"#fff8ee",textColor:"#6f6255"}}},{id:"aurora",name:"Aurora",description:"Pink accent theme",preview:{dark:{userBubble:"#ec4899",assistantBubble:"#1e1b2e",assistantBorder:"1px solid rgba(236,72,153,0.12)",containerBg:"#0f0d17",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#ec4899",assistantBubble:"#fef2f8",assistantBorder:"1px solid rgba(236,72,153,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}},{id:"honey",name:"Honey",description:"Warm yellow accents",preview:{dark:{userBubble:"#fbbf24",assistantBubble:"#1c1c1e",assistantBorder:"1px solid rgba(255,255,255,0.06)",containerBg:"#111113",textColor:"rgba(255,255,255,0.7)"},light:{userBubble:"#fbbf24",assistantBubble:"#fffbeb",assistantBorder:"1px solid rgba(251,191,36,0.15)",containerBg:"#f0f1f5",textColor:"#1a1a2e"}}}],Yc="adhdev-chat-theme",Xc="adhdev-chat-theme-custom";function en(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Yc)||"ember"}catch{return"ember"}}function Ot(e){try{const s=localStorage.getItem(Xc);if(s){const r=JSON.parse(s);return{...e==="dark"?ja:ka,...r[e]}}}catch{}return e==="dark"?ja:ka}function Or(e,s){try{localStorage.setItem(Xc,JSON.stringify({dark:e,light:s}))}catch{}}function $t(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 fn(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),a=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const Yp={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ur(e,s){var a;const r=(a=Yp[e])==null?void 0:a[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",fn(r,24)),n.style.setProperty("--accent-on-primary",qc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${fn(r,18)})`),n.style.setProperty("--border-accent",$t(r,.35)),n.style.setProperty("--nav-active-bg",$t(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${$t(r,.06)}`)}function gs(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",$t(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",$t(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",$t(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",$t(e.borderSubtle,.5)),s.style.setProperty("--border-default",$t(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",fn(e.accentColor,30)),s.style.setProperty("--accent-on-primary",qc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${fn(e.accentColor,40)})`),s.style.setProperty("--border-accent",$t(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",$t(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${$t(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 ${$t(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 ro(){const e=document.documentElement;["--bg-primary","--bg-secondary","--bg-card","--surface-primary","--surface-secondary","--bg-glass","--bg-glass-hover","--text-primary","--text-secondary","--text-muted","--border-subtle","--border-default","--accent-primary","--accent-primary-light","--accent-on-primary","--accent-gradient","--border-accent","--nav-active-bg","--nav-active-shadow","--chat-user-bg","--chat-user-color","--chat-user-radius","--chat-assistant-bg","--chat-assistant-color","--chat-assistant-radius","--chat-assistant-border","--chat-container-bg","--dashboard-pane-bg","--chat-thought-accent","--chat-tool-accent","--chat-action-color","--chat-send-bg","--chat-input-border"].forEach(r=>e.style.removeProperty(r))}function Xp(e){try{localStorage.setItem(Yc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ys()?"dark":"light";gs(Ot(s))}else ro(),ur(e,ys()?"dark":"light")}function Jp(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=en();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ys()?"dark":"light";gs(Ot(s))}else ro(),ur(e,ys()?"dark":"light")}function ys(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Nt({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function er({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function Qp({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Ot(r));o.useEffect(()=>{a(Ot(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const p={...u,[c]:l},f=Ot(r==="dark"?"light":"dark");return r==="dark"?Or(p,f):Or(f,p),gs(p),s(p),p})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(er,{title:"App Background",children:[t.jsx(Nt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(Nt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(Nt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(er,{title:"App Text",children:[t.jsx(Nt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(Nt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(Nt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(er,{title:"Borders & Accent",children:[t.jsx(Nt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(Nt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(Nt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(er,{title:"Chat Bubbles",children:[t.jsx(Nt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(Nt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(Nt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(Nt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(er,{title:"Chat Layout",children:[t.jsx(Nt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(Nt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(Nt,{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?ja:ka,u=Ot(e?"light":"dark");e?Or(c,u):Or(u,c),a(c),gs(c),s(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function Zp(){const[e,s]=o.useState(en),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Ot("dark"));o.useEffect(()=>{n(ys());const u=new MutationObserver(()=>{const f=ys();n(f);const g=en();g==="custom"?gs(Ot(f?"dark":"light")):ur(g,f?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=ys();n(f);const g=en();g==="custom"?gs(Ot(f?"dark":"light")):ur(g,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"?gs(Ot(r?"dark":"light")):(ro(),ur(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Ot(r?"dark":"light"))},[r]);const c=u=>{s(u),Xp(u)},l=[...qp,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const 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(Qp,{dark:r,onColorsChange:u=>i(u)})]})}const no="adhdev_mobileDashboardMode_v1",Sa="adhdev:mobile-dashboard-mode-change";function ao(){try{return localStorage.getItem(no)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ef(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??ao())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==no||s()};return window.addEventListener(Sa,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Sa,r),window.removeEventListener("storage",n)}}function tf(e){try{localStorage.setItem(no,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Sa,{detail:e}))}function sf(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(ao()==="chat")},[]),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Zt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{s(r),tf(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function rf(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 nf(e,s){const{sendData:r}=Pt(),{injectEntries:n,getIdes:a}=cn(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>os.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const m=a().find(g=>g.id===u),f=rf(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 af=4e3;function Jc(e,s){const{sendData:r}=Pt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=os.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},p=>{l&&(clearTimeout(l),l=null),a(p.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},af):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 of(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Qc(e){const{sendData:s}=Pt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=of(e);if(!a||!e.sessionId||!s){n({});return}const i=os.subscribe({sendData:s},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Ks.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 Zc="adhdev_hiddenTabs";function cf(){try{const e=localStorage.getItem(Zc);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function As(e){try{localStorage.setItem(Zc,JSON.stringify([...e]))}catch{}}function Wr(e){return Ba(e)}function oo(e,s){return rs(s).some(r=>e.has(r))}function lf(){const[e,s]=o.useState(cf),r=o.useCallback(p=>{s(m=>{const f=new Set(m);return f.has(p)?f.delete(p):f.add(p),As(f),f})},[]),n=o.useCallback(p=>{s(m=>{if(m.has(p))return m;const f=new Set(m);return f.add(p),As(f),f})},[]),a=o.useCallback(p=>{s(m=>{if(!m.has(p))return m;const f=new Set(m);return f.delete(p),As(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return As(m),m})},[]),c=o.useCallback((p,m)=>{s(f=>{const g=new Set(f);for(const w of m)g.add(w);return As(g),g})},[]),l=o.useCallback((p,m)=>{s(f=>{const g=new Set(f);for(const w of m)g.delete(w);return As(g),g})},[]),u=o.useCallback(p=>oo(e,p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function el(e){return e instanceof Error?e.message:String(e||"")}function io(e){const s=el(e);return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("P2P channel not open")||s.includes("P2P not available")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function co(e){const s=el(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function ni(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 df(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=ni(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>ni(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function tl(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 uf(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))tl(s,a)===i&&(delete n[a],r=!0);return r?n:e}function mf({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{dc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Rc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Fu(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 pf(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 Gn(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 ff(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 ai(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?ff(Os(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 hf(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||""),ai(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),ai(r.activeChat)].join(":"))].join("|")}function xf(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 bf(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 gf(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 yf(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of rs({routeId:n.routeId}))r.set(i,a);for(const i of rs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of rs({tabKey:n.tabKey}))r.set(i,n)}return r}function vf(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function wf(e){const s=vf(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=Os(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function jf({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>pf(e),[e]),c=o.useMemo(()=>Bc(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),m=o.useRef(new Map),f=o.useRef(new Map),g=o.useMemo(()=>{const k=new Map,I=[];for(const E of i){const{connectionState:L="new",machineName:M}=Oc(E,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),T=bf(E,r),B=hf(E),H=m.current.get(E.id);if(H&&H.ide===E&&H.sourceSignature===B&&H.connectionState===L&&H.machineName===M&&gf(H.localRefs,T)){k.set(E.id,H),I.push(...H.conversations);continue}const C=to(E,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),R={ide:E,sourceSignature:B,connectionState:L,machineName:M,localRefs:T,conversations:C};k.set(E.id,R),I.push(...C)}m.current=k;const j=new Map,v=E=>{const L=wf(E),M=f.current.get(E.tabKey);if(M&&M.signature===L)return j.set(E.tabKey,M),M.timestamp;const T={signature:L,timestamp:gc(E)||(M==null?void 0:M.timestamp)||0};return j.set(E.tabKey,T),T.timestamp},x=[...I].sort((E,L)=>yc(E,L,v));return f.current=j,x},[i,r,s,c]),w=o.useMemo(()=>{const k=xf(g,n);return Gn(l.current,k)?l.current:(l.current=k,k)},[g,n]),A=o.useMemo(()=>{const k=new Map,I=Array.from(new Set(w.map(j=>j.routeId)));for(const j of I){const v=Wt(w,j);v&&k.set(j,v)}return k},[w]),d=o.useMemo(()=>{const k=new Map;for(const I of w){const j=A.get(I.routeId),v=I.streamSource==="native"&&j?j:I;for(const x of rs({providerSessionId:I.providerSessionId,sessionId:I.sessionId}))k.set(x,v)}return k},[w,A]),b=o.useMemo(()=>yf(w,A),[w,A]),y=o.useCallback(k=>{if(k)return d.get(k)},[d]),h=o.useCallback(k=>{if(k)return b.get(k)},[b]),S=o.useMemo(()=>{const k=w.filter(I=>!oo(a,I));return Gn(u.current,k)?u.current:(u.current=k,k)},[w,a]),_=o.useMemo(()=>{const k=S.map(I=>I.tabKey);return Gn(p.current,k)?p.current:(p.current=k,k)},[S]);return{chatIdes:i,conversations:w,visibleConversations:S,visibleTabKeys:_,resolveConversationBySessionId:y,resolveConversationByTarget:h}}function kf({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 Sf({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{st.setIdes(e)},[e]),o.useEffect(()=>{st.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=st.onToast(u=>{r(m=>m.some(g=>g.message===u.message&&u.timestamp-g.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=st.onSystemMessage((u,p)=>{var w,A;const m=a(u),f=(w=p._localId)==null?void 0:w.startsWith("sys_approval_"),g=!!(m&&(m.status==="waiting_approval"||(A=m.modalButtons)!=null&&A.length||m.modalMessage));f&&g||n(d=>({...d,[u]:[...d[u]||[],p]}))}),l=st.onClearSystemMessage((u,p)=>{n(m=>{var f;return(f=m[u])!=null&&f.length?{...m,[u]:m[u].filter(g=>{var w;return!(g.role==="system"&&((w=g._localId)!=null&&w.startsWith(p)))})}:m})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=Mc.on("status_event",c=>{st.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 g=Number(u.buttonIndex),w=u.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[g])||"Approve",A=String(w).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(f,"resolve_action",{action:d?"approve":"reject",button:w,...Number.isFinite(g)&&{buttonIndex:g},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};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 Nf="adhdev_dashboardLayout_v1",Cf="adhdev_dashboardDockview_v1",If="adhdev_dashboardDockviewHiddenRestore_v1",tr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function lo(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function sl(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function rl(e){return`${Nf}:${e}`}function Af(e){const s=rl(e);return lo(s,null)}function Mf(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=rl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function nl(e){return`${Cf}:${e}`}function Tf(e){const s=nl(e);return lo(s,null)}function Lf(e,s){try{const r=nl(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function al(e){return`${If}:${e}`}function _f(e){const s=al(e);return lo(s,{})}function Rf(e,s){try{const r=al(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Pf(){return{groupAssignments:[...tr.groupAssignments],focusedGroup:tr.focusedGroup,groupActiveTabIds:{...tr.groupActiveTabIds},groupTabOrders:{...tr.groupTabOrders},groupSizes:[...tr.groupSizes]}}function Df(){const[e]=o.useState(()=>sl(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,g]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,A]=o.useState(!1),d=o.useCallback(()=>{if(w)return;const b=Af(e)??Pf();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),m(b.groupSizes),A(!0)},[w,e]);return o.useEffect(()=>{w&&Mf(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[w,e,s,n,i,l,p]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),y=h=>g(h.matches);return b.addEventListener("change",y),()=>b.removeEventListener("change",y)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:p,setGroupSizes:m,isMobile:f,hasHydratedStoredLayout:w,hydrateStoredLayout:d}}function Ef(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Ka(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function $f({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:g,handleRefreshHistory:w}){const A=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),y=o.useRef(!1);o.useEffect(()=>{if(!e||A.current||s.length===0)return;if(!a){i();return}const h=r(e);if(!h)return;const S=n.get(h.tabKey)??0;c(_=>({..._,[S]:h.tabKey})),l(S),A.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),u(_=>{const k=new URLSearchParams(_);return k.delete("activeTab"),k},{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(A.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){y.current=!1;return}if(!m||y.current||f)return;const h=g.find(S=>S.id===m.routeId);h&&(!h.chats||h.chats.length===0||Ef(h.chats,m))&&(y.current=!0,w())},[p,m,f,g,w]),o.useEffect(()=>{if(!m)return;let h=null,S=0,_=-1,k=0;const I=()=>{h=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(j.length===0){S<18&&(S+=1,h=requestAnimationFrame(I));return}let v=0;for(const x of j)x.scrollTop=x.scrollHeight,v+=x.scrollHeight;v===_?k+=1:(k=0,_=v),S+=1,!(k>=2||S>=18)&&(h=requestAnimationFrame(I))};return h=requestAnimationFrame(I),()=>{h!=null&&cancelAnimationFrame(h)}},[m==null?void 0:m.tabKey])}function Kf({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),g=o.useMemo(()=>{if(e||!n)return null;const y=l(n);return y&&!tt(y)&&!Ze(y)?y:null},[e,n,l]),w=o.useMemo(()=>{const y=u==null?void 0:u.routeId;if(!y)return null;const h=u!=null&&u.tabKey?i.find(S=>S.tabKey===u.tabKey):a?i.find(S=>S.tabKey===a):null;return(h==null?void 0:h.routeId)===y?h:Wt(i,y)},[i,u,a]),A=o.useMemo(()=>{if(w)return c.find(y=>y.id===w.routeId)},[c,w]);o.useEffect(()=>{g&&(p({routeId:g.routeId,tabKey:Uo(g)}),f(g),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,g]);const d=o.useCallback(y=>{y&&(p({routeId:y.routeId,tabKey:Uo(y)}),f(y))},[]),b=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:A,remoteDialogActiveConv:m,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:b}}function qn(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=Ka(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function oi({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]),g=o.useCallback(async(d,b)=>{try{const y=d||(s==null?void 0:s.daemonId)||"",h=await e(y,"switch_chat",{id:b,sessionId:b,...Es(s)}),S=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||S==="switched"||S==="switched-by-title")return;S===!1||S==="not_found"?Zs(a,"⚠️ Session tab not found — try refreshing history"):typeof S=="string"&&S.startsWith("error:")?Zs(a,`⚠️ Switch error: ${S}`):Zs(a,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),Zs(a,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,e,a]),w=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const d=gr(s);await e(d,"new_chat",{...Es(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]),A=o.useCallback(async()=>{var d,b;if(!(!s||p)){m(!0);try{const y=gr(s),h=async()=>e(y,"list_chats",{forceExpand:!0,...Es(s)});let S=await h(),_=(S==null?void 0:S.chats)||((d=S==null?void 0:S.result)==null?void 0:d.chats);qn(_,s)&&(await new Promise(k=>setTimeout(k,450)),S=await h(),_=(S==null?void 0:S.chats)||((b=S==null?void 0:S.result)==null?void 0:b.chats)),S!=null&&S.success&&Array.isArray(_)&&(n(s.routeId,_),qn(_,s)&&!qn(r,s)&&Zs(a,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{m(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:f,handleSwitchSession:g,handleNewChat:w,handleRefreshHistory:A}}function Bf(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 Of(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function ii(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 Hr(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 ci(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 Wf(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 Hf(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 li(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 di(e){return Array(e).fill(100/e)}function Ff({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(()=>Hr(e,p),[e,p]),g=f.assignments,w=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),A=w>1,d=o.useCallback((k,I)=>{s(j=>{const v=new Map(Hr(j,p).assignments);return I===0?v.delete(k):v.set(k,I),v}),n(j=>({...j,[I]:k})),r(I)},[s,p,n,r]),b=o.useCallback(k=>{s(I=>{const j=Hr(I,p).assignments,v=new Map;for(const[x,E]of j)E!==k&&(E>k?v.set(x,E-1):v.set(x,E));return v}),c(I=>{if(I.length<=1)return[];const j=[...I];j.splice(k,1);const v=j.reduce((x,E)=>x+E,0);return v>0?j.map(x=>x/v*100):[]}),r(0)},[s,p,c,r]),y=o.useCallback((k,I)=>{I.preventDefault();const j=m.current;if(!j)return;const v=I.clientX,x=j.offsetWidth,E=i.length===w?[...i]:di(w),L=T=>{const H=(T.clientX-v)/x*100,C=[...E];C[k]=Math.max(15,E[k]+H),C[k+1]=Math.max(15,E[k+1]-H),c(C)},M=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",M)},[i,w,c]),h=o.useCallback((k,I,j)=>{if(w>=4)return;const v=j==="left"?I:I+1;s(x=>{const E=Hr(x,p).assignments,L=new Map;for(const M of u){const T=E.get(M.tabKey)??0,B=T>=v?T+1:T;B>0&&L.set(M.tabKey,B)}return v>0&&L.set(k,v),L}),c(x=>{const E=x.length===w?[...x]:di(w),L=E[I]??100/w,M=Math.max(15,L/2),T=Math.max(15,L/2),B=[...E];B[I]=M,B.splice(v,0,T);const H=B.reduce((C,R)=>C+R,0);return B.map(C=>C/H*100)}),n(x=>{const E=li(x,v);return E[v]=k,E}),a(x=>{const E=li(x,v);return E[v]=[k],E}),r(v)},[w,s,p,u,c,n,a,r]);o.useEffect(()=>{Bf(e,g)||s(g)},[e,g,s]),o.useEffect(()=>{const{mapping:k,usedGroups:I}=f;n(j=>{const v=ci(j,k);return ii(j,v)?j:v}),a(j=>{const v=ci(j,k);return ii(j,v)?j:v}),r(j=>{const v=l?0:Wf(j,I,k);return j===v?j:v}),c(j=>{const v=l?[]:Hf(j,I,f.groupCount);return Of(j,v)?j:v})},[f,l,n,a,r,c]);const S=o.useMemo(()=>{const k=Array.from({length:w},()=>[]);for(const I of u){const j=g.get(I.tabKey)??0,v=Math.min(j,w-1);k[v].push(I)}return k},[u,g,w]),_=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:g,numGroups:w,isSplitMode:A,groupedConvs:S,moveTabToGroup:d,closeGroup:b,handleResizeStart:y,splitTabRelative:h,clearAllSplits:_}}function Uf({ides:e,sendDaemonCommand:s}){const r="0.8.86",n=o.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Gc(m,r)).sort((m,f)=>Number(dr(f,r))-Number(dr(m,r))),[r,e]),a=o.useMemo(()=>n.some(m=>dr(m,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async m=>{var f,g;u(w=>({...w,[m]:"upgrading"}));try{const w=await s(m,"daemon_upgrade",{});(f=w==null?void 0:w.result)!=null&&f.upgraded||(g=w==null?void 0:w.result)!=null&&g.success?u(A=>({...A,[m]:"done"})):u(A=>({...A,[m]:"error"}))}catch{u(w=>({...w,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const Na="adhdev_dashboard_notifications_v2",Ca="adhdev_dashboard_notifications_v1",Cr=80;function tn(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function uo(e){return{...e,createdAt:tn(e.createdAt),updatedAt:tn(e.updatedAt,e.createdAt),lastEventAt:tn(e.lastEventAt,e.updatedAt||e.createdAt)}}function zf(e){const s=Ba(e);return s==="unknown:"?e.id:s}function ui(e){return[e.type,ec(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Vf(e,s,r,n){var c;const a=Date.now(),i=[];for(const l of e){const u=l.sessionId?s.get(l.sessionId):void 0;if(u!=null&&u.surfaceHidden)continue;const p=ui({type:"task_complete",sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated}),m=!!((c=n==null?void 0:n.get(p))!=null&&c.forceUnread),f=wn(l,s,{notificationStateBySessionId:r}),g=f.inboxBucket==="needs_attention"?"needs_attention":f.inboxBucket==="task_complete"&&f.unread||(u==null?void 0:u.inboxBucket)==="task_complete"&&m?"task_complete":null;if(!g)continue;const w=tn(l.lastMessageAt||(u==null?void 0:u.lastUpdated)||l.lastUpdated,a),A=g==="task_complete"?p:ui({type:g,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated});i.push(uo({id:A,dedupKey:A,type:g,routeId:l.routeId,machineId:l.daemonId||l.routeId,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,title:hc(l),preview:mm(l),createdAt:w,updatedAt:w,lastEventAt:w}))}return i.sort((l,u)=>u.updatedAt-l.updatedAt)}function Gf(e,s=Cr){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=zf(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,s))}function qf(e){return e.filter(s=>typeof s.readAt=="number"||typeof s.deletedAt=="number").map(s=>({id:s.id,...typeof s.readAt=="number"?{readAt:s.readAt}:{},...typeof s.deletedAt=="number"?{deletedAt:s.deletedAt}:{}}))}function Yf(e){return new Map(e.map(s=>[s.id,s]))}function ol(e,s,r=Cr){const n=new Map;for(const i of s)n.set(i.id,i);const a=e.map(i=>{const c=uo(i),l=n.get(c.id);return{...c,...typeof(l==null?void 0:l.readAt)=="number"?{readAt:l.readAt}:{},...typeof(l==null?void 0:l.deletedAt)=="number"?{deletedAt:l.deletedAt}:{}}});return Gf(a,r)}function Xf(e,s,r=Cr){const n=new Set(ol(s,[],r).map(a=>a.id));return e.filter(a=>n.has(a.id)).slice(0,Math.max(0,r))}function Jf(e,s,r=Date.now()){const n=e.filter(a=>a.id!==s);return n.push({id:s,readAt:r}),n}function Qf(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,forceUnread:!0}),r}function Zf(e,s,r,n=Date.now()){const a=e.filter(i=>{const c=s.find(l=>l.id===i.id);return!c||!hr(c,r)});for(const i of s)hr(i,r)&&a.push({id:i.id,readAt:n});return a}function eh(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,deletedAt:Date.now()}),r}function th(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function sh(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=rs(r);if(n.length===0)continue;const a=r.readAt?0:1;for(const i of n){const c=s.get(i);if(!c){s.set(i,{unreadCount:a,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(i,{unreadCount:c.unreadCount+a,latestNotificationAt:Math.max(c.latestNotificationAt,r.updatedAt),latestRecordId:c.latestNotificationAt>=r.updatedAt?c.latestRecordId:r.id})}}return s}function rh(){if(typeof window>"u")return[];const e=s=>{if(!s||typeof s!="object")return null;const r=s;if(typeof r.id!="string"||r.id.length===0)return null;const n=typeof r.readAt=="number"&&Number.isFinite(r.readAt)?r.readAt:void 0,a=typeof r.deletedAt=="number"&&Number.isFinite(r.deletedAt)?r.deletedAt:void 0,i=r.forceUnread===!0;return typeof n!="number"&&typeof a!="number"&&!i?null:{id:r.id,...typeof n=="number"?{readAt:n}:{},...typeof a=="number"?{deletedAt:a}:{},...i?{forceUnread:!0}:{}}};try{const s=window.localStorage.getItem(Na),r=s?JSON.parse(s):[];if(Array.isArray(r))return r.map(e).filter(n=>!!n)}catch{}try{const s=window.localStorage.getItem(Ca),r=s?JSON.parse(s):[];return Array.isArray(r)?qf(r.map(n=>uo(n)).filter(n=>!n.deletedAt)):[]}catch{return[]}}function nh(e){if(!(typeof window>"u"))try{const s=e.filter(r=>typeof r.readAt=="number"||typeof r.deletedAt=="number"||r.forceUnread===!0).slice(0,Cr);if(s.length===0){window.localStorage.removeItem(Na),window.localStorage.removeItem(Ca);return}window.localStorage.setItem(Na,JSON.stringify(s)),window.localStorage.removeItem(Ca)}catch{}}function ah(e,s){return e===s?!0:e.length!==s.length?!1:e.every((r,n)=>{const a=s[n];return a?r.id===a.id&&r.readAt===a.readAt&&r.deletedAt===a.deletedAt&&r.forceUnread===a.forceUnread:!1})}function oh(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=Cr}=e,[a,i]=o.useState(()=>rh()),c=o.useMemo(()=>Yf(a),[a]),l=o.useMemo(()=>Vf(s,r,void 0,c),[s,r,c]),u=o.useMemo(()=>ol(l,a,n),[l,a,n]),p=o.useMemo(()=>sh(u),[u]);o.useEffect(()=>{i(d=>{const b=Xf(d,l,n);return ah(d,b)?d:b})},[l,n]),o.useEffect(()=>{nh(a)},[a]);const m=o.useMemo(()=>th(u),[u]),f=o.useCallback((d,b)=>{i(y=>Jf(y,d,b))},[]),g=o.useCallback(d=>{i(b=>Qf(b,d))},[]),w=o.useCallback((d,b)=>{i(y=>Zf(y,u,d,b))},[u]),A=o.useCallback(d=>{i(b=>eh(b,d))},[]);return{notifications:u,unreadCount:m,notificationStateBySessionId:p,markRead:f,markUnread:g,markTargetRead:w,deleteNotification:A}}function il(){return"select_session"}function ih(){return"open_panel"}function ch({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function lh(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function mi(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function pi(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function mo(e){return e instanceof Error?e.message:String(e||"")}function fi(e){const s=mo(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function hi(e,s){const r=mo(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function kn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useRef(!1),g=o.useRef(null);o.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const w=o.useCallback(async y=>{if(!s)return!1;const h=y.trim(),S=Ga(s);if(ch({hasMessage:!!h,blockedMessage:S,sendInFlight:f.current}))return S&&m(S),!1;const _=Date.now(),k={tabKey:s.tabKey,message:h,timestamp:_};if(lh(g.current,k))return m(null),!0;f.current=!0,u(!0),m(null),g.current=k;const I=`${_}-${Math.random().toString(36).slice(2,8)}`,j={role:"user",content:h,timestamp:_,_localId:I},v=!0;r(x=>({...x,[k.tabKey]:[...x[k.tabKey]||[],j]}));try{const x=gr(s);if(!x)return g.current=mi(g.current,k),v&&r(M=>({...M,[k.tabKey]:(M[k.tabKey]||[]).filter(T=>T._localId!==I)})),m("Unable to send message right now."),!1;const E=await e(x,"send_chat",{message:h,...Es(s)}),L=pi(E);if(v&&(L!=null&&L.deduplicated))return r(M=>({...M,[k.tabKey]:(M[k.tabKey]||[]).filter(T=>T._localId!==I)})),m(null),!0;if((L==null?void 0:L.sent)===!1)throw new Error((L==null?void 0:L.error)||"Send failed");if((L==null?void 0:L.success)===!1)throw new Error((L==null?void 0:L.error)||"Send failed");return setTimeout(()=>{const M=Date.now()-6e4;r(T=>{const B=T[k.tabKey];if(!B)return T;const H=B.filter(C=>C.timestamp>M);return H.length===B.length?T:{...T,[k.tabKey]:H}})},6e4),m(null),!0}catch(x){const E=mo(x);return E.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",E):console.warn("Send blocked/failed",x),g.current=mi(g.current,k),r(L=>({...L,[k.tabKey]:(L[k.tabKey]||[]).filter(M=>M._localId!==I)})),m(_m(x)),!1}finally{f.current=!1,u(!1)}},[s,e,n,r]),A=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(y){console.error("Relaunch failed",y)}},[s,e]),d=o.useCallback(async y=>{if(s)try{const S=(s.modalButtons||[]).indexOf(y),_=y.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_),I=gr(s);if(!I)return;const j=await e(I,"resolve_action",{button:y,action:k?"approve":"reject",...S>=0&&{buttonIndex:S},...Es(s)}),v=pi(j);v.success||n(x=>[...x,{routeId:s.tabKey,text:hi(y,v==null?void 0:v.error),timestamp:Date.now()}])}catch(h){fi(h)||console.error("[ModalButton] Error:",h),n(S=>[...S,{routeId:s.tabKey,text:fi(h)?hi(y,h):`❌ **${y}** error`,timestamp:Date.now()}])}},[s,e,n]),b=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,ih(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(y){console.error("Focus agent failed",y)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:p,isFocusingAgent:i,handleSendChat:w,handleRelaunch:A,handleModalButton:d,handleFocusAgent:b}}const po=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:d,isInputActive:b=!0}){const y=Qc(s),h=y.status||y.modalMessage||y.modalButtons?{...s,...y.status?{status:y.status}:{},...y.modalMessage!==void 0?{modalMessage:y.modalMessage}:{},...y.modalButtons!==void 0?{modalButtons:y.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(rc,{activeConv:h,onModalButton:c}),h.transport!=="pty"&&h.transport!=="acp"&&h.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[t.jsx("span",{className:"text-sm",children:t.jsx(ks,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,h.transport==="pty"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(np,{activeConv:h,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(va,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})})]}):t.jsx(va,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function dh({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:m,onOpenMachine:f,onOpenHistory:g,onOpenRemote:w,onHideConversation:A,onStopCli:d,cliViewMode:b,onSetCliViewMode:y,handleSendChat:h,handleFocusAgent:S,handleModalButton:_,handleRelaunch:k}){const I=o.useRef(null),j=tt(e)&&!s,v=j&&b==="terminal",x=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 ${x} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:t.jsx(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:lt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(wc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>m(e),onOpenMachine:()=>f(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&b&&t.jsx(Ya,{mode:b,onChange:y,compact:!0}),j&&d&&t.jsx("button",{onClick:()=>{d(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(At,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:t.jsx(Da,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:t.jsx(Rt,{size:14})}),A&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>A(e),type:"button",title:"Close chat",children:t.jsx(At,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(po,{activeConv:e,clearToken:0,isCliTerminal:v,ideEntry:n,terminalRef:I,handleModalButton:_,handleRelaunch:k,handleSendChat:h,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:S,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const Yn={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 uh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function cl(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(uh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Yn[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:Yn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Yn[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 ll({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Rt},{key:"chats",label:"Chats",icon:Zt}];return t.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:t.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:i})=>{const c=e===n;return t.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>s(n),type:"button","aria-pressed":c,children:[t.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:t.jsx(i,{size:15})}),t.jsx("span",{children:a})]},n)})})})}function Fr({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 Ms({children:e,className:s=""}){return t.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:e})}function sr({icon:e,title:s,subtitle:r,children:n}){return t.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[t.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Ur({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:p}=qs(e.conversation),m=lt(e.conversation),f=Cs(e.conversation),g=_c(e.conversation,{requiresAction:s==="needs_attention"}),w=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",A=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",d=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",S="text-[color:var(--status-warning)]";return t.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${w}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${A}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(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:sc(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:`${S} animate-pulse`,children:"Reconnecting…"})]}):p?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):g==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:S,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,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 xi({size:e=32,label:s}){return t.jsxs("div",{className:"flex flex-col items-center gap-2.5",children:[t.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}}),s&&t.jsx("div",{className:"text-xs font-semibold text-accent-primary-light tracking-tight",children:s})]})}function mh({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:p,onShowAllHidden:m,onOpenNewSession:f,onOpenMachine:g,onOpenSettings:w,onSectionChange:A,wsStatus:d="connected",isStandalone:b=!1}){const y=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",h=c.length>0,S=s.length>0||r.length>0||n.length>0||a.length>0,_=e==="machines"?"Machines":"Chats",k=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=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 ${k}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[t.jsx(yn,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:t.jsx(bn,{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] ${I}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:y?t.jsx(sr,{icon:t.jsx(xi,{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(sr,{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(cl,{})})}):t.jsx(Ms,{children:c.map((j,v)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>g(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(Fr,{title:"Needs attention",className:"mb-0"}),t.jsx(Ms,{children:s.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Ur,{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(Fr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(Ms,{children:r.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Ur,{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(Fr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(Ms,{children:n.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Ur,{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(Fr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(Ms,{children:a.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Ur,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):S?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?t.jsx(sr,{icon:t.jsx(xi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(sr,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Zt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(sr,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),t.jsx(Ms,{className:"bg-bg-secondary/25",children:i.map((j,v)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(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(lt(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:lt(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:Cs(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(ll,{section:e,onSectionChange:A})]})}function ph(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 dl(e){const s=[e.workspace||"Workspace unknown"],r=Ss(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=ph(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Sn(...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 fh(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=fh(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 hh(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 xh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Cn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=xh(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 In({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 g=hh(r),w=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(At,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||a||u(g)},disabled:!g||a,children:[t.jsx(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:A=>f(A.target.value),onKeyDown:A=>{A.key!=="Enter"||!w||a||(A.preventDefault(),u(w))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!w||a||u(w)},disabled:!w||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(A=>t.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(A.path),children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Bs,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:A.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:A.path})]})]},A.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(w||r),disabled:!w&&!r||a,children:c})]})]})})}function fo({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:g,modelValue:w,onModelChange:A,historyProviderNode:d,onConfirm:b,onCancel:y}){const h=n==null?void 0:n.find(S=>S.key===a);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":"Close launch confirmation",children:t.jsx(At,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:a||"",onChange:S=>i(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(S=>t.jsx("option",{value:S.key,children:S.label},S.key))}),(h==null?void 0:h.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),d,r.map(S=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:S.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:S.value})]},`${S.label}:${S.value}`)),g&&A&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:w||"",onChange:S=>A(S.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&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:S=>f(S.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,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(Ea,{size:14}),u?l:c]})]})]})})}function bi(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function vs(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?"⭐ ":""}${bi(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:bi(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 bh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function gh(e){return[bh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function yh(e){return e.lastLaunchedAt?vn(e.lastLaunchedAt):""}function ul(e){return{metaText:gh(e),updatedLabel:yh(e)}}function Xn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function vh({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var ze,xt,bt,ct;const c=Sr(),[l,u]=o.useState(!1),p=(((ze=e.detectedIdes)==null?void 0:ze.length)||0)>0,m=o.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),f=e.defaultWorkspaceId||null,[g,w]=o.useState(f||((xt=m[0])==null?void 0:xt.id)||""),[A,d]=o.useState(""),[b,y]=o.useState(""),[h,S]=o.useState([]),[_,k]=o.useState(!1),[I,j]=o.useState(""),[v,x]=o.useState(!1),[E,L]=o.useState(Xn(p,s.length,r.length)),M=o.useRef(null),[T,B]=o.useState(null),H=o.useRef("__home__"),[C,R]=o.useState("__home__"),[U,N]=o.useState(""),[D,Y]=o.useState(""),[q,W]=o.useState(""),[ae,ce]=o.useState([]),[Se,X]=o.useState(()=>jt().textQuery),[he,J]=o.useState(()=>jt().workspaceQuery),[Z,ue]=o.useState(()=>jt().modelQuery),[de,z]=o.useState(()=>jt().resumableOnly),[ye,ie]=o.useState(()=>jt().sortMode),[le,se]=o.useState(!1),[pe,ne]=o.useState(!1),ke=o.useRef(null),ve=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const K=g==="__custom__"?A.trim():((bt=m.find(Te=>Te.id===g))==null?void 0:bt.path)||"",V=g==="__custom__"&&!!K&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),we=g!=="__custom__"&&((ct=m.find(Te=>Te.id===g))==null?void 0:ct.path)||"",be=o.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),Q=o.useCallback(async Te=>{k(!0),j("");try{const Xe=await a(Te);y(Xe.path),d(Xe.path),S(Xe.directories)}catch(Xe){j(Xe instanceof Error?Xe.message:"Could not load folder")}finally{k(!1)}},[a]),Me=o.useCallback(()=>{var Xe;w("__custom__"),x(!0);const Te=Nn(e.platform,Sn(A.trim(),we,be,e.defaultWorkspacePath,(Xe=m.find(Fe=>Fe.id===f))==null?void 0:Xe.path,m.map(Fe=>Fe.path)));Q(Te)},[A,f,Q,be,we,e.platform,m]),Oe=o.useCallback(Te=>{if(Te!=null&&Te.workspaceId){w(Te.workspaceId),d("");return}if(Te!=null&&Te.workspacePath){w("__custom__"),d(Te.workspacePath);return}w(""),d("")},[]),Pe=o.useCallback(Te=>{if(w(Te),Te==="__custom__"){Me();return}d("")},[Me]),Ke=o.useCallback(Te=>{w("__custom__"),d(Te)},[]),Qe=o.useCallback((Te,Xe)=>{M.current=Xe,H.current=Te.selectedWorkspaceKey||"__home__",R(Te.selectedWorkspaceKey||"__home__"),N(Te.initialArgs||""),Y(Te.initialModel||""),W(""),ce([]);const Fe=Te.providerType?`${e.id}:${Te.providerType}`:null;if(cp(ve.current,Fe)){const Ue=jt();X(Ue.textQuery),J(Ue.workspaceQuery),ue(Ue.modelQuery),z(Ue.resumableOnly),ie(Ue.sortMode)}ve.current=Fe,B(Te),Te.providerType&&i&&(se(!0),i(Te.providerType).then(Ue=>ce(Ue||[])).catch(Ue=>console.warn("Failed to load saved sessions",Ue)).finally(()=>se(!1)))},[i,e.id]),Ge=o.useMemo(()=>Dc(ae,{textQuery:Se,workspaceQuery:he,modelQuery:Z,resumableOnly:de,sortMode:ye}),[Z,de,ae,ye,Se,he]);o.useEffect(()=>{q&&(Ge.some(Te=>Te.providerSessionId===q)||W(""))},[Ge,q]);const ut=o.useCallback(()=>{M.current&&(ne(!0),M.current().finally(()=>{M.current=null,ne(!1),B(null)}))},[]),it=o.useCallback(()=>{M.current=null,B(null)},[]),ht=o.useCallback(Te=>{H.current=Te,R(Te)},[]);return o.useEffect(()=>{var Te;ke.current!==e.id&&(ke.current=e.id,w(f||((Te=m[0])==null?void 0:Te.id)||"__custom__"),d(""),y(""),S([]),j(""),x(!1),X(jt().textQuery),J(jt().workspaceQuery),ue(jt().modelQuery),z(jt().resumableOnly),ie(jt().sortMode),ve.current=null,L(Xn(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,m]),o.useEffect(()=>{var Te;g!=="__custom__"&&(g&&m.some(Xe=>Xe.id===g)||w(f||((Te=m[0])==null?void 0:Te.id)||"__custom__"))},[f,g,m]),o.useEffect(()=>{E==="ide"&&p||E==="cli"&&s.length>0||E==="acp"&&r.length>0||L(Xn(p,s.length,r.length))},[E,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:f,workspaceChoice:g,customWorkspacePath:A,browseCurrentPath:b,browseDirectories:h,browseBusy:_,browseError:I,browseDialogOpen:v,activeLauncherKind:E,launchConfirm:T,launchConfirmWorkspaceKeyRef:H,launchConfirmWorkspaceKey:C,launchConfirmArgs:U,launchConfirmModel:D,launchConfirmResumeId:q,launchConfirmSavedSessions:ae,launchConfirmTextFilter:Se,launchConfirmWorkspaceFilter:he,launchConfirmModelFilter:Z,launchConfirmResumableOnly:de,launchConfirmSortMode:ye,filteredLaunchConfirmSavedSessions:Ge,launchConfirmSessionsLoading:le,launchConfirmBusy:pe,resolvedWorkspacePath:K,canCreateMissingWorkspace:V,openBrowseDialog:Me,loadBrowsePath:Q,handleWorkspaceChoiceChange:Pe,chooseCustomWorkspacePath:Ke,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:L,openLaunchConfirm:Qe,handleConfirmLaunch:ut,closeLaunchConfirm:it,setWorkspaceSelectionFromOption:Oe,setLaunchConfirmWorkspaceKeyAndSync:ht,setLaunchConfirmArgs:N,setLaunchConfirmModel:Y,setLaunchConfirmResumeId:W,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:J,setLaunchConfirmModelFilter:ue,setLaunchConfirmResumableOnly:z,setLaunchConfirmSortMode:ie}}function wh({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:g,onOpenConversation:w,onOpenRecent:A,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:y,onAddWorkspace:h,onBrowseDirectory:S,onLaunchWorkspaceProvider:_,onListSavedSessions:k}){const I=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",j=r.slice(0,4),v=s.slice(0,3),x=vh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:S,onListSavedSessions:k}),E=o.useMemo(()=>j.map(C=>{const{metaText:R,updatedLabel:U}=ul(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:R,updatedLabel:U,onClick:()=>{const{options:N,selectedKey:D}=vs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:C.workspace});x.openLaunchConfirm({title:C.kind==="ide"?xs("restart-ide",C.label):C.providerSessionId?Qa(C.label):xs("start-fresh",C.label),description:C.kind==="ide"?bs("restart-ide"):C.providerSessionId?Za():bs("start-fresh"),confirmLabel:C.kind==="ide"?Us("restart-ide"):C.providerSessionId?mn(!0):Us("start-fresh"),busyLabel:C.kind==="ide"?zs("restart-ide"):C.providerSessionId?Xa(!0):zs("start-fresh"),workspaceOptions:N,selectedWorkspaceKey:D,details:[{label:"Mode",value:I(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const Y=N.find(q=>q.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(Y),await A({...C,workspace:(Y==null?void 0:Y.workspacePath)??null})})}}}),[x,A,j]),L=o.useMemo(()=>v.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:lt(C.conversation),secondary:ep(C.conversation,{timestampLabel:C.timestamp?sc(C.timestamp):null}),unread:C.unread,onClick:()=>w(C.conversation)})),[w,v]),M=x.showAllRecent?E:E.slice(0,4),T=E.length>0,B=L.length>0,H=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${H} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick: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:_t(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[B&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.map(C=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),T&&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(C=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:C.primary}),C.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),E.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(C=>!C),children:x.showAllRecent?"Show fewer":`Show ${E.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:C=>x.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:x.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[x.workspaceRows.map(C=>t.jsxs("option",{value:C.id,children:[C.id===x.defaultWorkspaceId?"⭐ ":"",jn(C.path,C.label)||C.path]},C.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(Bs,{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(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:R,selectedKey:U}=vs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:R,selectedWorkspaceKey:U,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const N=R.find(D=>D.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(N),y(C.type,{workspacePath:(N==null?void 0:N.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(x.activeLauncherKind==="cli"?n:a).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const R=x.activeLauncherKind==="cli"?"cli":"acp",{options:U,selectedKey:N}=vs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${R.toUpperCase()}`,workspaceOptions:U,selectedWorkspaceKey:N,details:[{label:"Mode",value:R.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:R==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const D=U.find(Y=>Y.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),_(R,C.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:[C.icon?`${C.icon} `:"",C.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,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(In,{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:C=>{x.loadBrowsePath(C)},onConfirm:C=>{x.chooseCustomWorkspacePath(C),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx(fo,{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?mn(!!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:Ja()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:C=>x.setLaunchConfirmTextFilter(C.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmWorkspaceFilter,onChange:C=>x.setLaunchConfirmWorkspaceFilter(C.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmModelFilter,onChange:C=>x.setLaunchConfirmModelFilter(C.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsxs("select",{value:x.launchConfirmSortMode,onChange:C=>x.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled: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:C=>x.setLaunchConfirmResumableOnly(C.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:C=>x.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:up()}),x.filteredLaunchConfirmSavedSessions.map(C=>t.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.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 C=x.filteredLaunchConfirmSavedSessions.find(U=>U.providerSessionId===x.launchConfirmResumeId);if(!C)return null;const R=dl(C);return t.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:R.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:R.providerSessionId}),t.jsx("div",{className:"mt-1",children:R.metaLine}),R.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:R.updatedLabel}),R.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:R.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),m&&t.jsx(ll,{section:p,onSectionChange:g})]})}function ml(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 jh(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:Ss(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=xr(n)?"cli":Ps(n)?"acp":"ide",i=Ss(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(xr(n)?n.cliName||n.type:Ps(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ps(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 kh(e,s){const r=new Map;for(const n of s){const a=is(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,g)=>g.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ha(n),u=a.filter(f=>f.unread||f.requiresAction).length,p=ml(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:_t(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?tp(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 zr(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 Sh({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:g,onRequestedMobileSectionConsumed:w,setSelectedTabKey:A,setScreen:d,setSelectedMachineId:b,setSection:y,setMachineBackTarget:h,resetMachineAction:S,markNotificationTargetRead:_}){const k=o.useRef(null),I=o.useCallback(j=>{if(!(j!=null&&j.sessionId))return;const v=ln(j,c),x=Math.max(Date.now(),ps(j),v.lastUpdated||0);zr("mark_read:start",{tabKey:j.tabKey,sessionId:j.sessionId,displayPrimary:lt(j),inboxBucket:v.inboxBucket,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:ps(j),readAt:x}),_({sessionId:j.sessionId,providerSessionId:j.providerSessionId,tabKey:j.tabKey,routeId:j.routeId},x),l(is(j)||j.routeId,"mark_session_seen",{sessionId:j.sessionId,seenAt:x}).then(E=>{zr("mark_read:result",{tabKey:j.tabKey,sessionId:j.sessionId,result:E})}).catch(E=>{zr("mark_read:error",{tabKey:j.tabKey,sessionId:j.sessionId,error:E instanceof Error?E.message:String(E)})})},[c,l]);return o.useEffect(()=>{var v;if(!n){d("inbox"),A(((v=e[0])==null?void 0:v.tabKey)||null),k.current=null;return}if(i!=="chat"){k.current=null;return}const j=`${n.tabKey}:${n.sessionId||""}`;k.current!==j&&(k.current=j,I(n))},[e,I,i,n,d,A]),o.useEffect(()=>{if(!u)return;const j=e.find(v=>v.tabKey===u);j&&(A(j.tabKey),d("chat"),p==null||p())},[e,p,u,d,A]),o.useEffect(()=>{if(!m)return;const j=s.find(v=>v.id===m);j&&(b(j.id),S(),y("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,m,S,h,d,y,b]),o.useEffect(()=>{g&&(y(g),d("inbox"),w==null||w())},[w,g,d,y]),o.useEffect(()=>{const j=r.filter(v=>v.inboxBucket==="task_complete"||v.unread);j.length!==0&&zr("inbox_state",{screen:i,selectedTabKey:a,items:j.map(v=>{const x=ln(v.conversation,c);return{liveState:x,tabKey:v.conversation.tabKey,sessionId:v.conversation.sessionId,displayPrimary:lt(v.conversation),serverBucket:x.inboxBucket,computedBucket:v.inboxBucket,serverUnread:x.unread,computedUnread:v.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:ps(v.conversation)}})})},[r,c,i,a]),{markConversationRead:I}}function Nh(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function gi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ch(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Ih({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,S,_)=>{var k;try{i("loading"),l(`Launching ${S}…`);const I={ideType:S,enableCdp:!0};(k=_==null?void 0:_.workspacePath)!=null&&k.trim()&&(I.workspace=_.workspacePath.trim()),await e(h,"launch_ide",I),i("done"),l(`${S} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),g=o.useCallback(async(h,S,_)=>{if(S.trim())try{i("loading"),l(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const k=await e(h,"workspace_add",{path:S.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(k!=null&&k.success){i("done"),l(_!=null&&_.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((k==null?void 0:k.error)||"Could not save workspace")}catch(k){i("error"),l(k instanceof Error?k.message:"Could not save workspace")}},[e]),w=o.useCallback(async h=>{var S,_,k,I,j,v;try{i("loading"),l("Starting daemon upgrade…");const x=await e(h,"daemon_upgrade",{});if((S=x==null?void 0:x.result)!=null&&S.alreadyLatest){i("done"),l(`Already on v${((_=x==null?void 0:x.result)==null?void 0:_.version)||"latest"}.`);return}if((k=x==null?void 0:x.result)!=null&&k.upgraded||(I=x==null?void 0:x.result)!=null&&I.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(((v=x==null?void 0:x.result)==null?void 0:v.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),A=o.useCallback(async(h,S,_,k)=>{var v,x,E;const I=Date.now(),j={machineId:h,kind:S,providerType:_,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${_}…`),p(j);const L={cliType:_};(v=k==null?void 0:k.workspacePath)!=null&&v.trim()?L.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(L.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(L.resumeSessionId=k.resumeSessionId),(x=k==null?void 0:k.args)!=null&&x.trim()&&(L.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(E=k==null?void 0:k.model)!=null&&E.trim()&&(L.initialModel=k.model.trim());const M=await e(h,"launch_cli",L),T=(M==null?void 0:M.result)||M,B=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);if(M!=null&&M.success&&B){p(null),i("done"),l(`${_} launched`),s(as(B));return}if(M!=null&&M.success){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l((M==null?void 0:M.error)||(T==null?void 0:T.error)||`Could not launch ${S.toUpperCase()} workspace`)}catch(L){if(Ch(L)){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l(L instanceof Error?L.message:`Could not launch ${S.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(h,S)=>{try{const _=await e(h,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),k=(_==null?void 0:_.result)??_;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[e]),b=o.useCallback(async(h,S)=>Cn(e,h,S),[e]);o.useEffect(()=>{if(!u)return;const h=gi(u.workspacePath),S=r.find(k=>{var L,M,T,B;if(!k||k.type==="adhdev-daemon"||Nh(k.daemonId||k.id)!==u.machineId||(k.transport==="acp"?"acp":k.transport==="pty"?"cli":null)!==u.kind||String(k.agentType||k.type||"")!==u.providerType)return!1;const x=String(k.providerSessionId||"");if(u.resumeSessionId&&x)return x===u.resumeSessionId;if(h){const H=gi(k.workspace||k.runtimeWorkspaceLabel);return H?H===h:!1}return Number(k.lastUpdated||k._lastUpdate||k.timestamp||((B=(T=(M=(L=k.activeChat)==null?void 0:L.messages)==null?void 0:M.at)==null?void 0:T.call(M,-1))==null?void 0:B.timestamp)||0)>=u.startedAt-5e3});if(!S)return;const _=vc({entrySessionId:S.sessionId,entryInstanceId:S.instanceId,entryRouteId:S.id,conversations:n});_&&(p(null),i("done"),l(`${u.providerType} launched`),s(as(_)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{p(S=>!S||S.startedAt!==u.startedAt?S:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[u]);const y=o.useCallback(async(h,S)=>{if(S.kind==="ide"&&S.providerType){await f(h,S.providerType,{workspacePath:S.workspace||null});return}(S.kind==="cli"||S.kind==="acp")&&S.providerType&&await A(h,S.kind,S.providerType,{workspacePath:S.workspace||null,resumeSessionId:S.providerSessionId||null})},[f,A]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:A,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:y}}function Ah({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const m=o.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),f=o.useCallback(y=>{const h=e.find(S=>S.routeId===y.routeId&&S.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),g=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),w=o.useCallback((y,h="inbox")=>{l(y),a(),u("machines"),p(h),c("machine")},[a,p,c,u,l]),A=o.useCallback(y=>{const h=is(y);h&&w(h,"chat")},[w]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),b=o.useCallback(y=>{u(y),c("inbox")},[c,u]);return{openConversation:m,openNativeConversation:f,backFromConversation:g,openMachine:w,openConversationMachine:A,backFromMachine:d,changeMachineSection:b}}function Mh(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Vr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Th({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:g,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,onOpenHistory:d,onOpenRemote:b,onStopCli:y,wsStatus:h,isConnected:S,onShowHiddenConversation:_,onShowAllHiddenConversations:k,onHideConversation:I,onOpenNewSession:j,notificationStateBySessionId:v,liveSessionInboxState:x,onMarkNotificationTargetRead:E}){const[L,M]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[T,B]=o.useState(()=>e[0]?"chat":"inbox"),[H,C]=o.useState("chats"),[R,U]=o.useState(null),[N,D]=o.useState("inbox"),Y=Vs(),q="0.8.86",W=o.useMemo(()=>e.find(Q=>Q.tabKey===L)||e[0]||null,[e,L]),ae=o.useMemo(()=>W?r.find(Q=>Q.id===W.routeId):void 0,[r,W]),ce=o.useMemo(()=>!W||Ze(W)||!tt(W)?null:Hs(W),[W]),Se=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Wa),[r]),X=o.useMemo(()=>Se.find(Q=>Q.id===R)||null,[Se,R]),he=kn({sendDaemonCommand:a,activeConv:W||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),J=Ih({sendDaemonCommand:a,navigate:Y,ides:r,conversations:e}),Z=o.useMemo(()=>e.map(Q=>{const Me=T==="chat"&&(W==null?void 0:W.tabKey)===Q.tabKey,Oe=wn(Q,x,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Me,notificationStateBySessionId:v}),Pe=ps(Q),Ke=Lc(Q);return{conversation:Q,timestamp:Pe,preview:Ke,unread:Oe.unread,requiresAction:Oe.requiresAction,isWorking:Oe.isWorking,inboxBucket:Oe.inboxBucket}}),[e,x,v,T,W]),{markConversationRead:ue}=Sh({conversations:e,machineEntries:Se,items:Z,selectedConversation:W,selectedTabKey:L,screen:T,liveSessionInboxState:x,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:g,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,setSelectedTabKey:M,setScreen:B,setSelectedMachineId:U,setSection:C,setMachineBackTarget:D,resetMachineAction:J.resetMachineAction,markNotificationTargetRead:E}),de=Ah({conversations:e,selectedConversation:W,machineBackTarget:N,markConversationRead:ue,resetMachineAction:J.resetMachineAction,setSelectedTabKey:M,setScreen:B,setSelectedMachineId:U,setSection:C,setMachineBackTarget:D}),z=o.useMemo(()=>Vr(Z.filter(Q=>Q.requiresAction)),[Z]),ye=o.useMemo(()=>Vr(Z.filter(Q=>Q.unread&&!Q.requiresAction)),[Z]),ie=o.useMemo(()=>Vr(Z.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking)),[Z]),le=o.useMemo(()=>Vr(Z.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[Z]),se=o.useMemo(()=>X?Z.filter(Q=>is(Q.conversation)===X.id):[],[Z,X]),pe=o.useMemo(()=>jh(X,r),[r,X]),ne=(X==null?void 0:X.version)||null,ke=!!X&&!!ne&&!0&&ne!==q,ve=o.useMemo(()=>(X==null?void 0:X.availableProviders)||[],[X]),K=o.useMemo(()=>ve.filter(Q=>Q.category==="cli"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ve]),V=o.useMemo(()=>ve.filter(Q=>Q.category==="acp"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ve]),we=o.useMemo(()=>kh(Se,Z),[Z,Se]),be=o.useCallback(async Q=>{X&&await J.handleOpenRecent(X.id,Q)},[J,X]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:T==="chat"&&W?t.jsx(dh,{selectedConversation:W,isAcp:Ze(W),isStandalone:l,selectedIdeEntry:ae,actionLogs:n,userName:u,isSendingChat:he.isSendingChat,sendFeedbackMessage:he.sendFeedbackMessage,isFocusingAgent:he.isFocusingAgent,handleModalButton:he.handleModalButton,handleRelaunch:he.handleRelaunch,onBack:de.backFromConversation,onOpenNativeConversation:de.openNativeConversation,onOpenMachine:de.openConversationMachine,onHideConversation:I,onOpenHistory:d,onOpenRemote:b,onStopCli:y,cliViewMode:ce,onSetCliViewMode:async Q=>{if(W&&ce!==Q)try{await a(is(W)||W.routeId,"set_cli_view_mode",{targetSessionId:W.sessionId,cliType:Bt(W),mode:Q})}catch(Me){const Oe=co(Me);io(Me)?console.warn(Oe?"CLI view mode result was lost after send; keeping optimistic mobile mode override:":"Skipped CLI view mode switch:",Me instanceof Error?Me.message:String(Me)):console.error("Failed to switch CLI view mode:",Me)}},handleSendChat:he.handleSendChat,handleFocusAgent:he.handleFocusAgent}):T==="machine"&&X?t.jsx(wh,{selectedMachineEntry:X,selectedMachineConversations:se,selectedMachineRecentLaunches:pe,cliProviders:K,acpProviders:V,selectedMachineNeedsUpgrade:ke,appVersion:q,machineAction:J.machineAction,isStandalone:l,section:H,showBottomNav:N==="inbox",onBack:de.backFromMachine,onSectionChange:de.changeMachineSection,onOpenConversation:de.openConversation,onOpenRecent:be,onOpenMachineDetails:()=>Y(`/machines/${X.id}`),onMachineUpgrade:()=>J.handleMachineUpgrade(X.id),onLaunchDetectedIde:(Q,Me)=>J.handleLaunchDetectedIde(X.id,Q,Me),onAddWorkspace:(Q,Me)=>J.handleAddWorkspace(X.id,Q,Me),onBrowseDirectory:Q=>J.handleBrowseDirectory(X.id,Q),onLaunchWorkspaceProvider:(Q,Me,Oe)=>J.handleLaunchWorkspaceProvider(X.id,Q,Me,Oe),onListSavedSessions:Q=>J.handleListSavedSessions(X.id,Q)}):t.jsx(mh,{section:H,attentionItems:z,unreadItems:ye,workingItems:ie,completedItems:le,hiddenConversations:s,machineCards:we,getAvatarText:Mh,onOpenConversation:de.openConversation,onShowConversation:_,onShowAllHidden:k,onOpenNewSession:j,onOpenMachine:de.openMachine,onOpenSettings:()=>Y("/settings"),onSectionChange:C,wsStatus:h,isConnected:S,isStandalone:l})})}function Jn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Lh({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 g=o.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),w=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!Jn(s,r)){m("merge");return}const y=b.currentTarget.getBoundingClientRect(),h=b.clientX-y.left,S=y.width/3;h<S?m("split-left"):h>S*2?m("split-right"):m("merge")},[s,r]),A=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 y=b.dataTransfer.getData("text/tab-key"),h=y?e.some(_=>_.tabKey===y):!1,S=p;if(m(null),i(),!!y){if(b.preventDefault(),S==="split-left"&&Jn(s,r)){r==null||r(y,"split-left");return}if(S==="split-right"&&Jn(s,r)){r==null||r(y,"split-right");return}if(h){a(y);return}n==null||n(y)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:f,handleDragEnter:g,handleDragOver:w,handleDragLeave:A,handleDrop:d}}function _h(e,s){const r=new Set(s.map(i=>i.tabKey)),n=e.filter(i=>r.has(i)),a=s.filter(i=>!e.includes(i.tabKey)).map(i=>i.tabKey);return[...n,...a]}function Rh({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),g=o.useRef(null),w=o.useRef(n),A=o.useRef(a);o.useEffect(()=>{w.current=n},[n]),o.useEffect(()=>{A.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(j=>{const v=_h(j,e);return v.length===j.length&&v.every((x,E)=>x===j[E])?j:v})},[e]);const d=o.useMemo(()=>{const j=p??l;if(j.length===0)return e;const v=new Map(j.map((x,E)=>[x,E]));return[...e].sort((x,E)=>{const L=v.get(x.tabKey)??999,M=v.get(E.tabKey)??999;return L-M})},[e,p,l]);o.useEffect(()=>{var v,x;if(d.length===0){i!==null&&(c(null),(v=w.current)==null||v.call(w,null));return}if(i&&d.some(E=>E.tabKey===i))return;const j=d[0].tabKey;j!==i&&(c(j),(x=w.current)==null||x.call(w,j))},[d,i]);const b=o.useMemo(()=>d.find(j=>j.tabKey===i),[d,i]),y=o.useCallback(j=>{var v;c(j),(v=w.current)==null||v.call(w,j)},[]),h=o.useCallback((j,v,x)=>{u(E=>{var B;const L=E.filter(H=>H!==j),M=L.indexOf(v);if(M<0)return E;const T=x==="left"?M:M+1;return L.splice(T,0,j),(B=A.current)==null||B.call(A,L),L}),m(null)},[]),S=o.useCallback((j,v,x)=>{const L=(l.length>0?l:e.map(B=>B.tabKey)).filter(B=>B!==j),M=L.indexOf(v);if(M<0)return;const T=x==="left"?M:M+1;L.splice(T,0,j),f.current=L,m(L)},[l,e]),_=o.useCallback(()=>{var v;const j=f.current;j&&(u(j),(v=A.current)==null||v.call(A,j))},[]),k=o.useCallback(()=>{f.current=null,m(null)},[]),I=o.useCallback(j=>{u(v=>{var E;const x=v.filter(L=>L!==j);return x.push(j),(E=A.current)==null||E.call(A,x),x})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:f,draggingTabRef:g,selectTab:y,handleTabReorder:h,updatePreviewOrder:S,commitPreviewOrder:_,clearPreviewOrder:k,moveTabToEnd:I,setDraggingTabKey:j=>{g.current=j}}}function Ph({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 ho({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(cl,{}),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 pl="adhdev-tab-shortcuts";function fl(){try{return JSON.parse(localStorage.getItem(pl)||"{}")}catch{return{}}}function hl({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>fl()),[l,u]=o.useState(null),p=o.useCallback(f=>{const g=[];return f.metaKey&&g.push(a?"⌘":"Meta"),f.ctrlKey&&g.push("Ctrl"),f.altKey&&g.push(a?"⌥":"Alt"),f.shiftKey&&g.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(g.push(f.key.length===1?f.key.toUpperCase():f.key),g.join("+"))},[a]),m=o.useCallback(f=>{c(f);try{localStorage.setItem(pl,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){u(null);return}const w=p(g);if(!w)return;const A={...i};for(const[d,b]of Object.entries(A))b===w&&delete A[d];A[l]=w,m(A),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=g=>{if(!(!g.ctrlKey&&!g.metaKey&&!g.altKey)){for(const[w,A]of Object.entries(i))if(s.includes(w)&&p(g)===A){g.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:m}}const Dh=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:g,onCommitPreviewOrder:w,onClearPreviewOrder:A,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:h,longPressTimer:S,isGroupActive:_}){const k=qs(s),I=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",j=k.isReconnecting,v=o.useCallback(R=>{l.current=s.tabKey,b(s.tabKey),R.dataTransfer.setData("text/tab-key",s.tabKey),R.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),x=o.useCallback(()=>{l.current=null,b(null),w(),A(),d()},[l,b,w,A,d]),E=o.useCallback(R=>{const U=l.current;if(!(!U||U===s.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const N=R.currentTarget.getBoundingClientRect(),D=R.clientX<N.left+N.width/2?"left":"right";f(U,s.tabKey,D)}},[s.tabKey,l,f]),L=o.useCallback(R=>{R.preventDefault(),R.stopPropagation();const U=R.dataTransfer.getData("text/tab-key");if(U&&U!==s.tabKey){const N=R.currentTarget.getBoundingClientRect(),D=R.clientX<N.left+N.width/2?"left":"right";c.includes(U)?g(U,s.tabKey,D):y&&y(U)}A()},[s.tabKey,c,g,y,A]),M=o.useCallback(R=>{R.stopPropagation(),u(),p(s.tabKey),m(s)},[s,m,u,p]),T=o.useCallback(R=>{R.preventDefault(),h(R.clientX,R.clientY,s.tabKey)},[s.tabKey,h]),B=o.useCallback(R=>{const U=R.touches[0];S.current=setTimeout(()=>{h(U.clientX,U.clientY,s.tabKey)},600)},[s.tabKey,S,h]),H=o.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),C=["adhdev-dockview-tab",I,r&&"is-active",_&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:v,onDragEnd:x,onDragOver:E,onDrop:L,onClick:M,onContextMenu:T,onTouchStart:B,onTouchEnd:H,onTouchMove:H,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?t.jsx("div",{className:"tab-spinner"}):k.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.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:lt(s),children:lt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:hs(s)}):k.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[hs(s),t.jsx("span",{className:"connecting-dots"})]}):hs(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 Eh({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:g,onDragTabKeyChange:w,onReceiveTab:A,onHideTab:d,isGroupActive:b,allowTabShortcuts:y=!0}){const[h,S]=o.useState(null),_=o.useRef(null),k=o.useRef(null),I=o.useMemo(()=>e.map(T=>T.tabKey),[e]);wr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:j,tabShortcuts:v,shortcutListening:x,setShortcutListening:E,saveShortcuts:L}=hl({enabled:y,sortedTabKeys:e.map(T=>T.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const T=B=>{const H=document.querySelector("[data-pane-context-menu]");H&&H.contains(B.target)||S(null)};return window.addEventListener("mousedown",T,!0),()=>window.removeEventListener("mousedown",T,!0)},[h]),o.useEffect(()=>{const T=k.current;if(!T)return;const B=H=>{Math.abs(H.deltaY)<=Math.abs(H.deltaX)||(H.preventDefault(),T.scrollLeft+=H.deltaY)};return T.addEventListener("wheel",B,{passive:!1}),()=>T.removeEventListener("wheel",B)},[]);const M=o.useCallback((T,B,H)=>{S({x:T,y:B,tabKey:H})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(T=>t.jsx(Dh,{conv:T,isActive:s===T.tabKey,isDraggedTab:a.current===T.tabKey,isTaskCompleteUnread:n.has(T.tabKey),shortcut:y?v[T.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:g,onDragTabKeyChange:w,onReceiveTab:A,onOpenContextMenu:M,longPressTimer:_,isGroupActive:b},T.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:[y&&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:T=>{T.stopPropagation(),E(h.tabKey),S(null)},children:["⌨ ",v[h.tabKey]?`Change shortcut (${v[h.tabKey]})`:"Set shortcut"]}),v[h.tabKey]&&t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const T={...v};delete T[h.tabKey],L(T),S(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[y&&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),S(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&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:()=>E(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:T=>T.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 $h({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:g,numGroups:w,onMoveTab:A,onReceiveTab:d,style:b,onActiveTabChange:y,initialActiveTabId:h,initialTabOrder:S,onTabOrderChange:_,onHideTab:k,isFocused:I,allowTabShortcuts:j=!0,notificationStateBySessionId:v,liveSessionInboxState:x}){const{sendCommand:E}=Pt(),L=o.useRef(null),{activeTabId:M,activeConv:T,sortedConversations:B,draggingTabRef:H,selectTab:C,handleTabReorder:R,updatePreviewOrder:U,commitPreviewOrder:N,clearPreviewOrder:D,moveTabToEnd:Y,setDraggingTabKey:q}=Rh({conversations:e,initialActiveTabId:h,initialTabOrder:S,onActiveTabChange:y,onTabOrderChange:_}),W=kn({sendDaemonCommand:a,activeConv:T,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:ae,dropAction:ce,resetDragState:Se,handleDragEnter:X,handleDragOver:he,handleDragLeave:J,handleDrop:Z}=Lh({conversations:e,numGroups:w,onMoveTab:A,onReceiveTab:d,onOwnTabDrop:Y,onClearPreviewOrder:D}),ue=T&&!Ze(T)&&Hs(T)==="terminal",de=o.useMemo(()=>T?s.find(le=>le.id===T.routeId):void 0,[s,T]),z=o.useMemo(()=>T?n.filter(le=>le.routeId===T.tabKey):[],[n,T]),ye=o.useMemo(()=>new Set(B.filter(le=>wu(le,x,{isOpenConversation:le.tabKey===M,notificationStateBySessionId:v})).map(le=>le.tabKey)),[M,x,B]);wr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:M,dragOver:ae});const ie=o.useCallback(le=>{le.streamSource==="agent-stream"&&le.agentType&&E(le.routeId,il(),{agentType:le.agentType,...le.sessionId&&{targetSessionId:le.sessionId}}).catch(()=>{})},[E]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...b,outline:ae?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Eh,{conversations:B,activeTabId:M,groupIndex:m,numGroups:w,unreadTabKeys:ye,draggingTabRef:H,onFocus:f,onSelectTab:C,onConversationActivated:ie,onPreviewReorder:U,onReorderTab:R,onCommitPreviewOrder:N,onClearPreviewOrder:D,onDragStateReset:Se,onDragTabKeyChange:q,onMoveTab:A,onReceiveTab:d,onHideTab:k,isGroupActive:I??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:X,onDragOver:he,onDragLeave:J,onDrop:Z,children:[ae&&t.jsx(Ph,{dropAction:ce,canSplit:!!(w<4&&A)}),T?t.jsx(po,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!ue,ideEntry:de,terminalRef:L,handleModalButton:W.handleModalButton,handleRelaunch:W.handleRelaunch,handleSendChat:W.handleSendChat,isSendingChat:W.isSendingChat,sendFeedbackMessage:W.sendFeedbackMessage,handleFocusAgent:W.handleFocusAgent,isFocusingAgent:W.isFocusingAgent,actionLogs:z,userName:p,isInputActive:!g||!!I}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(ho,{conversationsCount:e.length,isSplitMode:g,isStandalone:l,hasRegisteredMachines:u})})]})]})}function Kh({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:g,userName:w,focusedGroup:A,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:y,closeGroup:h,handleResizeStart:S,groupActiveTabIds:_,setGroupActiveTabIds:k,groupTabOrders:I,setGroupTabOrders:j,toggleHiddenTab:v,allowTabShortcuts:x=!0,notificationStateBySessionId:E,liveSessionInboxState:L}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((M,T)=>{const B=s&&n.length===r?`${n[T]}%`:void 0;return t.jsxs(at.Fragment,{children:[s&&T>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:H=>S(T-1,H),onDoubleClick:()=>h(T),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx($h,{style:s?{flexBasis:B??`${100/r}%`,flexGrow:B?0:1,flexShrink:B?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:g,userName:w,groupIndex:T,isFocused:s&&A===T,onFocus:()=>d(T),isSplitMode:s,numGroups:r,onMoveTab:(H,C)=>{C==="left"&&T>0?b(H,T-1):C==="right"&&T<r-1?b(H,T+1):C==="split-left"&&r<4?y(H,T,"left"):C==="split-right"&&r<4&&y(H,T,"right")},onReceiveTab:H=>b(H,T),onActiveTabChange:H=>k(C=>(C[T]??null)===(H??null)?C:{...C,[T]:H}),initialActiveTabId:_[T],initialTabOrder:I[T],onTabOrderChange:H=>j(C=>{const R=C[T]||[];return R.length===H.length&&R.every((U,N)=>U===H[N])?C:{...C,[T]:H}}),onHideTab:v,allowTabShortcuts:x,notificationStateBySessionId:E,liveSessionInboxState:L})]},T)})})}function xl({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ft.onScreenshot("ide-page",(m,f)=>{if(m!==e)return;const g=new FileReader;g.onload=()=>i(g.result),g.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var m;return e?((m=ft.onStatus)==null?void 0:m.call(ft,(f,g)=>{f===e&&g!=null&&g.screenshotUsage&&l(g.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?ft.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?ft.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 bl="adhdev-dashboard-action-shortcuts",Bh=1200,Oh={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Wh(){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 gl(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 Ia(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function hn(e){const s=Object.fromEntries(gl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(bl)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Oh))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function yl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Hh({enabled:e=!0,onTrigger:s}){const r=Wh(),[n,a]=o.useState(()=>hn(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(yl(d.key)),b.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(bl,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=hn(r),b=Object.entries(n),y=Object.entries(d);b.length===y.length&&b.every(([h,S])=>d[h]===S)||f(d)},[n,r,f]);const g=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),w=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},Bh))},[]);o.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),u([]);return}const y=m(b);if(!y)return;const S=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(l.length===0&&S){u([y]);return}const k=[...l,y].slice(0,2).join(" "),I={...n};for(const[j,v]of Object.entries(I))v===k&&delete I[j];I[i]=k,f(I),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 y=m(b);if(!y)return;const h=b.metaKey||b.ctrlKey||b.altKey;if(Ia(b.target)&&!h)return;const S=p.current.parts,_=h?[y]:[...S.slice(-1),y].slice(-2),k=_.join(" "),I=_[_.length-1],j=Object.entries(n).filter(([,M])=>!!M),v=j.find(([,M])=>M===k);if(v){b.preventDefault(),g(),s(v[0]);return}if(j.some(([,M])=>M.startsWith(`${k} `))){b.preventDefault(),p.current.parts=_,w();return}const E=j.find(([,M])=>M===I);if(E){b.preventDefault(),g(),s(E[0]);return}if(j.some(([,M])=>M.startsWith(`${I} `))){b.preventDefault(),p.current.parts=[I],w();return}g()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,w,e,m,s,g,i]),o.useEffect(()=>()=>g(),[g]);const A=o.useMemo(()=>gl(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:f}}function Fh({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):s?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function Uh(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function yi({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Uh(n):!0}const vl=o.createContext(null);function An(){const e=o.useContext(vl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function sn(e){return lt(e)||e.tabKey}function zh(e){return`remote:${e}`}function ts(e){return e.startsWith("remote:")}function vi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Qn(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 Gr(e,s){e.classList.remove(ua.className,ma.className),e.classList.add(s==="light"?ua.className:ma.className)}function wi(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 Vh(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 Gh(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:sn(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 ji(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])ts(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!==sn(n)&&a.api.setTitle(sn(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:sn(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 ki(e,s,r){var u,p;const n=r?zh(r):null;for(const m of[...e.panels])ts(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Wt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=Pc(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=>!ts(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 qh({params:e,api:s}){var f;const r=An(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=kn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const g=[s.onDidActiveChange(w=>i(w.isActive)),s.onDidActiveGroupChange(w=>{if(!s.isActive&&!w.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const w of g)w.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(g=>g.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(g=>g.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(ho,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const m=!Ze(c)&&Hs(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(po,{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 Yh({params:e}){var u;const s=An(),r=o.useMemo(()=>Wt([...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}=xl({doId:a,targetSessionId:r?bc(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(Zi,{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 Xh(){const e=An();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(ho,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function Jh(e){var w,A;Vh(e);const s=An(),r=o.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Wt([...s.conversationsByTabKey.values()],e.params.routeId),b=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,y=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${y?" 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=((A=e.api.group.activePanel)==null?void 0:A.id)===e.api.id,i=e.api.isGroupActive,c=wn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,m=c.isWaiting,f=c.unread,g=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:lt(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:lt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:hs(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:hs(n)}):t.jsx("span",{children:hs(n)})})]}),g&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:g,children:g})]})}function Qh({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:g,registerActionHandlers:w,onActiveTabChange:A,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:y,scrollToBottomRequest:h,notificationStateBySessionId:S,liveSessionInboxState:_}){var Tt,ee,Re;const{theme:k}=so(),{sendCommand:I}=Pt(),j=o.useRef(null),v=o.useRef(null),x=o.useRef(!1),E=o.useRef(!1),L=o.useRef(!1),M=o.useRef(null),T=o.useRef([]),[B,H]=o.useState(null),[C,R]=o.useState(!1),[U,N]=o.useState(!1),[D,Y]=o.useState(0),q=o.useRef(null),W=o.useMemo(()=>sl(typeof window<"u"?window.innerWidth:1280),[]),ae=o.useRef(typeof window>"u"?{}:_f(W)),ce=o.useMemo(()=>new Map(e.map(P=>[P.tabKey,P])),[e]),Se=o.useMemo(()=>{const P=j.current;return P?P.groups.some(O=>{try{const F=O.model.location.type;return F!=="floating"&&F!=="popout"?!1:O.panels.some(G=>ce.has(G.id))}catch{return!1}}):!1},[ce,D,e]),X=o.useCallback(()=>{var P;(P=j.current)==null||P.focus()},[]),he=o.useCallback(P=>{const O=document,F=P.document;for(const Ae of O.querySelectorAll('link[rel="stylesheet"]')){const We=F.createElement("link");We.rel="stylesheet",We.href=Ae.href,Ae.crossOrigin&&(We.crossOrigin=Ae.crossOrigin),F.head.appendChild(We)}for(const Ae of O.querySelectorAll("style")){const We=F.createElement("style");We.textContent=Ae.textContent,F.head.appendChild(We)}const G=[];for(const Ae of O.styleSheets)try{for(const We of Ae.cssRules)We instanceof CSSStyleRule&&(We.selectorText===":root"||We.selectorText==="html")&&G.push(We.cssText)}catch{}if(G.length>0){const Ae=F.createElement("style");Ae.textContent=G.join(`
|
|
44
|
-
`),F.head.appendChild(Ae)}const oe=O.documentElement.getAttribute("data-theme");oe&&F.documentElement.setAttribute("data-theme",oe),F.documentElement.style.colorScheme=oe==="light"?"light":"dark",F.body.className=O.body.className;const Ie=O.documentElement.getAttribute("style");Ie&&F.documentElement.setAttribute("style",Ie);const _e=F.getElementById("dv-popout-window");_e instanceof HTMLElement&&(_e.classList.add("adhdev-dockview"),Gr(_e,k))},[k]),J=o.useCallback(()=>{var O;const P=j.current;if(P)for(const F of P.groups)try{const G=(O=F.element)==null?void 0:O.ownerDocument;if(!G||G===document)continue;const oe=G.getElementById("dv-popout-window");oe instanceof HTMLElement&&(oe.classList.add("adhdev-dockview"),Gr(oe,k));const Ie=document.documentElement.getAttribute("data-theme");Ie&&G.documentElement.setAttribute("data-theme",Ie),G.documentElement.style.colorScheme=Ie==="light"?"light":"dark",G.body.className=document.body.className;const _e=document.documentElement.getAttribute("style");_e?G.documentElement.setAttribute("style",_e):G.documentElement.removeAttribute("style")}catch{}},[k]),Z=o.useCallback(()=>{var O;const P=j.current;if(P)for(const F of P.groups)try{const G=(O=F.element)==null?void 0:O.ownerDocument;if(!G||G===document)continue;const oe=G.getElementById("dv-popout-window");if(!(oe instanceof HTMLElement))continue;oe.classList.add("adhdev-dockview"),Gr(oe,k),oe.classList.toggle("is-showing-dockview-overlay",U),oe.classList.toggle("is-dragging-dockview",C)}catch{}},[C,U,k]),ue=o.useCallback(P=>{const O=j.current;if(!O)return;const F=O.getPanel(P);F&&O.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:G})=>{he(G),ke();const oe=ce.get(P);G.document.title=oe?`${lt(oe)} — ADHDev`:"ADHDev — Popout"}})},[ce,he]),de=o.useCallback(P=>{const O=j.current,F=O==null?void 0:O.getPanel(P);if(!O||!F)return;const G=O.groups.filter(oe=>{var Ie;try{return((Ie=oe.element)==null?void 0:Ie.ownerDocument)===document}catch{return!0}});G.length>0?F.api.moveTo({group:G[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),z=o.useCallback(P=>{var G;const O=j.current;if(!O)return!1;const F=O.getPanel(P);if(!F)return!1;try{return((G=F.group.element)==null?void 0:G.ownerDocument)!==document}catch{return!1}},[]),ye=o.useCallback(P=>{z(P)&&de(P),f(P)},[z,de,f]),ie=o.useCallback(P=>{const O=j.current,F=O==null?void 0:O.getPanel(P);!O||!F||O.addFloatingGroup(F,{width:600,height:500})},[]),le=o.useCallback(P=>{var F;const O=(F=j.current)==null?void 0:F.getPanel(P);if(!O)return!1;try{return O.group.model.location.type==="floating"}catch{return!1}},[]),se=o.useCallback(()=>{var O,F;const P=(F=(O=j.current)==null?void 0:O.activePanel)==null?void 0:F.id;return!P||ts(P)?null:ce.has(P)?P:null},[ce]),pe=o.useCallback(P=>{const O=j.current,F=O==null?void 0:O.getPanel(P);if(!O||!F)return;const G=O.groups.filter(oe=>{try{return oe.model.location.type==="grid"}catch{return!0}});G.length>0?F.api.moveTo({group:G[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),ne=o.useCallback(()=>{var Ie;const P=j.current;if(!P)return;const F=P.groups.filter(_e=>{var Ae;try{return((Ae=_e.element)==null?void 0:Ae.ownerDocument)===document&&_e.model.location.type==="grid"}catch{return!1}})[0]||null,G=[...P.panels];for(const _e of G){const Ae=(Ie=_e.group.element)==null?void 0:Ie.ownerDocument,We=_e.group.model.location.type;Ae===document&&We==="grid"||(F&&F.id!==_e.group.id?_e.api.moveTo({group:F,position:"center"}):_e.api.moveTo({position:"center"}))}const oe=P.activePanel;oe&&(oe.group.model.openPanel(oe),oe.api.setActive()),Qn(document)},[]),ke=o.useCallback(()=>{var O,F;const P=j.current;if(P)for(const G of P.groups){const oe=(O=G.element)==null?void 0:O.ownerDocument;if(!oe||oe===document)continue;const Ie=oe.getElementById("dv-popout-window");if(!(Ie instanceof HTMLElement))continue;let _e=null,Ae=oe.title||"ADHDev",We="Popout workspace";const De=G.activePanel;if(De)if(_e=De.id,ts(De.id)){const je=((F=De.params)==null?void 0:F.routeId)||De.id.slice(7),Be=Wt([...ce.values()],je);Ae=
|
|
43
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>m(null)})]})}const Yp=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Xp(){const{preference:e,setPreference:s}=so();return t.jsx("div",{className:"flex gap-2",children:Yp.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 Jp(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 Qp(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Vn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function ri(e){const{r:s,g:r,b:n}=Qp(e);return .2126*Vn(s)+.7152*Vn(r)+.0722*Vn(n)}function ni(e,s){const r=ri(e),n=ri(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Yc(e){const s=Jp(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return ni(s,r)>=ni(s,n)?r:n}const ja={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},ka={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},Zp=[{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"}}}],Xc="adhdev-chat-theme",Jc="adhdev-chat-theme-custom";function en(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Xc)||"ember"}catch{return"ember"}}function Ot(e){try{const s=localStorage.getItem(Jc);if(s){const r=JSON.parse(s);return{...e==="dark"?ja:ka,...r[e]}}}catch{}return e==="dark"?ja:ka}function Or(e,s){try{localStorage.setItem(Jc,JSON.stringify({dark:e,light:s}))}catch{}}function $t(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 fn(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 ef={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ur(e,s){var a;const r=(a=ef[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",fn(r,24)),n.style.setProperty("--accent-on-primary",Yc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${fn(r,18)})`),n.style.setProperty("--border-accent",$t(r,.35)),n.style.setProperty("--nav-active-bg",$t(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${$t(r,.06)}`)}function gs(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",$t(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",$t(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",$t(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",$t(e.borderSubtle,.5)),s.style.setProperty("--border-default",$t(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",fn(e.accentColor,30)),s.style.setProperty("--accent-on-primary",Yc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${fn(e.accentColor,40)})`),s.style.setProperty("--border-accent",$t(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",$t(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${$t(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 ${$t(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 ro(){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 tf(e){try{localStorage.setItem(Xc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ys()?"dark":"light";gs(Ot(s))}else ro(),ur(e,ys()?"dark":"light")}function sf(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=en();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ys()?"dark":"light";gs(Ot(s))}else ro(),ur(e,ys()?"dark":"light")}function ys(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Nt({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function er({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function rf({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Ot(r));o.useEffect(()=>{a(Ot(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const p={...u,[c]:l},f=Ot(r==="dark"?"light":"dark");return r==="dark"?Or(p,f):Or(f,p),gs(p),s(p),p})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(er,{title:"App Background",children:[t.jsx(Nt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(Nt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(Nt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(er,{title:"App Text",children:[t.jsx(Nt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(Nt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(Nt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(er,{title:"Borders & Accent",children:[t.jsx(Nt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(Nt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(Nt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(er,{title:"Chat Bubbles",children:[t.jsx(Nt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(Nt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(Nt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(Nt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(er,{title:"Chat Layout",children:[t.jsx(Nt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(Nt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(Nt,{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?ja:ka,u=Ot(e?"light":"dark");e?Or(c,u):Or(u,c),a(c),gs(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 nf(){const[e,s]=o.useState(en),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Ot("dark"));o.useEffect(()=>{n(ys());const u=new MutationObserver(()=>{const f=ys();n(f);const g=en();g==="custom"?gs(Ot(f?"dark":"light")):ur(g,f?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=ys();n(f);const g=en();g==="custom"?gs(Ot(f?"dark":"light")):ur(g,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"?gs(Ot(r?"dark":"light")):(ro(),ur(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Ot(r?"dark":"light"))},[r]);const c=u=>{s(u),tf(u)},l=[...Zp,{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(rf,{dark:r,onColorsChange:u=>i(u)})]})}const no="adhdev_mobileDashboardMode_v1",Sa="adhdev:mobile-dashboard-mode-change";function ao(){try{return localStorage.getItem(no)==="workspace"?"workspace":"chat"}catch{return"chat"}}function af(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??ao())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==no||s()};return window.addEventListener(Sa,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Sa,r),window.removeEventListener("storage",n)}}function of(e){try{localStorage.setItem(no,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Sa,{detail:e}))}function cf(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(ao()==="chat")},[]),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Zt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{s(r),of(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function lf(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 df(e,s){const{sendData:r}=Pt(),{injectEntries:n,getIdes:a}=cn(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>os.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const m=a().find(g=>g.id===u),f=lf(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])}function Qc(e,s){const{sendData:r}=Pt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=os.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},p=>{l&&(clearTimeout(l),l=null),a(p.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Mm):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 uf(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Zc(e){const{sendData:s}=Pt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=uf(e);if(!a||!e.sessionId||!s){n({});return}const i=os.subscribe({sendData:s},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Ks.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 el="adhdev_hiddenTabs";function mf(){try{const e=localStorage.getItem(el);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function As(e){try{localStorage.setItem(el,JSON.stringify([...e]))}catch{}}function Wr(e){return Ba(e)}function oo(e,s){return rs(s).some(r=>e.has(r))}function pf(){const[e,s]=o.useState(mf),r=o.useCallback(p=>{s(m=>{const f=new Set(m);return f.has(p)?f.delete(p):f.add(p),As(f),f})},[]),n=o.useCallback(p=>{s(m=>{if(m.has(p))return m;const f=new Set(m);return f.add(p),As(f),f})},[]),a=o.useCallback(p=>{s(m=>{if(!m.has(p))return m;const f=new Set(m);return f.delete(p),As(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return As(m),m})},[]),c=o.useCallback((p,m)=>{s(f=>{const g=new Set(f);for(const w of m)g.add(w);return As(g),g})},[]),l=o.useCallback((p,m)=>{s(f=>{const g=new Set(f);for(const w of m)g.delete(w);return As(g),g})},[]),u=o.useCallback(p=>oo(e,p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function tl(e){return e instanceof Error?e.message:String(e||"")}function io(e){const s=tl(e);return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("P2P channel not open")||s.includes("P2P not available")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function co(e){const s=tl(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function ai(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 ff(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=ai(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>ai(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function sl(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 hf(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))sl(s,a)===i&&(delete n[a],r=!0);return r?n:e}function xf({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{uc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:Pc(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return Uu(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 bf(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 Gn(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 gf(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 oi(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?gf(Os(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 yf(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||""),oi(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),oi(r.activeChat)].join(":"))].join("|")}function vf(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 wf(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 jf(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 kf(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of rs({routeId:n.routeId}))r.set(i,a);for(const i of rs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of rs({tabKey:n.tabKey}))r.set(i,n)}return r}function Sf(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Nf(e){const s=Sf(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=Os(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Cf({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>bf(e),[e]),c=o.useMemo(()=>Oc(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),m=o.useRef(new Map),f=o.useRef(new Map),g=o.useMemo(()=>{const k=new Map,I=[];for(const E of i){const{connectionState:L="new",machineName:M}=Wc(E,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),T=wf(E,r),B=yf(E),H=m.current.get(E.id);if(H&&H.ide===E&&H.sourceSignature===B&&H.connectionState===L&&H.machineName===M&&jf(H.localRefs,T)){k.set(E.id,H),I.push(...H.conversations);continue}const C=to(E,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),R={ide:E,sourceSignature:B,connectionState:L,machineName:M,localRefs:T,conversations:C};k.set(E.id,R),I.push(...C)}m.current=k;const j=new Map,v=E=>{const L=Nf(E),M=f.current.get(E.tabKey);if(M&&M.signature===L)return j.set(E.tabKey,M),M.timestamp;const T={signature:L,timestamp:yc(E)||(M==null?void 0:M.timestamp)||0};return j.set(E.tabKey,T),T.timestamp},x=[...I].sort((E,L)=>vc(E,L,v));return f.current=j,x},[i,r,s,c]),w=o.useMemo(()=>{const k=vf(g,n);return Gn(l.current,k)?l.current:(l.current=k,k)},[g,n]),A=o.useMemo(()=>{const k=new Map,I=Array.from(new Set(w.map(j=>j.routeId)));for(const j of I){const v=Wt(w,j);v&&k.set(j,v)}return k},[w]),d=o.useMemo(()=>{const k=new Map;for(const I of w){const j=A.get(I.routeId),v=I.streamSource==="native"&&j?j:I;for(const x of rs({providerSessionId:I.providerSessionId,sessionId:I.sessionId}))k.set(x,v)}return k},[w,A]),b=o.useMemo(()=>kf(w,A),[w,A]),y=o.useCallback(k=>{if(k)return d.get(k)},[d]),h=o.useCallback(k=>{if(k)return b.get(k)},[b]),S=o.useMemo(()=>{const k=w.filter(I=>!oo(a,I));return Gn(u.current,k)?u.current:(u.current=k,k)},[w,a]),_=o.useMemo(()=>{const k=S.map(I=>I.tabKey);return Gn(p.current,k)?p.current:(p.current=k,k)},[S]);return{chatIdes:i,conversations:w,visibleConversations:S,visibleTabKeys:_,resolveConversationBySessionId:y,resolveConversationByTarget:h}}function If({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 Af({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{st.setIdes(e)},[e]),o.useEffect(()=>{st.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=st.onToast(u=>{r(m=>m.some(g=>g.message===u.message&&u.timestamp-g.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=st.onSystemMessage((u,p)=>{var w,A;const m=a(u),f=(w=p._localId)==null?void 0:w.startsWith("sys_approval_"),g=!!(m&&(m.status==="waiting_approval"||(A=m.modalButtons)!=null&&A.length||m.modalMessage));f&&g||n(d=>({...d,[u]:[...d[u]||[],p]}))}),l=st.onClearSystemMessage((u,p)=>{n(m=>{var f;return(f=m[u])!=null&&f.length?{...m,[u]:m[u].filter(g=>{var w;return!(g.role==="system"&&((w=g._localId)!=null&&w.startsWith(p)))})}:m})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=Tc.on("status_event",c=>{st.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 g=Number(u.buttonIndex),w=u.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[g])||"Approve",A=String(w).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A);s(f,"resolve_action",{action:d?"approve":"reject",button:w,...Number.isFinite(g)&&{buttonIndex:g},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};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 Mf="adhdev_dashboardLayout_v1",Tf="adhdev_dashboardDockview_v1",Lf="adhdev_dashboardDockviewHiddenRestore_v1",tr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function lo(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function rl(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function nl(e){return`${Mf}:${e}`}function _f(e){const s=nl(e);return lo(s,null)}function Rf(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=nl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function al(e){return`${Tf}:${e}`}function Pf(e){const s=al(e);return lo(s,null)}function Df(e,s){try{const r=al(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function ol(e){return`${Lf}:${e}`}function Ef(e){const s=ol(e);return lo(s,{})}function $f(e,s){try{const r=ol(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Kf(){return{groupAssignments:[...tr.groupAssignments],focusedGroup:tr.focusedGroup,groupActiveTabIds:{...tr.groupActiveTabIds},groupTabOrders:{...tr.groupTabOrders},groupSizes:[...tr.groupSizes]}}function Bf(){const[e]=o.useState(()=>rl(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,g]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,A]=o.useState(!1),d=o.useCallback(()=>{if(w)return;const b=_f(e)??Kf();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),m(b.groupSizes),A(!0)},[w,e]);return o.useEffect(()=>{w&&Rf(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[w,e,s,n,i,l,p]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),y=h=>g(h.matches);return b.addEventListener("change",y),()=>b.removeEventListener("change",y)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:p,setGroupSizes:m,isMobile:f,hasHydratedStoredLayout:w,hydrateStoredLayout:d}}function Of(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Ka(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Wf({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:g,handleRefreshHistory:w}){const A=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),y=o.useRef(!1);o.useEffect(()=>{if(!e||A.current||s.length===0)return;if(!a){i();return}const h=r(e);if(!h)return;const S=n.get(h.tabKey)??0;c(_=>({..._,[S]:h.tabKey})),l(S),A.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),u(_=>{const k=new URLSearchParams(_);return k.delete("activeTab"),k},{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(A.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){y.current=!1;return}if(!m||y.current||f)return;const h=g.find(S=>S.id===m.routeId);h&&(!h.chats||h.chats.length===0||Of(h.chats,m))&&(y.current=!0,w())},[p,m,f,g,w]),o.useEffect(()=>{if(!m)return;let h=null,S=0,_=-1,k=0;const I=()=>{h=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(j.length===0){S<18&&(S+=1,h=requestAnimationFrame(I));return}let v=0;for(const x of j)x.scrollTop=x.scrollHeight,v+=x.scrollHeight;v===_?k+=1:(k=0,_=v),S+=1,!(k>=2||S>=18)&&(h=requestAnimationFrame(I))};return h=requestAnimationFrame(I),()=>{h!=null&&cancelAnimationFrame(h)}},[m==null?void 0:m.tabKey])}function Hf({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),g=o.useMemo(()=>{if(e||!n)return null;const y=l(n);return y&&!tt(y)&&!Ze(y)?y:null},[e,n,l]),w=o.useMemo(()=>{const y=u==null?void 0:u.routeId;if(!y)return null;const h=u!=null&&u.tabKey?i.find(S=>S.tabKey===u.tabKey):a?i.find(S=>S.tabKey===a):null;return(h==null?void 0:h.routeId)===y?h:Wt(i,y)},[i,u,a]),A=o.useMemo(()=>{if(w)return c.find(y=>y.id===w.routeId)},[c,w]);o.useEffect(()=>{g&&(p({routeId:g.routeId,tabKey:Uo(g)}),f(g),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,g]);const d=o.useCallback(y=>{y&&(p({routeId:y.routeId,tabKey:Uo(y)}),f(y))},[]),b=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:A,remoteDialogActiveConv:m,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:b}}function qn(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=Ka(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function ii({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]),g=o.useCallback(async(d,b)=>{try{const y=d||(s==null?void 0:s.daemonId)||"",h=await e(y,"switch_chat",{id:b,sessionId:b,...Es(s)}),S=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||S==="switched"||S==="switched-by-title")return;S===!1||S==="not_found"?Zs(a,"⚠️ Session tab not found — try refreshing history"):typeof S=="string"&&S.startsWith("error:")?Zs(a,`⚠️ Switch error: ${S}`):Zs(a,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),Zs(a,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,e,a]),w=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const d=gr(s);await e(d,"new_chat",{...Es(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]),A=o.useCallback(async()=>{var d,b;if(!(!s||p)){m(!0);try{const y=gr(s),h=async()=>e(y,"list_chats",{forceExpand:!0,...Es(s)});let S=await h(),_=(S==null?void 0:S.chats)||((d=S==null?void 0:S.result)==null?void 0:d.chats);qn(_,s)&&(await new Promise(k=>setTimeout(k,450)),S=await h(),_=(S==null?void 0:S.chats)||((b=S==null?void 0:S.result)==null?void 0:b.chats)),S!=null&&S.success&&Array.isArray(_)&&(n(s.routeId,_),qn(_,s)&&!qn(r,s)&&Zs(a,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{m(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:f,handleSwitchSession:g,handleNewChat:w,handleRefreshHistory:A}}function Ff(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 Uf(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function ci(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 Hr(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 li(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 zf(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 Vf(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 di(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 ui(e){return Array(e).fill(100/e)}function Gf({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(()=>Hr(e,p),[e,p]),g=f.assignments,w=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),A=w>1,d=o.useCallback((k,I)=>{s(j=>{const v=new Map(Hr(j,p).assignments);return I===0?v.delete(k):v.set(k,I),v}),n(j=>({...j,[I]:k})),r(I)},[s,p,n,r]),b=o.useCallback(k=>{s(I=>{const j=Hr(I,p).assignments,v=new Map;for(const[x,E]of j)E!==k&&(E>k?v.set(x,E-1):v.set(x,E));return v}),c(I=>{if(I.length<=1)return[];const j=[...I];j.splice(k,1);const v=j.reduce((x,E)=>x+E,0);return v>0?j.map(x=>x/v*100):[]}),r(0)},[s,p,c,r]),y=o.useCallback((k,I)=>{I.preventDefault();const j=m.current;if(!j)return;const v=I.clientX,x=j.offsetWidth,E=i.length===w?[...i]:ui(w),L=T=>{const H=(T.clientX-v)/x*100,C=[...E];C[k]=Math.max(15,E[k]+H),C[k+1]=Math.max(15,E[k+1]-H),c(C)},M=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",M),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",M)},[i,w,c]),h=o.useCallback((k,I,j)=>{if(w>=4)return;const v=j==="left"?I:I+1;s(x=>{const E=Hr(x,p).assignments,L=new Map;for(const M of u){const T=E.get(M.tabKey)??0,B=T>=v?T+1:T;B>0&&L.set(M.tabKey,B)}return v>0&&L.set(k,v),L}),c(x=>{const E=x.length===w?[...x]:ui(w),L=E[I]??100/w,M=Math.max(15,L/2),T=Math.max(15,L/2),B=[...E];B[I]=M,B.splice(v,0,T);const H=B.reduce((C,R)=>C+R,0);return B.map(C=>C/H*100)}),n(x=>{const E=di(x,v);return E[v]=k,E}),a(x=>{const E=di(x,v);return E[v]=[k],E}),r(v)},[w,s,p,u,c,n,a,r]);o.useEffect(()=>{Ff(e,g)||s(g)},[e,g,s]),o.useEffect(()=>{const{mapping:k,usedGroups:I}=f;n(j=>{const v=li(j,k);return ci(j,v)?j:v}),a(j=>{const v=li(j,k);return ci(j,v)?j:v}),r(j=>{const v=l?0:zf(j,I,k);return j===v?j:v}),c(j=>{const v=l?[]:Vf(j,I,f.groupCount);return Uf(j,v)?j:v})},[f,l,n,a,r,c]);const S=o.useMemo(()=>{const k=Array.from({length:w},()=>[]);for(const I of u){const j=g.get(I.tabKey)??0,v=Math.min(j,w-1);k[v].push(I)}return k},[u,g,w]),_=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:g,numGroups:w,isSplitMode:A,groupedConvs:S,moveTabToGroup:d,closeGroup:b,handleResizeStart:y,splitTabRelative:h,clearAllSplits:_}}function qf({ides:e,sendDaemonCommand:s}){const r="0.8.88",n=o.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:qc(m,r)).sort((m,f)=>Number(dr(f,r))-Number(dr(m,r))),[r,e]),a=o.useMemo(()=>n.some(m=>dr(m,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async m=>{var f,g;u(w=>({...w,[m]:"upgrading"}));try{const w=await s(m,"daemon_upgrade",{});(f=w==null?void 0:w.result)!=null&&f.upgraded||(g=w==null?void 0:w.result)!=null&&g.success?u(A=>({...A,[m]:"done"})):u(A=>({...A,[m]:"error"}))}catch{u(w=>({...w,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const Na="adhdev_dashboard_notifications_v2",Ca="adhdev_dashboard_notifications_v1",Cr=80;function tn(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function uo(e){return{...e,createdAt:tn(e.createdAt),updatedAt:tn(e.updatedAt,e.createdAt),lastEventAt:tn(e.lastEventAt,e.updatedAt||e.createdAt)}}function Yf(e){const s=Ba(e);return s==="unknown:"?e.id:s}function mi(e){return[e.type,tc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Xf(e,s,r,n){var c;const a=Date.now(),i=[];for(const l of e){const u=l.sessionId?s.get(l.sessionId):void 0;if(u!=null&&u.surfaceHidden)continue;const p=mi({type:"task_complete",sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated}),m=!!((c=n==null?void 0:n.get(p))!=null&&c.forceUnread),f=wn(l,s,{notificationStateBySessionId:r}),g=f.inboxBucket==="needs_attention"?"needs_attention":f.inboxBucket==="task_complete"&&f.unread||(u==null?void 0:u.inboxBucket)==="task_complete"&&m?"task_complete":null;if(!g)continue;const w=tn(l.lastMessageAt||(u==null?void 0:u.lastUpdated)||l.lastUpdated,a),A=g==="task_complete"?p:mi({type:g,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated});i.push(uo({id:A,dedupKey:A,type:g,routeId:l.routeId,machineId:l.daemonId||l.routeId,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,title:xc(l),preview:pm(l),createdAt:w,updatedAt:w,lastEventAt:w}))}return i.sort((l,u)=>u.updatedAt-l.updatedAt)}function Jf(e,s=Cr){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Yf(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,s))}function Qf(e){return e.filter(s=>typeof s.readAt=="number"||typeof s.deletedAt=="number").map(s=>({id:s.id,...typeof s.readAt=="number"?{readAt:s.readAt}:{},...typeof s.deletedAt=="number"?{deletedAt:s.deletedAt}:{}}))}function Zf(e){return new Map(e.map(s=>[s.id,s]))}function il(e,s,r=Cr){const n=new Map;for(const i of s)n.set(i.id,i);const a=e.map(i=>{const c=uo(i),l=n.get(c.id);return{...c,...typeof(l==null?void 0:l.readAt)=="number"?{readAt:l.readAt}:{},...typeof(l==null?void 0:l.deletedAt)=="number"?{deletedAt:l.deletedAt}:{}}});return Jf(a,r)}function eh(e,s,r=Cr){const n=new Set(il(s,[],r).map(a=>a.id));return e.filter(a=>n.has(a.id)).slice(0,Math.max(0,r))}function th(e,s,r=Date.now()){const n=e.filter(a=>a.id!==s);return n.push({id:s,readAt:r}),n}function sh(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,forceUnread:!0}),r}function rh(e,s,r,n=Date.now()){const a=e.filter(i=>{const c=s.find(l=>l.id===i.id);return!c||!hr(c,r)});for(const i of s)hr(i,r)&&a.push({id:i.id,readAt:n});return a}function nh(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,deletedAt:Date.now()}),r}function ah(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function oh(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=rs(r);if(n.length===0)continue;const a=r.readAt?0:1;for(const i of n){const c=s.get(i);if(!c){s.set(i,{unreadCount:a,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(i,{unreadCount:c.unreadCount+a,latestNotificationAt:Math.max(c.latestNotificationAt,r.updatedAt),latestRecordId:c.latestNotificationAt>=r.updatedAt?c.latestRecordId:r.id})}}return s}function ih(){if(typeof window>"u")return[];const e=s=>{if(!s||typeof s!="object")return null;const r=s;if(typeof r.id!="string"||r.id.length===0)return null;const n=typeof r.readAt=="number"&&Number.isFinite(r.readAt)?r.readAt:void 0,a=typeof r.deletedAt=="number"&&Number.isFinite(r.deletedAt)?r.deletedAt:void 0,i=r.forceUnread===!0;return typeof n!="number"&&typeof a!="number"&&!i?null:{id:r.id,...typeof n=="number"?{readAt:n}:{},...typeof a=="number"?{deletedAt:a}:{},...i?{forceUnread:!0}:{}}};try{const s=window.localStorage.getItem(Na),r=s?JSON.parse(s):[];if(Array.isArray(r))return r.map(e).filter(n=>!!n)}catch{}try{const s=window.localStorage.getItem(Ca),r=s?JSON.parse(s):[];return Array.isArray(r)?Qf(r.map(n=>uo(n)).filter(n=>!n.deletedAt)):[]}catch{return[]}}function ch(e){if(!(typeof window>"u"))try{const s=e.filter(r=>typeof r.readAt=="number"||typeof r.deletedAt=="number"||r.forceUnread===!0).slice(0,Cr);if(s.length===0){window.localStorage.removeItem(Na),window.localStorage.removeItem(Ca);return}window.localStorage.setItem(Na,JSON.stringify(s)),window.localStorage.removeItem(Ca)}catch{}}function lh(e,s){return e===s?!0:e.length!==s.length?!1:e.every((r,n)=>{const a=s[n];return a?r.id===a.id&&r.readAt===a.readAt&&r.deletedAt===a.deletedAt&&r.forceUnread===a.forceUnread:!1})}function dh(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=Cr}=e,[a,i]=o.useState(()=>ih()),c=o.useMemo(()=>Zf(a),[a]),l=o.useMemo(()=>Xf(s,r,void 0,c),[s,r,c]),u=o.useMemo(()=>il(l,a,n),[l,a,n]),p=o.useMemo(()=>oh(u),[u]);o.useEffect(()=>{i(d=>{const b=eh(d,l,n);return lh(d,b)?d:b})},[l,n]),o.useEffect(()=>{ch(a)},[a]);const m=o.useMemo(()=>ah(u),[u]),f=o.useCallback((d,b)=>{i(y=>th(y,d,b))},[]),g=o.useCallback(d=>{i(b=>sh(b,d))},[]),w=o.useCallback((d,b)=>{i(y=>rh(y,u,d,b))},[u]),A=o.useCallback(d=>{i(b=>nh(b,d))},[]);return{notifications:u,unreadCount:m,notificationStateBySessionId:p,markRead:f,markUnread:g,markTargetRead:w,deleteNotification:A}}function cl(){return"select_session"}function uh(){return"open_panel"}function mh({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function ph(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function pi(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function fi(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function mo(e){return e instanceof Error?e.message:String(e||"")}function hi(e){const s=mo(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function xi(e,s){const r=mo(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function kn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useRef(!1),g=o.useRef(null);o.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const w=o.useCallback(async y=>{if(!s)return!1;const h=y.trim(),S=Ga(s);if(mh({hasMessage:!!h,blockedMessage:S,sendInFlight:f.current}))return S&&m(S),!1;const _=Date.now(),k={tabKey:s.tabKey,message:h,timestamp:_};if(ph(g.current,k))return m(null),!0;f.current=!0,u(!0),m(null),g.current=k;const I=`${_}-${Math.random().toString(36).slice(2,8)}`,j={role:"user",content:h,timestamp:_,_localId:I},v=!0;r(x=>({...x,[k.tabKey]:[...x[k.tabKey]||[],j]}));try{const x=gr(s);if(!x)return g.current=pi(g.current,k),v&&r(M=>({...M,[k.tabKey]:(M[k.tabKey]||[]).filter(T=>T._localId!==I)})),m("Unable to send message right now."),!1;const E=await e(x,"send_chat",{message:h,...Es(s)}),L=fi(E);if(v&&(L!=null&&L.deduplicated))return r(M=>({...M,[k.tabKey]:(M[k.tabKey]||[]).filter(T=>T._localId!==I)})),m(null),!0;if((L==null?void 0:L.sent)===!1)throw new Error((L==null?void 0:L.error)||"Send failed");if((L==null?void 0:L.success)===!1)throw new Error((L==null?void 0:L.error)||"Send failed");return setTimeout(()=>{const M=Date.now()-6e4;r(T=>{const B=T[k.tabKey];if(!B)return T;const H=B.filter(C=>C.timestamp>M);return H.length===B.length?T:{...T,[k.tabKey]:H}})},6e4),m(null),!0}catch(x){const E=mo(x);return E.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",E):console.warn("Send blocked/failed",x),g.current=pi(g.current,k),r(L=>({...L,[k.tabKey]:(L[k.tabKey]||[]).filter(M=>M._localId!==I)})),m($m(x)),!1}finally{f.current=!1,u(!1)}},[s,e,n,r]),A=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(y){console.error("Relaunch failed",y)}},[s,e]),d=o.useCallback(async y=>{if(s)try{const S=(s.modalButtons||[]).indexOf(y),_=y.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_),I=gr(s);if(!I)return;const j=await e(I,"resolve_action",{button:y,action:k?"approve":"reject",...S>=0&&{buttonIndex:S},...Es(s)}),v=fi(j);v.success||n(x=>[...x,{routeId:s.tabKey,text:xi(y,v==null?void 0:v.error),timestamp:Date.now()}])}catch(h){hi(h)||console.error("[ModalButton] Error:",h),n(S=>[...S,{routeId:s.tabKey,text:hi(h)?xi(y,h):`❌ **${y}** error`,timestamp:Date.now()}])}},[s,e,n]),b=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,uh(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(y){console.error("Focus agent failed",y)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:p,isFocusingAgent:i,handleSendChat:w,handleRelaunch:A,handleModalButton:d,handleFocusAgent:b}}const po=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:d,isInputActive:b=!0}){const y=Zc(s),h=y.status||y.modalMessage||y.modalButtons?{...s,...y.status?{status:y.status}:{},...y.modalMessage!==void 0?{modalMessage:y.modalMessage}:{},...y.modalButtons!==void 0?{modalButtons:y.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(nc,{activeConv:h,onModalButton:c}),h.transport!=="pty"&&h.transport!=="acp"&&h.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[t.jsx("span",{className:"text-sm",children:t.jsx(ks,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,h.transport==="pty"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(lp,{activeConv:h,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(va,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})})]}):t.jsx(va,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:p,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:A,scrollToBottomRequestNonce:d,isInputActive:b})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function fh({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:m,onOpenMachine:f,onOpenHistory:g,onOpenRemote:w,onHideConversation:A,onStopCli:d,cliViewMode:b,onSetCliViewMode:y,handleSendChat:h,handleFocusAgent:S,handleModalButton:_,handleRelaunch:k}){const I=o.useRef(null),j=tt(e)&&!s,v=j&&b==="terminal",x=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 ${x} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:t.jsx(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:lt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(jc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>m(e),onOpenMachine:()=>f(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&b&&t.jsx(Ya,{mode:b,onChange:y,compact:!0}),j&&d&&t.jsx("button",{onClick:()=>{d(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(At,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:t.jsx(Da,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:t.jsx(Rt,{size:14})}),A&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>A(e),type:"button",title:"Close chat",children:t.jsx(At,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(po,{activeConv:e,clearToken:0,isCliTerminal:v,ideEntry:n,terminalRef:I,handleModalButton:_,handleRelaunch:k,handleSendChat:h,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:S,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const Yn={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 hh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function ll(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(hh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Yn[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:Yn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Yn[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 dl({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Rt},{key:"chats",label:"Chats",icon:Zt}];return t.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:t.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:i})=>{const c=e===n;return t.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>s(n),type:"button","aria-pressed":c,children:[t.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:t.jsx(i,{size:15})}),t.jsx("span",{children:a})]},n)})})})}function Fr({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 Ms({children:e,className:s=""}){return t.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:e})}function sr({icon:e,title:s,subtitle:r,children:n}){return t.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[t.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Ur({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:p}=qs(e.conversation),m=lt(e.conversation),f=Cs(e.conversation),g=Rc(e.conversation,{requiresAction:s==="needs_attention"}),w=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",A=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",d=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",S="text-[color:var(--status-warning)]";return t.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${w}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${A}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(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:rc(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:`${S} animate-pulse`,children:"Reconnecting…"})]}):p?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):g==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:S,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${y}`,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 bi({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 xh({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:g,onOpenSettings:w,onSectionChange:A,wsStatus:d="connected",isStandalone:b=!1}){const y=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",h=c.length>0,S=s.length>0||r.length>0||n.length>0||a.length>0,_=e==="machines"?"Machines":"Chats",k=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=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 ${k}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[t.jsx(yn,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:t.jsx(bn,{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] ${I}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:y?t.jsx(sr,{icon:t.jsx(bi,{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(sr,{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(ll,{})})}):t.jsx(Ms,{children:c.map((j,v)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>g(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(Fr,{title:"Needs attention",className:"mb-0"}),t.jsx(Ms,{children:s.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Ur,{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(Fr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(Ms,{children:r.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Ur,{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(Fr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(Ms,{children:n.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Ur,{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(Fr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(Ms,{children:a.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Ur,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):S?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?t.jsx(sr,{icon:t.jsx(bi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(sr,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Zt,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(sr,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:m,children:"Restore all"})]}),t.jsx(Ms,{className:"bg-bg-secondary/25",children:i.map((j,v)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(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(lt(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:lt(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:Cs(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(dl,{section:e,onSectionChange:A})]})}function bh(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 ul(e){const s=[e.workspace||"Workspace unknown"],r=Ss(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=bh(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Sn(...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 gh(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=gh(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 yh(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 vh(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Cn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=vh(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 In({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 g=yh(r),w=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(At,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||a||u(g)},disabled:!g||a,children:[t.jsx(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:A=>f(A.target.value),onKeyDown:A=>{A.key!=="Enter"||!w||a||(A.preventDefault(),u(w))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!w||a||u(w)},disabled:!w||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(A=>t.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(A.path),children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Bs,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:A.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:A.path})]})]},A.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(w||r),disabled:!w&&!r||a,children:c})]})]})})}function fo({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:g,modelValue:w,onModelChange:A,historyProviderNode:d,onConfirm:b,onCancel:y}){const h=n==null?void 0:n.find(S=>S.key===a);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":"Close launch confirmation",children:t.jsx(At,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:a||"",onChange:S=>i(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(S=>t.jsx("option",{value:S.key,children:S.label},S.key))}),(h==null?void 0:h.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),d,r.map(S=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:S.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:S.value})]},`${S.label}:${S.value}`)),g&&A&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:w||"",onChange:S=>A(S.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&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:S=>f(S.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,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(Ea,{size:14}),u?l:c]})]})]})})}function gi(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function vs(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?"⭐ ":""}${gi(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:gi(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 wh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function jh(e){return[wh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function kh(e){return e.lastLaunchedAt?vn(e.lastLaunchedAt):""}function ml(e){return{metaText:jh(e),updatedLabel:kh(e)}}function Xn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function Sh({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var ze,xt,bt,ct;const c=Sr(),[l,u]=o.useState(!1),p=(((ze=e.detectedIdes)==null?void 0:ze.length)||0)>0,m=o.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),f=e.defaultWorkspaceId||null,[g,w]=o.useState(f||((xt=m[0])==null?void 0:xt.id)||""),[A,d]=o.useState(""),[b,y]=o.useState(""),[h,S]=o.useState([]),[_,k]=o.useState(!1),[I,j]=o.useState(""),[v,x]=o.useState(!1),[E,L]=o.useState(Xn(p,s.length,r.length)),M=o.useRef(null),[T,B]=o.useState(null),H=o.useRef("__home__"),[C,R]=o.useState("__home__"),[U,N]=o.useState(""),[D,Y]=o.useState(""),[q,W]=o.useState(""),[ae,ce]=o.useState([]),[Se,X]=o.useState(()=>jt().textQuery),[he,J]=o.useState(()=>jt().workspaceQuery),[Z,ue]=o.useState(()=>jt().modelQuery),[de,z]=o.useState(()=>jt().resumableOnly),[ye,ie]=o.useState(()=>jt().sortMode),[le,se]=o.useState(!1),[pe,ne]=o.useState(!1),ke=o.useRef(null),ve=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const K=g==="__custom__"?A.trim():((bt=m.find(Te=>Te.id===g))==null?void 0:bt.path)||"",V=g==="__custom__"&&!!K&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),we=g!=="__custom__"&&((ct=m.find(Te=>Te.id===g))==null?void 0:ct.path)||"",be=o.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),Q=o.useCallback(async Te=>{k(!0),j("");try{const Xe=await a(Te);y(Xe.path),d(Xe.path),S(Xe.directories)}catch(Xe){j(Xe instanceof Error?Xe.message:"Could not load folder")}finally{k(!1)}},[a]),Me=o.useCallback(()=>{var Xe;w("__custom__"),x(!0);const Te=Nn(e.platform,Sn(A.trim(),we,be,e.defaultWorkspacePath,(Xe=m.find(Fe=>Fe.id===f))==null?void 0:Xe.path,m.map(Fe=>Fe.path)));Q(Te)},[A,f,Q,be,we,e.platform,m]),Oe=o.useCallback(Te=>{if(Te!=null&&Te.workspaceId){w(Te.workspaceId),d("");return}if(Te!=null&&Te.workspacePath){w("__custom__"),d(Te.workspacePath);return}w(""),d("")},[]),Pe=o.useCallback(Te=>{if(w(Te),Te==="__custom__"){Me();return}d("")},[Me]),Ke=o.useCallback(Te=>{w("__custom__"),d(Te)},[]),Qe=o.useCallback((Te,Xe)=>{M.current=Xe,H.current=Te.selectedWorkspaceKey||"__home__",R(Te.selectedWorkspaceKey||"__home__"),N(Te.initialArgs||""),Y(Te.initialModel||""),W(""),ce([]);const Fe=Te.providerType?`${e.id}:${Te.providerType}`:null;if(pp(ve.current,Fe)){const Ue=jt();X(Ue.textQuery),J(Ue.workspaceQuery),ue(Ue.modelQuery),z(Ue.resumableOnly),ie(Ue.sortMode)}ve.current=Fe,B(Te),Te.providerType&&i&&(se(!0),i(Te.providerType).then(Ue=>ce(Ue||[])).catch(Ue=>console.warn("Failed to load saved sessions",Ue)).finally(()=>se(!1)))},[i,e.id]),Ge=o.useMemo(()=>Ec(ae,{textQuery:Se,workspaceQuery:he,modelQuery:Z,resumableOnly:de,sortMode:ye}),[Z,de,ae,ye,Se,he]);o.useEffect(()=>{q&&(Ge.some(Te=>Te.providerSessionId===q)||W(""))},[Ge,q]);const ut=o.useCallback(()=>{M.current&&(ne(!0),M.current().finally(()=>{M.current=null,ne(!1),B(null)}))},[]),it=o.useCallback(()=>{M.current=null,B(null)},[]),ht=o.useCallback(Te=>{H.current=Te,R(Te)},[]);return o.useEffect(()=>{var Te;ke.current!==e.id&&(ke.current=e.id,w(f||((Te=m[0])==null?void 0:Te.id)||"__custom__"),d(""),y(""),S([]),j(""),x(!1),X(jt().textQuery),J(jt().workspaceQuery),ue(jt().modelQuery),z(jt().resumableOnly),ie(jt().sortMode),ve.current=null,L(Xn(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,m]),o.useEffect(()=>{var Te;g!=="__custom__"&&(g&&m.some(Xe=>Xe.id===g)||w(f||((Te=m[0])==null?void 0:Te.id)||"__custom__"))},[f,g,m]),o.useEffect(()=>{E==="ide"&&p||E==="cli"&&s.length>0||E==="acp"&&r.length>0||L(Xn(p,s.length,r.length))},[E,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:f,workspaceChoice:g,customWorkspacePath:A,browseCurrentPath:b,browseDirectories:h,browseBusy:_,browseError:I,browseDialogOpen:v,activeLauncherKind:E,launchConfirm:T,launchConfirmWorkspaceKeyRef:H,launchConfirmWorkspaceKey:C,launchConfirmArgs:U,launchConfirmModel:D,launchConfirmResumeId:q,launchConfirmSavedSessions:ae,launchConfirmTextFilter:Se,launchConfirmWorkspaceFilter:he,launchConfirmModelFilter:Z,launchConfirmResumableOnly:de,launchConfirmSortMode:ye,filteredLaunchConfirmSavedSessions:Ge,launchConfirmSessionsLoading:le,launchConfirmBusy:pe,resolvedWorkspacePath:K,canCreateMissingWorkspace:V,openBrowseDialog:Me,loadBrowsePath:Q,handleWorkspaceChoiceChange:Pe,chooseCustomWorkspacePath:Ke,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:L,openLaunchConfirm:Qe,handleConfirmLaunch:ut,closeLaunchConfirm:it,setWorkspaceSelectionFromOption:Oe,setLaunchConfirmWorkspaceKeyAndSync:ht,setLaunchConfirmArgs:N,setLaunchConfirmModel:Y,setLaunchConfirmResumeId:W,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:J,setLaunchConfirmModelFilter:ue,setLaunchConfirmResumableOnly:z,setLaunchConfirmSortMode:ie}}function Nh({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:g,onOpenConversation:w,onOpenRecent:A,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:y,onAddWorkspace:h,onBrowseDirectory:S,onLaunchWorkspaceProvider:_,onListSavedSessions:k}){const I=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",j=r.slice(0,4),v=s.slice(0,3),x=Sh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:S,onListSavedSessions:k}),E=o.useMemo(()=>j.map(C=>{const{metaText:R,updatedLabel:U}=ml(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:R,updatedLabel:U,onClick:()=>{const{options:N,selectedKey:D}=vs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:C.workspace});x.openLaunchConfirm({title:C.kind==="ide"?xs("restart-ide",C.label):C.providerSessionId?Qa(C.label):xs("start-fresh",C.label),description:C.kind==="ide"?bs("restart-ide"):C.providerSessionId?Za():bs("start-fresh"),confirmLabel:C.kind==="ide"?Us("restart-ide"):C.providerSessionId?mn(!0):Us("start-fresh"),busyLabel:C.kind==="ide"?zs("restart-ide"):C.providerSessionId?Xa(!0):zs("start-fresh"),workspaceOptions:N,selectedWorkspaceKey:D,details:[{label:"Mode",value:I(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const Y=N.find(q=>q.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(Y),await A({...C,workspace:(Y==null?void 0:Y.workspacePath)??null})})}}}),[x,A,j]),L=o.useMemo(()=>v.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:lt(C.conversation),secondary:ap(C.conversation,{timestampLabel:C.timestamp?rc(C.timestamp):null}),unread:C.unread,onClick:()=>w(C.conversation)})),[w,v]),M=x.showAllRecent?E:E.slice(0,4),T=E.length>0,B=L.length>0,H=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${H} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick: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:_t(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[B&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.map(C=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),T&&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(C=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:C.primary}),C.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),E.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(C=>!C),children:x.showAllRecent?"Show fewer":`Show ${E.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:C=>x.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:x.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[x.workspaceRows.map(C=>t.jsxs("option",{value:C.id,children:[C.id===x.defaultWorkspaceId?"⭐ ":"",jn(C.path,C.label)||C.path]},C.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(Bs,{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(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:R,selectedKey:U}=vs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:R,selectedWorkspaceKey:U,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const N=R.find(D=>D.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(N),y(C.type,{workspacePath:(N==null?void 0:N.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(x.activeLauncherKind==="cli"?n:a).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const R=x.activeLauncherKind==="cli"?"cli":"acp",{options:U,selectedKey:N}=vs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${R.toUpperCase()}`,workspaceOptions:U,selectedWorkspaceKey:N,details:[{label:"Mode",value:R.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:R==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const D=U.find(Y=>Y.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),_(R,C.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:[C.icon?`${C.icon} `:"",C.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,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(In,{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:C=>{x.loadBrowsePath(C)},onConfirm:C=>{x.chooseCustomWorkspacePath(C),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx(fo,{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?mn(!!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:Ja()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:C=>x.setLaunchConfirmTextFilter(C.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmWorkspaceFilter,onChange:C=>x.setLaunchConfirmWorkspaceFilter(C.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmModelFilter,onChange:C=>x.setLaunchConfirmModelFilter(C.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsxs("select",{value:x.launchConfirmSortMode,onChange:C=>x.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled: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:C=>x.setLaunchConfirmResumableOnly(C.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:C=>x.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:xp()}),x.filteredLaunchConfirmSavedSessions.map(C=>t.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.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 C=x.filteredLaunchConfirmSavedSessions.find(U=>U.providerSessionId===x.launchConfirmResumeId);if(!C)return null;const R=ul(C);return t.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:R.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:R.providerSessionId}),t.jsx("div",{className:"mt-1",children:R.metaLine}),R.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:R.updatedLabel}),R.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:R.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),m&&t.jsx(dl,{section:p,onSectionChange:g})]})}function pl(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 Ch(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:Ss(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=xr(n)?"cli":Ps(n)?"acp":"ide",i=Ss(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(xr(n)?n.cliName||n.type:Ps(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ps(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 Ih(e,s){const r=new Map;for(const n of s){const a=is(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,g)=>g.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ha(n),u=a.filter(f=>f.unread||f.requiresAction).length,p=pl(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:_t(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?op(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 zr(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 Ah({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:g,onRequestedMobileSectionConsumed:w,setSelectedTabKey:A,setScreen:d,setSelectedMachineId:b,setSection:y,setMachineBackTarget:h,resetMachineAction:S,markNotificationTargetRead:_}){const k=o.useRef(null),I=o.useCallback(j=>{if(!(j!=null&&j.sessionId))return;const v=ln(j,c),x=Math.max(Date.now(),ps(j),v.lastUpdated||0);zr("mark_read:start",{tabKey:j.tabKey,sessionId:j.sessionId,displayPrimary:lt(j),inboxBucket:v.inboxBucket,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:ps(j),readAt:x}),_({sessionId:j.sessionId,providerSessionId:j.providerSessionId,tabKey:j.tabKey,routeId:j.routeId},x),l(is(j)||j.routeId,"mark_session_seen",{sessionId:j.sessionId,seenAt:x}).then(E=>{zr("mark_read:result",{tabKey:j.tabKey,sessionId:j.sessionId,result:E})}).catch(E=>{zr("mark_read:error",{tabKey:j.tabKey,sessionId:j.sessionId,error:E instanceof Error?E.message:String(E)})})},[c,l]);return o.useEffect(()=>{var v;if(!n){d("inbox"),A(((v=e[0])==null?void 0:v.tabKey)||null),k.current=null;return}if(i!=="chat"){k.current=null;return}const j=`${n.tabKey}:${n.sessionId||""}`;k.current!==j&&(k.current=j,I(n))},[e,I,i,n,d,A]),o.useEffect(()=>{if(!u)return;const j=e.find(v=>v.tabKey===u);j&&(A(j.tabKey),d("chat"),p==null||p())},[e,p,u,d,A]),o.useEffect(()=>{if(!m)return;const j=s.find(v=>v.id===m);j&&(b(j.id),S(),y("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,m,S,h,d,y,b]),o.useEffect(()=>{g&&(y(g),d("inbox"),w==null||w())},[w,g,d,y]),o.useEffect(()=>{const j=r.filter(v=>v.inboxBucket==="task_complete"||v.unread);j.length!==0&&zr("inbox_state",{screen:i,selectedTabKey:a,items:j.map(v=>{const x=ln(v.conversation,c);return{liveState:x,tabKey:v.conversation.tabKey,sessionId:v.conversation.sessionId,displayPrimary:lt(v.conversation),serverBucket:x.inboxBucket,computedBucket:v.inboxBucket,serverUnread:x.unread,computedUnread:v.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:ps(v.conversation)}})})},[r,c,i,a]),{markConversationRead:I}}function Mh(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function yi(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Th(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Lh({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,S,_)=>{var k;try{i("loading"),l(`Launching ${S}…`);const I={ideType:S,enableCdp:!0};(k=_==null?void 0:_.workspacePath)!=null&&k.trim()&&(I.workspace=_.workspacePath.trim()),await e(h,"launch_ide",I),i("done"),l(`${S} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),g=o.useCallback(async(h,S,_)=>{if(S.trim())try{i("loading"),l(_!=null&&_.createIfMissing?"Creating folder…":"Saving workspace…");const k=await e(h,"workspace_add",{path:S.trim(),createIfMissing:(_==null?void 0:_.createIfMissing)===!0});if(k!=null&&k.success){i("done"),l(_!=null&&_.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((k==null?void 0:k.error)||"Could not save workspace")}catch(k){i("error"),l(k instanceof Error?k.message:"Could not save workspace")}},[e]),w=o.useCallback(async h=>{var S,_,k,I,j,v;try{i("loading"),l("Starting daemon upgrade…");const x=await e(h,"daemon_upgrade",{});if((S=x==null?void 0:x.result)!=null&&S.alreadyLatest){i("done"),l(`Already on v${((_=x==null?void 0:x.result)==null?void 0:_.version)||"latest"}.`);return}if((k=x==null?void 0:x.result)!=null&&k.upgraded||(I=x==null?void 0:x.result)!=null&&I.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(((v=x==null?void 0:x.result)==null?void 0:v.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),A=o.useCallback(async(h,S,_,k)=>{var v,x,E;const I=Date.now(),j={machineId:h,kind:S,providerType:_,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${_}…`),p(j);const L={cliType:_};(v=k==null?void 0:k.workspacePath)!=null&&v.trim()?L.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(L.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(L.resumeSessionId=k.resumeSessionId),(x=k==null?void 0:k.args)!=null&&x.trim()&&(L.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(E=k==null?void 0:k.model)!=null&&E.trim()&&(L.initialModel=k.model.trim());const M=await e(h,"launch_cli",L),T=(M==null?void 0:M.result)||M,B=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);if(M!=null&&M.success&&B){p(null),i("done"),l(`${_} launched`),s(as(B));return}if(M!=null&&M.success){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l((M==null?void 0:M.error)||(T==null?void 0:T.error)||`Could not launch ${S.toUpperCase()} workspace`)}catch(L){if(Th(L)){i("loading"),l(`${_} launch requested — waiting for session…`);return}p(null),i("error"),l(L instanceof Error?L.message:`Could not launch ${S.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(h,S)=>{try{const _=await e(h,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),k=(_==null?void 0:_.result)??_;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(_){return console.error("Failed to list saved sessions on mobile:",_),[]}},[e]),b=o.useCallback(async(h,S)=>Cn(e,h,S),[e]);o.useEffect(()=>{if(!u)return;const h=yi(u.workspacePath),S=r.find(k=>{var L,M,T,B;if(!k||k.type==="adhdev-daemon"||Mh(k.daemonId||k.id)!==u.machineId||(k.transport==="acp"?"acp":k.transport==="pty"?"cli":null)!==u.kind||String(k.agentType||k.type||"")!==u.providerType)return!1;const x=String(k.providerSessionId||"");if(u.resumeSessionId&&x)return x===u.resumeSessionId;if(h){const H=yi(k.workspace||k.runtimeWorkspaceLabel);return H?H===h:!1}return Number(k.lastUpdated||k._lastUpdate||k.timestamp||((B=(T=(M=(L=k.activeChat)==null?void 0:L.messages)==null?void 0:M.at)==null?void 0:T.call(M,-1))==null?void 0:B.timestamp)||0)>=u.startedAt-5e3});if(!S)return;const _=wc({entrySessionId:S.sessionId,entryInstanceId:S.instanceId,entryRouteId:S.id,conversations:n});_&&(p(null),i("done"),l(`${u.providerType} launched`),s(as(_)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{p(S=>!S||S.startedAt!==u.startedAt?S:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[u]);const y=o.useCallback(async(h,S)=>{if(S.kind==="ide"&&S.providerType){await f(h,S.providerType,{workspacePath:S.workspace||null});return}(S.kind==="cli"||S.kind==="acp")&&S.providerType&&await A(h,S.kind,S.providerType,{workspacePath:S.workspace||null,resumeSessionId:S.providerSessionId||null})},[f,A]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:A,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:y}}function _h({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:p}){const m=o.useCallback(y=>{i(y.tabKey),c("chat"),n(y)},[n,c,i]),f=o.useCallback(y=>{const h=e.find(S=>S.routeId===y.routeId&&S.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),g=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),w=o.useCallback((y,h="inbox")=>{l(y),a(),u("machines"),p(h),c("machine")},[a,p,c,u,l]),A=o.useCallback(y=>{const h=is(y);h&&w(h,"chat")},[w]),d=o.useCallback(()=>{a(),c(r)},[r,a,c]),b=o.useCallback(y=>{u(y),c("inbox")},[c,u]);return{openConversation:m,openNativeConversation:f,backFromConversation:g,openMachine:w,openConversationMachine:A,backFromMachine:d,changeMachineSection:b}}function Rh(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Vr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Ph({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:g,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,onOpenHistory:d,onOpenRemote:b,onStopCli:y,wsStatus:h,isConnected:S,onShowHiddenConversation:_,onShowAllHiddenConversations:k,onHideConversation:I,onOpenNewSession:j,notificationStateBySessionId:v,liveSessionInboxState:x,onMarkNotificationTargetRead:E}){const[L,M]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[T,B]=o.useState(()=>e[0]?"chat":"inbox"),[H,C]=o.useState("chats"),[R,U]=o.useState(null),[N,D]=o.useState("inbox"),Y=Vs(),q="0.8.88",W=o.useMemo(()=>e.find(Q=>Q.tabKey===L)||e[0]||null,[e,L]),ae=o.useMemo(()=>W?r.find(Q=>Q.id===W.routeId):void 0,[r,W]),ce=o.useMemo(()=>!W||Ze(W)||!tt(W)?null:Hs(W),[W]),Se=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Wa),[r]),X=o.useMemo(()=>Se.find(Q=>Q.id===R)||null,[Se,R]),he=kn({sendDaemonCommand:a,activeConv:W||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),J=Lh({sendDaemonCommand:a,navigate:Y,ides:r,conversations:e}),Z=o.useMemo(()=>e.map(Q=>{const Me=T==="chat"&&(W==null?void 0:W.tabKey)===Q.tabKey,Oe=wn(Q,x,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Me,notificationStateBySessionId:v}),Pe=ps(Q),Ke=_c(Q);return{conversation:Q,timestamp:Pe,preview:Ke,unread:Oe.unread,requiresAction:Oe.requiresAction,isWorking:Oe.isWorking,inboxBucket:Oe.inboxBucket}}),[e,x,v,T,W]),{markConversationRead:ue}=Ah({conversations:e,machineEntries:Se,items:Z,selectedConversation:W,selectedTabKey:L,screen:T,liveSessionInboxState:x,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:g,requestedMobileSection:w,onRequestedMobileSectionConsumed:A,setSelectedTabKey:M,setScreen:B,setSelectedMachineId:U,setSection:C,setMachineBackTarget:D,resetMachineAction:J.resetMachineAction,markNotificationTargetRead:E}),de=_h({conversations:e,selectedConversation:W,machineBackTarget:N,markConversationRead:ue,resetMachineAction:J.resetMachineAction,setSelectedTabKey:M,setScreen:B,setSelectedMachineId:U,setSection:C,setMachineBackTarget:D}),z=o.useMemo(()=>Vr(Z.filter(Q=>Q.requiresAction)),[Z]),ye=o.useMemo(()=>Vr(Z.filter(Q=>Q.unread&&!Q.requiresAction)),[Z]),ie=o.useMemo(()=>Vr(Z.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking)),[Z]),le=o.useMemo(()=>Vr(Z.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[Z]),se=o.useMemo(()=>X?Z.filter(Q=>is(Q.conversation)===X.id):[],[Z,X]),pe=o.useMemo(()=>Ch(X,r),[r,X]),ne=(X==null?void 0:X.version)||null,ke=!!X&&!!ne&&!0&&ne!==q,ve=o.useMemo(()=>(X==null?void 0:X.availableProviders)||[],[X]),K=o.useMemo(()=>ve.filter(Q=>Q.category==="cli"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ve]),V=o.useMemo(()=>ve.filter(Q=>Q.category==="acp"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[ve]),we=o.useMemo(()=>Ih(Se,Z),[Z,Se]),be=o.useCallback(async Q=>{X&&await J.handleOpenRecent(X.id,Q)},[J,X]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:T==="chat"&&W?t.jsx(fh,{selectedConversation:W,isAcp:Ze(W),isStandalone:l,selectedIdeEntry:ae,actionLogs:n,userName:u,isSendingChat:he.isSendingChat,sendFeedbackMessage:he.sendFeedbackMessage,isFocusingAgent:he.isFocusingAgent,handleModalButton:he.handleModalButton,handleRelaunch:he.handleRelaunch,onBack:de.backFromConversation,onOpenNativeConversation:de.openNativeConversation,onOpenMachine:de.openConversationMachine,onHideConversation:I,onOpenHistory:d,onOpenRemote:b,onStopCli:y,cliViewMode:ce,onSetCliViewMode:async Q=>{if(W&&ce!==Q)try{await a(is(W)||W.routeId,"set_cli_view_mode",{targetSessionId:W.sessionId,cliType:Bt(W),mode:Q})}catch(Me){const Oe=co(Me);io(Me)?console.warn(Oe?"CLI view mode result was lost after send; keeping optimistic mobile mode override:":"Skipped CLI view mode switch:",Me instanceof Error?Me.message:String(Me)):console.error("Failed to switch CLI view mode:",Me)}},handleSendChat:he.handleSendChat,handleFocusAgent:he.handleFocusAgent}):T==="machine"&&X?t.jsx(Nh,{selectedMachineEntry:X,selectedMachineConversations:se,selectedMachineRecentLaunches:pe,cliProviders:K,acpProviders:V,selectedMachineNeedsUpgrade:ke,appVersion:q,machineAction:J.machineAction,isStandalone:l,section:H,showBottomNav:N==="inbox",onBack:de.backFromMachine,onSectionChange:de.changeMachineSection,onOpenConversation:de.openConversation,onOpenRecent:be,onOpenMachineDetails:()=>Y(`/machines/${X.id}`),onMachineUpgrade:()=>J.handleMachineUpgrade(X.id),onLaunchDetectedIde:(Q,Me)=>J.handleLaunchDetectedIde(X.id,Q,Me),onAddWorkspace:(Q,Me)=>J.handleAddWorkspace(X.id,Q,Me),onBrowseDirectory:Q=>J.handleBrowseDirectory(X.id,Q),onLaunchWorkspaceProvider:(Q,Me,Oe)=>J.handleLaunchWorkspaceProvider(X.id,Q,Me,Oe),onListSavedSessions:Q=>J.handleListSavedSessions(X.id,Q)}):t.jsx(xh,{section:H,attentionItems:z,unreadItems:ye,workingItems:ie,completedItems:le,hiddenConversations:s,machineCards:we,getAvatarText:Rh,onOpenConversation:de.openConversation,onShowConversation:_,onShowAllHidden:k,onOpenNewSession:j,onOpenMachine:de.openMachine,onOpenSettings:()=>Y("/settings"),onSectionChange:C,wsStatus:h,isConnected:S,isStandalone:l})})}function Jn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Dh({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 g=o.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),w=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!Jn(s,r)){m("merge");return}const y=b.currentTarget.getBoundingClientRect(),h=b.clientX-y.left,S=y.width/3;h<S?m("split-left"):h>S*2?m("split-right"):m("merge")},[s,r]),A=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 y=b.dataTransfer.getData("text/tab-key"),h=y?e.some(_=>_.tabKey===y):!1,S=p;if(m(null),i(),!!y){if(b.preventDefault(),S==="split-left"&&Jn(s,r)){r==null||r(y,"split-left");return}if(S==="split-right"&&Jn(s,r)){r==null||r(y,"split-right");return}if(h){a(y);return}n==null||n(y)}},[e,p,s,r,n,a,i]);return{dragOver:l,dropAction:p,resetDragState:f,handleDragEnter:g,handleDragOver:w,handleDragLeave:A,handleDrop:d}}function Eh(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 $h({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),g=o.useRef(null),w=o.useRef(n),A=o.useRef(a);o.useEffect(()=>{w.current=n},[n]),o.useEffect(()=>{A.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(j=>{const v=Eh(j,e);return v.length===j.length&&v.every((x,E)=>x===j[E])?j:v})},[e]);const d=o.useMemo(()=>{const j=p??l;if(j.length===0)return e;const v=new Map(j.map((x,E)=>[x,E]));return[...e].sort((x,E)=>{const L=v.get(x.tabKey)??999,M=v.get(E.tabKey)??999;return L-M})},[e,p,l]);o.useEffect(()=>{var v,x;if(d.length===0){i!==null&&(c(null),(v=w.current)==null||v.call(w,null));return}if(i&&d.some(E=>E.tabKey===i))return;const j=d[0].tabKey;j!==i&&(c(j),(x=w.current)==null||x.call(w,j))},[d,i]);const b=o.useMemo(()=>d.find(j=>j.tabKey===i),[d,i]),y=o.useCallback(j=>{var v;c(j),(v=w.current)==null||v.call(w,j)},[]),h=o.useCallback((j,v,x)=>{u(E=>{var B;const L=E.filter(H=>H!==j),M=L.indexOf(v);if(M<0)return E;const T=x==="left"?M:M+1;return L.splice(T,0,j),(B=A.current)==null||B.call(A,L),L}),m(null)},[]),S=o.useCallback((j,v,x)=>{const L=(l.length>0?l:e.map(B=>B.tabKey)).filter(B=>B!==j),M=L.indexOf(v);if(M<0)return;const T=x==="left"?M:M+1;L.splice(T,0,j),f.current=L,m(L)},[l,e]),_=o.useCallback(()=>{var v;const j=f.current;j&&(u(j),(v=A.current)==null||v.call(A,j))},[]),k=o.useCallback(()=>{f.current=null,m(null)},[]),I=o.useCallback(j=>{u(v=>{var E;const x=v.filter(L=>L!==j);return x.push(j),(E=A.current)==null||E.call(A,x),x})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:f,draggingTabRef:g,selectTab:y,handleTabReorder:h,updatePreviewOrder:S,commitPreviewOrder:_,clearPreviewOrder:k,moveTabToEnd:I,setDraggingTabKey:j=>{g.current=j}}}function Kh({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 ho({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(ll,{}),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 fl="adhdev-tab-shortcuts";function hl(){try{return JSON.parse(localStorage.getItem(fl)||"{}")}catch{return{}}}function xl({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>hl()),[l,u]=o.useState(null),p=o.useCallback(f=>{const g=[];return f.metaKey&&g.push(a?"⌘":"Meta"),f.ctrlKey&&g.push("Ctrl"),f.altKey&&g.push(a?"⌥":"Alt"),f.shiftKey&&g.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(g.push(f.key.length===1?f.key.toUpperCase():f.key),g.join("+"))},[a]),m=o.useCallback(f=>{c(f);try{localStorage.setItem(fl,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){u(null);return}const w=p(g);if(!w)return;const A={...i};for(const[d,b]of Object.entries(A))b===w&&delete A[d];A[l]=w,m(A),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=g=>{if(!(!g.ctrlKey&&!g.metaKey&&!g.altKey)){for(const[w,A]of Object.entries(i))if(s.includes(w)&&p(g)===A){g.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,i,s,r,n,p]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:m}}const Bh=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:g,onCommitPreviewOrder:w,onClearPreviewOrder:A,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:h,longPressTimer:S,isGroupActive:_}){const k=qs(s),I=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",j=k.isReconnecting,v=o.useCallback(R=>{l.current=s.tabKey,b(s.tabKey),R.dataTransfer.setData("text/tab-key",s.tabKey),R.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),x=o.useCallback(()=>{l.current=null,b(null),w(),A(),d()},[l,b,w,A,d]),E=o.useCallback(R=>{const U=l.current;if(!(!U||U===s.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const N=R.currentTarget.getBoundingClientRect(),D=R.clientX<N.left+N.width/2?"left":"right";f(U,s.tabKey,D)}},[s.tabKey,l,f]),L=o.useCallback(R=>{R.preventDefault(),R.stopPropagation();const U=R.dataTransfer.getData("text/tab-key");if(U&&U!==s.tabKey){const N=R.currentTarget.getBoundingClientRect(),D=R.clientX<N.left+N.width/2?"left":"right";c.includes(U)?g(U,s.tabKey,D):y&&y(U)}A()},[s.tabKey,c,g,y,A]),M=o.useCallback(R=>{R.stopPropagation(),u(),p(s.tabKey),m(s)},[s,m,u,p]),T=o.useCallback(R=>{R.preventDefault(),h(R.clientX,R.clientY,s.tabKey)},[s.tabKey,h]),B=o.useCallback(R=>{const U=R.touches[0];S.current=setTimeout(()=>{h(U.clientX,U.clientY,s.tabKey)},600)},[s.tabKey,S,h]),H=o.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),C=["adhdev-dockview-tab",I,r&&"is-active",_&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:v,onDragEnd:x,onDragOver:E,onDrop:L,onClick:M,onContextMenu:T,onTouchStart:B,onTouchEnd:H,onTouchMove:H,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?t.jsx("div",{className:"tab-spinner"}):k.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.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:lt(s),children:lt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:hs(s)}):k.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[hs(s),t.jsx("span",{className:"connecting-dots"})]}):hs(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 Oh({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:g,onDragTabKeyChange:w,onReceiveTab:A,onHideTab:d,isGroupActive:b,allowTabShortcuts:y=!0}){const[h,S]=o.useState(null),_=o.useRef(null),k=o.useRef(null),I=o.useMemo(()=>e.map(T=>T.tabKey),[e]);wr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:j,tabShortcuts:v,shortcutListening:x,setShortcutListening:E,saveShortcuts:L}=xl({enabled:y,sortedTabKeys:e.map(T=>T.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const T=B=>{const H=document.querySelector("[data-pane-context-menu]");H&&H.contains(B.target)||S(null)};return window.addEventListener("mousedown",T,!0),()=>window.removeEventListener("mousedown",T,!0)},[h]),o.useEffect(()=>{const T=k.current;if(!T)return;const B=H=>{Math.abs(H.deltaY)<=Math.abs(H.deltaX)||(H.preventDefault(),T.scrollLeft+=H.deltaY)};return T.addEventListener("wheel",B,{passive:!1}),()=>T.removeEventListener("wheel",B)},[]);const M=o.useCallback((T,B,H)=>{S({x:T,y:B,tabKey:H})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(T=>t.jsx(Bh,{conv:T,isActive:s===T.tabKey,isDraggedTab:a.current===T.tabKey,isTaskCompleteUnread:n.has(T.tabKey),shortcut:y?v[T.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:g,onDragTabKeyChange:w,onReceiveTab:A,onOpenContextMenu:M,longPressTimer:_,isGroupActive:b},T.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:[y&&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:T=>{T.stopPropagation(),E(h.tabKey),S(null)},children:["⌨ ",v[h.tabKey]?`Change shortcut (${v[h.tabKey]})`:"Set shortcut"]}),v[h.tabKey]&&t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const T={...v};delete T[h.tabKey],L(T),S(null)},children:"✕ Remove shortcut"})]}),d&&t.jsxs(t.Fragment,{children:[y&&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),S(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&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:()=>E(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:T=>T.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 Wh({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:g,numGroups:w,onMoveTab:A,onReceiveTab:d,style:b,onActiveTabChange:y,initialActiveTabId:h,initialTabOrder:S,onTabOrderChange:_,onHideTab:k,isFocused:I,allowTabShortcuts:j=!0,notificationStateBySessionId:v,liveSessionInboxState:x}){const{sendCommand:E}=Pt(),L=o.useRef(null),{activeTabId:M,activeConv:T,sortedConversations:B,draggingTabRef:H,selectTab:C,handleTabReorder:R,updatePreviewOrder:U,commitPreviewOrder:N,clearPreviewOrder:D,moveTabToEnd:Y,setDraggingTabKey:q}=$h({conversations:e,initialActiveTabId:h,initialTabOrder:S,onActiveTabChange:y,onTabOrderChange:_}),W=kn({sendDaemonCommand:a,activeConv:T,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:ae,dropAction:ce,resetDragState:Se,handleDragEnter:X,handleDragOver:he,handleDragLeave:J,handleDrop:Z}=Dh({conversations:e,numGroups:w,onMoveTab:A,onReceiveTab:d,onOwnTabDrop:Y,onClearPreviewOrder:D}),ue=T&&!Ze(T)&&Hs(T)==="terminal",de=o.useMemo(()=>T?s.find(le=>le.id===T.routeId):void 0,[s,T]),z=o.useMemo(()=>T?n.filter(le=>le.routeId===T.tabKey):[],[n,T]),ye=o.useMemo(()=>new Set(B.filter(le=>ju(le,x,{isOpenConversation:le.tabKey===M,notificationStateBySessionId:v})).map(le=>le.tabKey)),[M,x,B]);wr("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:M,dragOver:ae});const ie=o.useCallback(le=>{le.streamSource==="agent-stream"&&le.agentType&&E(le.routeId,cl(),{agentType:le.agentType,...le.sessionId&&{targetSessionId:le.sessionId}}).catch(()=>{})},[E]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...b,outline:ae?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Oh,{conversations:B,activeTabId:M,groupIndex:m,numGroups:w,unreadTabKeys:ye,draggingTabRef:H,onFocus:f,onSelectTab:C,onConversationActivated:ie,onPreviewReorder:U,onReorderTab:R,onCommitPreviewOrder:N,onClearPreviewOrder:D,onDragStateReset:Se,onDragTabKeyChange:q,onMoveTab:A,onReceiveTab:d,onHideTab:k,isGroupActive:I??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:X,onDragOver:he,onDragLeave:J,onDrop:Z,children:[ae&&t.jsx(Kh,{dropAction:ce,canSplit:!!(w<4&&A)}),T?t.jsx(po,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!ue,ideEntry:de,terminalRef:L,handleModalButton:W.handleModalButton,handleRelaunch:W.handleRelaunch,handleSendChat:W.handleSendChat,isSendingChat:W.isSendingChat,sendFeedbackMessage:W.sendFeedbackMessage,handleFocusAgent:W.handleFocusAgent,isFocusingAgent:W.isFocusingAgent,actionLogs:z,userName:p,isInputActive:!g||!!I}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(ho,{conversationsCount:e.length,isSplitMode:g,isStandalone:l,hasRegisteredMachines:u})})]})]})}function Hh({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:g,userName:w,focusedGroup:A,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:y,closeGroup:h,handleResizeStart:S,groupActiveTabIds:_,setGroupActiveTabIds:k,groupTabOrders:I,setGroupTabOrders:j,toggleHiddenTab:v,allowTabShortcuts:x=!0,notificationStateBySessionId:E,liveSessionInboxState:L}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((M,T)=>{const B=s&&n.length===r?`${n[T]}%`:void 0;return t.jsxs(at.Fragment,{children:[s&&T>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:H=>S(T-1,H),onDoubleClick:()=>h(T),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(Wh,{style:s?{flexBasis:B??`${100/r}%`,flexGrow:B?0:1,flexShrink:B?0:1}:void 0,conversations:M,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:g,userName:w,groupIndex:T,isFocused:s&&A===T,onFocus:()=>d(T),isSplitMode:s,numGroups:r,onMoveTab:(H,C)=>{C==="left"&&T>0?b(H,T-1):C==="right"&&T<r-1?b(H,T+1):C==="split-left"&&r<4?y(H,T,"left"):C==="split-right"&&r<4&&y(H,T,"right")},onReceiveTab:H=>b(H,T),onActiveTabChange:H=>k(C=>(C[T]??null)===(H??null)?C:{...C,[T]:H}),initialActiveTabId:_[T],initialTabOrder:I[T],onTabOrderChange:H=>j(C=>{const R=C[T]||[];return R.length===H.length&&R.every((U,N)=>U===H[N])?C:{...C,[T]:H}}),onHideTab:v,allowTabShortcuts:x,notificationStateBySessionId:E,liveSessionInboxState:L})]},T)})})}function bl({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ft.onScreenshot("ide-page",(m,f)=>{if(m!==e)return;const g=new FileReader;g.onload=()=>i(g.result),g.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var m;return e?((m=ft.onStatus)==null?void 0:m.call(ft,(f,g)=>{f===e&&g!=null&&g.screenshotUsage&&l(g.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?ft.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?ft.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 gl="adhdev-dashboard-action-shortcuts",Fh=1200,Uh={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function zh(){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 yl(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 Ia(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function hn(e){const s=Object.fromEntries(yl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(gl)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Uh))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function vl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Vh({enabled:e=!0,onTrigger:s}){const r=zh(),[n,a]=o.useState(()=>hn(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(vl(d.key)),b.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(gl,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=hn(r),b=Object.entries(n),y=Object.entries(d);b.length===y.length&&b.every(([h,S])=>d[h]===S)||f(d)},[n,r,f]);const g=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),w=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},Fh))},[]);o.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),u([]);return}const y=m(b);if(!y)return;const S=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(l.length===0&&S){u([y]);return}const k=[...l,y].slice(0,2).join(" "),I={...n};for(const[j,v]of Object.entries(I))v===k&&delete I[j];I[i]=k,f(I),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 y=m(b);if(!y)return;const h=b.metaKey||b.ctrlKey||b.altKey;if(Ia(b.target)&&!h)return;const S=p.current.parts,_=h?[y]:[...S.slice(-1),y].slice(-2),k=_.join(" "),I=_[_.length-1],j=Object.entries(n).filter(([,M])=>!!M),v=j.find(([,M])=>M===k);if(v){b.preventDefault(),g(),s(v[0]);return}if(j.some(([,M])=>M.startsWith(`${k} `))){b.preventDefault(),p.current.parts=_,w();return}const E=j.find(([,M])=>M===I);if(E){b.preventDefault(),g(),s(E[0]);return}if(j.some(([,M])=>M.startsWith(`${I} `))){b.preventDefault(),p.current.parts=[I],w();return}g()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,w,e,m,s,g,i]),o.useEffect(()=>()=>g(),[g]);const A=o.useMemo(()=>yl(r),[r]);return{isMac:r,actionDefinitions:A,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:f}}function Gh({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):s?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function qh(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function vi({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!qh(n):!0}const wl=o.createContext(null);function An(){const e=o.useContext(wl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function sn(e){return lt(e)||e.tabKey}function Yh(e){return`remote:${e}`}function ts(e){return e.startsWith("remote:")}function wi(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Qn(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 Gr(e,s){e.classList.remove(ua.className,ma.className),e.classList.add(s==="light"?ua.className:ma.className)}function ji(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 Xh(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 Jh(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:sn(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 ki(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])ts(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!==sn(n)&&a.api.setTitle(sn(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:sn(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 Si(e,s,r){var u,p;const n=r?Yh(r):null;for(const m of[...e.panels])ts(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Wt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=Dc(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=>!ts(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 Qh({params:e,api:s}){var f;const r=An(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=kn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const g=[s.onDidActiveChange(w=>i(w.isActive)),s.onDidActiveGroupChange(w=>{if(!s.isActive&&!w.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const w of g)w.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(g=>g.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(g=>g.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(ho,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const m=!Ze(c)&&Hs(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(po,{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 Zh({params:e}){var u;const s=An(),r=o.useMemo(()=>Wt([...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}=bl({doId:a,targetSessionId:r?gc(r):(n==null?void 0:n.sessionId)||(n==null?void 0:n.instanceId),connState:(r==null?void 0:r.connectionState)||"new",viewMode:"remote"});return r?t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:t.jsx(ec,{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 ex(){const e=An();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(ho,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function tx(e){var w,A;Xh(e);const s=An(),r=o.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Wt([...s.conversationsByTabKey.values()],e.params.routeId),b=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,y=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${y?" 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=((A=e.api.group.activePanel)==null?void 0:A.id)===e.api.id,i=e.api.isGroupActive,c=wn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,m=c.isWaiting,f=c.unread,g=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:lt(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:lt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:hs(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:hs(n)}):t.jsx("span",{children:hs(n)})})]}),g&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:g,children:g})]})}function sx({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:g,registerActionHandlers:w,onActiveTabChange:A,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:y,scrollToBottomRequest:h,notificationStateBySessionId:S,liveSessionInboxState:_}){var Tt,ee,Re;const{theme:k}=so(),{sendCommand:I}=Pt(),j=o.useRef(null),v=o.useRef(null),x=o.useRef(!1),E=o.useRef(!1),L=o.useRef(!1),M=o.useRef(null),T=o.useRef([]),[B,H]=o.useState(null),[C,R]=o.useState(!1),[U,N]=o.useState(!1),[D,Y]=o.useState(0),q=o.useRef(null),W=o.useMemo(()=>rl(typeof window<"u"?window.innerWidth:1280),[]),ae=o.useRef(typeof window>"u"?{}:Ef(W)),ce=o.useMemo(()=>new Map(e.map(P=>[P.tabKey,P])),[e]),Se=o.useMemo(()=>{const P=j.current;return P?P.groups.some(O=>{try{const F=O.model.location.type;return F!=="floating"&&F!=="popout"?!1:O.panels.some(G=>ce.has(G.id))}catch{return!1}}):!1},[ce,D,e]),X=o.useCallback(()=>{var P;(P=j.current)==null||P.focus()},[]),he=o.useCallback(P=>{const O=document,F=P.document;for(const Ae of O.querySelectorAll('link[rel="stylesheet"]')){const We=F.createElement("link");We.rel="stylesheet",We.href=Ae.href,Ae.crossOrigin&&(We.crossOrigin=Ae.crossOrigin),F.head.appendChild(We)}for(const Ae of O.querySelectorAll("style")){const We=F.createElement("style");We.textContent=Ae.textContent,F.head.appendChild(We)}const G=[];for(const Ae of O.styleSheets)try{for(const We of Ae.cssRules)We instanceof CSSStyleRule&&(We.selectorText===":root"||We.selectorText==="html")&&G.push(We.cssText)}catch{}if(G.length>0){const Ae=F.createElement("style");Ae.textContent=G.join(`
|
|
44
|
+
`),F.head.appendChild(Ae)}const oe=O.documentElement.getAttribute("data-theme");oe&&F.documentElement.setAttribute("data-theme",oe),F.documentElement.style.colorScheme=oe==="light"?"light":"dark",F.body.className=O.body.className;const Ie=O.documentElement.getAttribute("style");Ie&&F.documentElement.setAttribute("style",Ie);const _e=F.getElementById("dv-popout-window");_e instanceof HTMLElement&&(_e.classList.add("adhdev-dockview"),Gr(_e,k))},[k]),J=o.useCallback(()=>{var O;const P=j.current;if(P)for(const F of P.groups)try{const G=(O=F.element)==null?void 0:O.ownerDocument;if(!G||G===document)continue;const oe=G.getElementById("dv-popout-window");oe instanceof HTMLElement&&(oe.classList.add("adhdev-dockview"),Gr(oe,k));const Ie=document.documentElement.getAttribute("data-theme");Ie&&G.documentElement.setAttribute("data-theme",Ie),G.documentElement.style.colorScheme=Ie==="light"?"light":"dark",G.body.className=document.body.className;const _e=document.documentElement.getAttribute("style");_e?G.documentElement.setAttribute("style",_e):G.documentElement.removeAttribute("style")}catch{}},[k]),Z=o.useCallback(()=>{var O;const P=j.current;if(P)for(const F of P.groups)try{const G=(O=F.element)==null?void 0:O.ownerDocument;if(!G||G===document)continue;const oe=G.getElementById("dv-popout-window");if(!(oe instanceof HTMLElement))continue;oe.classList.add("adhdev-dockview"),Gr(oe,k),oe.classList.toggle("is-showing-dockview-overlay",U),oe.classList.toggle("is-dragging-dockview",C)}catch{}},[C,U,k]),ue=o.useCallback(P=>{const O=j.current;if(!O)return;const F=O.getPanel(P);F&&O.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:G})=>{he(G),ke();const oe=ce.get(P);G.document.title=oe?`${lt(oe)} — ADHDev`:"ADHDev — Popout"}})},[ce,he]),de=o.useCallback(P=>{const O=j.current,F=O==null?void 0:O.getPanel(P);if(!O||!F)return;const G=O.groups.filter(oe=>{var Ie;try{return((Ie=oe.element)==null?void 0:Ie.ownerDocument)===document}catch{return!0}});G.length>0?F.api.moveTo({group:G[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),z=o.useCallback(P=>{var G;const O=j.current;if(!O)return!1;const F=O.getPanel(P);if(!F)return!1;try{return((G=F.group.element)==null?void 0:G.ownerDocument)!==document}catch{return!1}},[]),ye=o.useCallback(P=>{z(P)&&de(P),f(P)},[z,de,f]),ie=o.useCallback(P=>{const O=j.current,F=O==null?void 0:O.getPanel(P);!O||!F||O.addFloatingGroup(F,{width:600,height:500})},[]),le=o.useCallback(P=>{var F;const O=(F=j.current)==null?void 0:F.getPanel(P);if(!O)return!1;try{return O.group.model.location.type==="floating"}catch{return!1}},[]),se=o.useCallback(()=>{var O,F;const P=(F=(O=j.current)==null?void 0:O.activePanel)==null?void 0:F.id;return!P||ts(P)?null:ce.has(P)?P:null},[ce]),pe=o.useCallback(P=>{const O=j.current,F=O==null?void 0:O.getPanel(P);if(!O||!F)return;const G=O.groups.filter(oe=>{try{return oe.model.location.type==="grid"}catch{return!0}});G.length>0?F.api.moveTo({group:G[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),ne=o.useCallback(()=>{var Ie;const P=j.current;if(!P)return;const F=P.groups.filter(_e=>{var Ae;try{return((Ae=_e.element)==null?void 0:Ae.ownerDocument)===document&&_e.model.location.type==="grid"}catch{return!1}})[0]||null,G=[...P.panels];for(const _e of G){const Ae=(Ie=_e.group.element)==null?void 0:Ie.ownerDocument,We=_e.group.model.location.type;Ae===document&&We==="grid"||(F&&F.id!==_e.group.id?_e.api.moveTo({group:F,position:"center"}):_e.api.moveTo({position:"center"}))}const oe=P.activePanel;oe&&(oe.group.model.openPanel(oe),oe.api.setActive()),Qn(document)},[]),ke=o.useCallback(()=>{var O,F;const P=j.current;if(P)for(const G of P.groups){const oe=(O=G.element)==null?void 0:O.ownerDocument;if(!oe||oe===document)continue;const Ie=oe.getElementById("dv-popout-window");if(!(Ie instanceof HTMLElement))continue;let _e=null,Ae=oe.title||"ADHDev",We="Popout workspace";const De=G.activePanel;if(De)if(_e=De.id,ts(De.id)){const je=((F=De.params)==null?void 0:F.routeId)||De.id.slice(7),Be=Wt([...ce.values()],je);Ae=Dc(Be),We=Be!=null&&Be.machineName?`Remote view · ${Be.machineName}`:"Remote view"}else{const je=ce.get(De.id);Ae=je?lt(je):De.title||De.id,We=je?hs(je):"Dockview panel"}oe.title=`${Ae} — ADHDev`;let Je=oe.getElementById("adhdev-popout-header");Je instanceof HTMLElement||(Je=oe.createElement("div"),Je.id="adhdev-popout-header",oe.body.appendChild(Je)),Je.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(";")),Je.innerHTML=`
|
|
45
45
|
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
46
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;">${
|
|
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;">${
|
|
47
|
+
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${wi(Ae)}</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;">${wi(We)}</div>
|
|
49
49
|
</div>
|
|
50
50
|
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
51
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
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
53
|
</div>
|
|
54
|
-
`,Ie.style.top="52px",Ie.style.height="calc(100% - 52px)";const Ve=Je.querySelector("[data-adhdev-popout-focus]");Ve&&(Ve.onclick=()=>{window.focus()});const re=Je.querySelector("[data-adhdev-popout-dock]");re&&(re.disabled=!_e,re.style.opacity=_e?"1":"0.5",re.style.cursor=_e?"pointer":"default",re.onclick=()=>{var je;_e&&de(_e),(je=oe.defaultView)==null||je.focus()})}},[ce,de]),ve=o.useCallback(P=>{var G;const O=j.current,F=O==null?void 0:O.getPanel(P);if(!(!O||!F)){F.group.model.openPanel(F),F.api.setActive();try{const oe=F.group.model.location;oe.type==="popout"?oe.getWindow().focus():Qn((G=F.group.element)==null?void 0:G.ownerDocument)}catch{}}},[]),K=o.useCallback(P=>{const O=j.current,F=O==null?void 0:O.activePanel,G=(O==null?void 0:O.activeGroup)||(F==null?void 0:F.group);if(!O||!F||!G)return;const oe=G.panels||[];if(oe.length<=1)return;const Ie=oe.findIndex(We=>We.id===F.id);if(Ie<0)return;const _e=(Ie+P+oe.length)%oe.length,Ae=oe[_e];Ae&&(Ae.group.model.openPanel(Ae),Ae.api.setActive())},[]),V=o.useCallback(P=>{var re;const O=j.current,F=(O==null?void 0:O.activeGroup)||((re=O==null?void 0:O.activePanel)==null?void 0:re.group);if(!O||!F)return;const G=O.groups||[],oe=G.find(je=>je.id===F.id);if(!oe)return;const Ie=oe.element.getBoundingClientRect(),_e=Ie.left+Ie.width/2,Ae=Ie.top+Ie.height/2,We=(je,Be,rt,$)=>Math.max(0,Math.min(Be,$)-Math.max(je,rt)),De=je=>{const Be=je.element.getBoundingClientRect(),rt=Be.left+Be.width/2,$=Be.top+Be.height/2;let te=0,fe=0,Ee=0,Le=!1;if(P==="left"?(Le=rt<_e,te=Math.max(0,Ie.left-Be.right),fe=Math.abs($-Ae),Ee=We(Ie.top,Ie.bottom,Be.top,Be.bottom)):P==="right"?(Le=rt>_e,te=Math.max(0,Be.left-Ie.right),fe=Math.abs($-Ae),Ee=We(Ie.top,Ie.bottom,Be.top,Be.bottom)):P==="above"?(Le=$<Ae,te=Math.max(0,Ie.top-Be.bottom),fe=Math.abs(rt-_e),Ee=We(Ie.left,Ie.right,Be.left,Be.right)):(Le=$>Ae,te=Math.max(0,Be.top-Ie.bottom),fe=Math.abs(rt-_e),Ee=We(Ie.left,Ie.right,Be.left,Be.right)),!Le)return Number.POSITIVE_INFINITY;const Ne=Ee>0?0:120;return te*3+fe+Ne};let Je=null,Ve=Number.POSITIVE_INFINITY;for(const je of G){if(je.id===oe.id)continue;const Be=De(je);Number.isFinite(Be)&&(Be>=Ve||(Ve=Be,Je=je))}return Je||void 0},[]),we=o.useCallback(P=>{var G;const O=V(P);if(!O)return;const F=O.activePanel||O.panels[0];F&&(O.model.openPanel(F),F.api.setActive(),Qn((G=O.element)==null?void 0:G.ownerDocument))},[V]),be=o.useCallback((P,O)=>{const F=j.current,G=F==null?void 0:F.activePanel,oe=(F==null?void 0:F.activeGroup)||(G==null?void 0:G.group);if(!F||!G||!oe)return;let Ie=V(P);!Ie&&(O!=null&&O.createGroupIfMissing)&&(Ie=F.addGroup({referenceGroup:oe,direction:P})),Ie&&(G.api.moveTo({group:Ie,position:"center"}),G.group.model.openPanel(G),G.api.setActive())},[V]),{isMac:Q,tabShortcuts:Me,shortcutListening:Oe,setShortcutListening:Pe,saveShortcuts:Ke}=hl({sortedTabKeys:e.map(P=>P.tabKey),onFocus:X,onSelectTab:ve}),Qe=o.useCallback(()=>{var F;const P=j.current;if(!P)return;const O=P.activePanel;if(O){if(ts(O.id)){const G=((F=O.params)==null?void 0:F.routeId)||O.id.slice(7),oe=Wt(e,G);oe!=null&&oe.tabKey&&Pe(oe.tabKey);return}ce.has(O.id)&&Pe(O.id)}},[ce,ve,Pe,e]),Ge=o.useCallback(P=>{const O=[];return P.metaKey&&O.push(Q?"⌘":"Meta"),P.ctrlKey&&O.push("Ctrl"),P.altKey&&O.push(Q?"⌥":"Alt"),P.shiftKey&&P.key.length!==1&&O.push(Q?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(P.key)?null:(O.push(yl(P.key)),O.join("+"))},[Q]),ut=o.useCallback(P=>{var O,F;switch(P){case"splitActiveTabRight":be("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":be("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const G=se();G&&ie(G);return}case"popoutActiveTab":{const G=se();G&&ue(G);return}case"dockActiveTab":{const G=se();if(!G)return;z(G)?de(G):le(G)&&pe(G);return}case"focusLeftPane":we("left");return;case"focusRightPane":we("right");return;case"focusUpPane":we("above");return;case"focusDownPane":we("below");return;case"moveActiveTabToLeftPane":be("left");return;case"moveActiveTabToRightPane":be("right");return;case"moveActiveTabToUpPane":be("above");return;case"moveActiveTabToDownPane":be("below");return;case"selectPreviousGroupTab":K(-1);return;case"selectNextGroupTab":K(1);return;case"setActiveTabShortcut":Qe();return;case"hideCurrentTab":{const G=(F=(O=j.current)==null?void 0:O.activePanel)==null?void 0:F.id;G&&!ts(G)&&ye(G);return}default:return}},[K,pe,we,ie,se,ye,le,z,de,be,ue,Qe]);o.useEffect(()=>{if(!B)return;const P=B.sourceDocument,O=P.defaultView??window,F=G=>{const oe=P.querySelector("[data-dockview-tab-context-menu]");oe&&oe.contains(G.target)||H(null)};return O.addEventListener("mousedown",F,!0),O!==window&&window.addEventListener("mousedown",()=>H(null),!0),()=>{O.removeEventListener("mousedown",F,!0),O!==window&&window.removeEventListener("mousedown",()=>H(null),!0)}},[B]);const it=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:ce,hasDetachedConversationPanels:Se,ides:r,isStandalone:l,hasRegisteredMachines:u,liveSessionInboxState:_,notificationStateBySessionId:S,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:ye,userName:m,scrollToBottomRequest:h,tabShortcuts:Me,openTabContextMenu:({x:P,y:O,tabKey:F,sourceDocument:G})=>H({x:P,y:O,tabKey:F,sourceDocument:G??document}),popoutTab:ue,moveTabBackToMain:de,isTabInPopout:z,floatTab:ie,isTabFloating:le}),[n,s,ce,Se,r,l,u,_,S,a,c,i,ye,m,h,Me,ue,de,z,ie,le]),ht=B?Fh({isTabInPopout:z(B.tabKey),isTabFloating:le(B.tabKey),tabShortcut:Me[B.tabKey],actionShortcuts:g}):[],ze=o.useCallback(P=>{var G;const O=j.current;if((((G=O==null?void 0:O.activePanel)==null?void 0:G.id)??null)===P.id){P.group.model.openPanel(P);return}P.group.model.openPanel(P),P.api.setActive()},[]),xt=o.useCallback(P=>{if(!P)return!1;const O=j.current;if(!O)return!1;const F=O.getPanel(P);return F?(ze(F),y==null||y(),!0):!1},[ze,y]),bt=o.useCallback(()=>{if(L.current)return!1;const P=xt(M.current);return P&&(L.current=!0),P},[xt]),ct=o.useCallback(()=>{var O;const P=j.current;P&&Lf(W,{activeTabId:((O=P.activePanel)==null?void 0:O.id)??null,layout:P.toJSON()})},[W]),Te=o.useCallback(()=>{Rf(W,ae.current)},[W]),Xe=o.useCallback(P=>{var G,oe,Ie,_e;const O=j.current;if(!O)return{kind:"grid"};const F=O.toJSON();for(const Ae of F.floatingGroups||[])if((oe=(G=Ae.data)==null?void 0:G.views)!=null&&oe.includes(P)&&Ae.position)return{kind:"floating",position:Ae.position};for(const Ae of F.popoutGroups||[])if((_e=(Ie=Ae.data)==null?void 0:Ie.views)!=null&&_e.includes(P))return{kind:"popout",position:Ae.position,popoutUrl:Ae.url};return{kind:"grid"}},[]),Fe=o.useCallback(P=>{const O=j.current;if(!O)return;const F=O.getPanel(P),G=ae.current[P];if(!F||!G||G.kind==="grid")return;if(F.group.model.location.type===G.kind){delete ae.current[P],Te();return}if(G.kind==="floating"){O.addFloatingGroup(F,{x:G.position.left??24,y:G.position.top??24,width:G.position.width,height:G.position.height}),delete ae.current[P],Te();return}delete ae.current[P],Te()},[Te]);o.useEffect(()=>(w==null||w({setShortcutForActiveTab:Qe,restoreHiddenTabToSavedLocation:Fe,activateConversationTab:ve,resetAllPanelsToMain:ne,activatePreviousTabInGroup:()=>K(-1),activateNextTabInGroup:()=>K(1),floatActiveTab:()=>{const P=se();P&&ie(P)},popoutActiveTab:()=>{const P=se();P&&ue(P)},dockActiveTab:()=>{const P=se();P&&(z(P)?de(P):le(P)&&pe(P))},splitActiveTabRight:()=>be("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>be("below",{createGroupIfMissing:!0}),focusLeftPane:()=>we("left"),focusRightPane:()=>we("right"),focusUpPane:()=>we("above"),focusDownPane:()=>we("below"),moveActiveTabToLeftPane:()=>be("left"),moveActiveTabToRightPane:()=>be("right"),moveActiveTabToUpPane:()=>be("above"),moveActiveTabToDownPane:()=>be("below")}),()=>w==null?void 0:w(null)),[K,pe,ie,we,se,le,z,be,de,ue,w,ne,Fe,ve,Qe]);const Ue=o.useCallback(()=>{const P=v.current;if(!P)return;const O=P.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const F of O)F.setAttribute("data-adhdev-force-hidden","true")},[]),kt=o.useCallback(()=>{const P=v.current;if(!P)return;const O=P.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of O)F.removeAttribute("data-adhdev-force-hidden")},[]),yt=o.useCallback(()=>{const P=v.current;if(!P)return;const O=P.querySelectorAll(".dv-drop-target-container");for(const oe of O)oe.remove();const F=P.querySelectorAll(".dv-drop-target-dropzone");for(const oe of F)oe.remove();const G=P.querySelectorAll(".dv-drop-target");for(const oe of G)oe.classList.remove("dv-drop-target")},[]),wt=o.useCallback(()=>{R(!1),N(!1),kt(),Ue(),yt(),!(typeof window>"u")&&(q.current!=null&&window.clearTimeout(q.current),window.requestAnimationFrame(()=>{Ue(),yt()}),q.current=window.setTimeout(()=>{Ue(),yt(),q.current=null},80))},[kt,Ue,yt]),St=o.useCallback(P=>{var F;j.current=P.api;const O=Tf(W);if(M.current=(O==null?void 0:O.activeTabId)??null,O!=null&&O.layout&&P.api.fromJSON(O.layout,{reuseExistingPanels:!1}),E.current=yi({hasStoredLayout:!!(O!=null&&O.layout),initialDataLoaded:p,visibleConversationCount:e.length,ides:r}),E.current||(ji(P.api,e),ki(P.api,e,b)),P.api.totalPanels===0&&e.length>0){const G=Gh(P.api,e,d);if(G){const oe=P.api.getPanel(G);oe&&ze(oe)}}else!E.current&&!xt(d)&&bt();x.current=!0,P.api.onDidActivePanelChange(G=>{var Ie;if(M.current=(G==null?void 0:G.id)??null,L.current=!0,ke(),G&&ts(G.id)){const _e=((Ie=G.params)==null?void 0:Ie.routeId)||G.id.slice(7),Ae=Wt(e,_e);A((Ae==null?void 0:Ae.tabKey)??null),ct();return}if(A((G==null?void 0:G.id)??null),ct(),!G)return;const oe=ce.get(G.id);(oe==null?void 0:oe.streamSource)==="agent-stream"&&oe.agentType&&I(oe.routeId,il(),{agentType:oe.agentType,...oe.sessionId&&{targetSessionId:oe.sessionId}}).catch(()=>{})}),P.api.onDidLayoutChange(()=>{ct(),ke(),Y(G=>G+1)}),P.api.onWillDragPanel(()=>{R(!0),N(!1),Ue()}),P.api.onWillDragGroup(()=>{R(!0),N(!1),Ue()}),P.api.onWillShowOverlay(()=>{kt(),N(!0)}),P.api.onDidMovePanel(wt),P.api.onDidDrop(wt),P.api.onDidAddGroup(G=>{requestAnimationFrame(()=>{var oe,Ie;try{const _e=(oe=G.element)==null?void 0:oe.ownerDocument;if(!_e||_e===document)return;(Ie=_e.getElementById("dv-popout-window"))==null||Ie.classList.add("adhdev-dockview");const Ae=document.documentElement.getAttribute("data-theme");Ae&&_e.documentElement.setAttribute("data-theme",Ae),_e.body.className=document.body.className;const We=document.documentElement.getAttribute("style");We&&_e.documentElement.setAttribute("style",We)}catch{}ke(),Y(_e=>_e+1)})}),A(((F=P.api.activePanel)==null?void 0:F.id)??null)},[ze,xt,wt,kt,ce,r,p,W,Ue,A,ct,d,b,I,ke,e]);o.useLayoutEffect(()=>{const P=j.current;if(!P||!x.current||E.current&&yi({hasStoredLayout:!0,initialDataLoaded:p,visibleConversationCount:e.length,ides:r}))return;E.current&&(E.current=!1);const O=T.current,F=new Set(O),G=e.map(De=>De.tabKey),oe=new Set(G);let Ie=!1;for(const De of O)oe.has(De)||(ae.current[De]=Xe(De),Ie=!0);Ie&&Te(),ji(P,e),ki(P,e,b);const _e=G.filter(De=>!F.has(De));let Ae=!1;for(const De of _e){const Je=P.getPanel(De),Ve=ae.current[De];if(!Je||!Ve||Ve.kind==="grid")continue;if(Je.group.model.location.type===Ve.kind){delete ae.current[De],Ae=!0;continue}if(Ve.kind==="floating"){P.addFloatingGroup(Je,{x:Ve.position.left??24,y:Ve.position.top??24,width:Ve.position.width,height:Ve.position.height}),delete ae.current[De],Ae=!0;continue}}if(Ae&&Te(),T.current=G,d&&xt(d))return;!P.activePanel&&P.panels[0]&&ze(P.panels[0]),!!(P.activePanel&&P.getPanel(P.activePanel.id))||bt()},[ze,xt,bt,r,p,Te,Xe,d,b,e]),o.useEffect(()=>{x.current&&xt(d)},[xt,d]),o.useEffect(()=>{if(!C||typeof window>"u")return;const P=()=>wt();return window.addEventListener("pointerup",P),window.addEventListener("mouseup",P),window.addEventListener("dragend",P),()=>{window.removeEventListener("pointerup",P),window.removeEventListener("mouseup",P),window.removeEventListener("dragend",P)}},[wt,C]),o.useEffect(()=>()=>{typeof window>"u"||q.current!=null&&window.clearTimeout(q.current)},[]),o.useEffect(()=>{const P=F=>{const G=F.target;if(!G)return;const oe=G.querySelector("[data-tab-key]")||G.closest("[data-tab-key]");if(oe){const Ie=oe.getAttribute("data-tab-key");if(Ie&&F.dataTransfer){const _e=G.closest(".dv-tab")||oe.closest(".dv-tab")||oe;F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/tab-key",Ie),_e instanceof HTMLElement&&F.dataTransfer.setDragImage(_e,Math.max(12,Math.round(_e.clientWidth/2)),Math.max(10,Math.round(_e.clientHeight/2)))}}};window.addEventListener("dragstart",P);const O=wi(j.current);for(const F of O)F.addEventListener("dragstart",P);return()=>{window.removeEventListener("dragstart",P);for(const F of O)F.removeEventListener("dragstart",P)}},[D]),o.useEffect(()=>{var O;const P=(O=v.current)==null?void 0:O.querySelector(".adhdev-dockview");P instanceof HTMLElement&&Gr(P,k),J(),ke(),Z()},[ke,Z,J,k]),o.useEffect(()=>{ke(),Z()},[ke,Z]),o.useEffect(()=>{const P=O=>{if(O.defaultPrevented||Oe)return;const F=Ge(O);if(!F)return;const G=O.metaKey||O.ctrlKey||O.altKey;Ia(O.target)&&!G||hn(Q).setActiveTabShortcut!==F||(O.preventDefault(),O.stopPropagation(),Qe())};return window.addEventListener("keydown",P,!0),()=>window.removeEventListener("keydown",P,!0)},[Ge,Q,Oe,Qe]),o.useEffect(()=>{const P=v.current;if(!P)return;const O=F=>{var Ae,We;if(!F.isTrusted)return;const G=(We=(Ae=F.target)==null?void 0:Ae.closest)==null?void 0:We.call(Ae,".dv-scrollable");if(!G)return;F.preventDefault(),F.stopPropagation();const oe=Math.abs(F.deltaX),Ie=Math.abs(F.deltaY),_e=oe>Ie?F.deltaX:F.deltaY;G.dispatchEvent(new WheelEvent("wheel",{deltaY:_e,deltaMode:F.deltaMode,bubbles:!1,cancelable:!0}))};return P.addEventListener("wheel",O,{passive:!1,capture:!0}),()=>P.removeEventListener("wheel",O,{capture:!0})},[]),o.useEffect(()=>{const P=wi(j.current);if(P.length===0)return;const O=P.map(F=>{let G=[],oe=null;const Ie=()=>{oe!=null&&F.clearTimeout(oe),oe=null,G=[]},_e=()=>{oe!=null&&F.clearTimeout(oe),oe=F.setTimeout(()=>{oe=null,G=[]},1200)},Ae=De=>{if(!De.ctrlKey&&!De.metaKey&&!De.altKey)return;const Je=Ge(De);if(!Je)return;const Ve=fl();for(const[re,je]of Object.entries(Ve))if(e.some(Be=>Be.tabKey===re)&&je===Je){De.preventDefault(),ve(re);return}},We=De=>{if(De.defaultPrevented||Oe)return;const Je=Ge(De);if(!Je)return;const Ve=De.metaKey||De.ctrlKey||De.altKey;if(Ia(De.target)&&!Ve)return;const re=hn(Q),je=Object.entries(re).filter(([Ne,et])=>!!et&&(Ne==="splitActiveTabRight"||Ne==="splitActiveTabDown"||Ne==="floatActiveTab"||Ne==="popoutActiveTab"||Ne==="dockActiveTab"||Ne==="focusLeftPane"||Ne==="focusRightPane"||Ne==="focusUpPane"||Ne==="focusDownPane"||Ne==="moveActiveTabToLeftPane"||Ne==="moveActiveTabToRightPane"||Ne==="moveActiveTabToUpPane"||Ne==="moveActiveTabToDownPane"||Ne==="selectPreviousGroupTab"||Ne==="selectNextGroupTab"||Ne==="setActiveTabShortcut"||Ne==="hideCurrentTab")),Be=Ve?[Je]:[...G.slice(-1),Je].slice(-2),rt=Be.join(" "),$=Be[Be.length-1],te=je.find(([,Ne])=>Ne===rt);if(te){De.preventDefault(),Ie(),ut(te[0]);return}if(je.some(([,Ne])=>Ne.startsWith(`${rt} `))){De.preventDefault(),G=Be,_e();return}const Ee=je.find(([,Ne])=>Ne===$);if(Ee){De.preventDefault(),Ie(),ut(Ee[0]);return}if(je.some(([,Ne])=>Ne.startsWith(`${$} `))){De.preventDefault(),G=[$],_e();return}Ie()};return F.addEventListener("keydown",Ae),F.addEventListener("keydown",We),()=>{Ie(),F.removeEventListener("keydown",Ae),F.removeEventListener("keydown",We)}});return()=>{for(const F of O)F()}},[Ge,Q,D,ve,Oe,ut,e]);const Ht=k==="light"?ua:ma,Mt=((Re=(ee=(Tt=j.current)==null?void 0:Tt.activePanel)==null?void 0:ee.group.element)==null?void 0:Re.ownerDocument)??document;return t.jsxs(vl.Provider,{value:it,children:[t.jsx("div",{ref:v,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(pd,{className:`h-full min-h-0 min-w-0 adhdev-dockview${C?" is-dragging-dockview":""}${U?" is-showing-dockview-overlay":""}`,components:{conversation:qh,remote:Yh},defaultTabComponent:Jh,watermarkComponent:Xh,onReady:St,singleTabMode:"default",tabAnimation:"smooth",theme:Ht,popoutUrl:"/popout.html"})}),B&&pr.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:B.x,top:B.y},children:ht.map(P=>{if(P.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},P.id);let O=t.jsx(eu,{size:13,className:"shrink-0 opacity-70"}),F=()=>{};switch(P.id){case"dockInWindow":case"dockBackToGrid":O=t.jsx(su,{size:13,className:"shrink-0 opacity-70"}),F=()=>{pe(B.tabKey),H(null)};break;case"moveBackToMain":O=t.jsx(Zd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{de(B.tabKey),H(null)};break;case"floatAsPanel":O=t.jsx(tu,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ie(B.tabKey),H(null)};break;case"openInNewWindow":O=t.jsx(Qd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ue(B.tabKey),H(null)};break;case"setShortcut":F=G=>{G.stopPropagation(),Pe(B.tabKey),H(null)};break;case"removeShortcut":O=t.jsx(At,{size:13,className:"shrink-0 opacity-70"}),F=()=>{const G={...Me};delete G[B.tabKey],Ke(G),H(null)};break;case"hideTab":O=t.jsx(qi,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ye(B.tabKey),H(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 ${P.tone==="muted"?"text-text-muted":""}`,onClick:F,children:[O,t.jsx("span",{className:"flex-1 min-w-0",children:P.label}),P.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:P.shortcut}):null]},P.id)})}),B.sourceDocument.body),Oe&&pr.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:()=>Pe(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.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"})]})}),Mt.body)]})}const wl="adhdev-recent-launch-args-v1",Zh=8;function ex(e){return String(e||"").trim().replace(/\s+/g," ")}function jl(e,s){return`${e.trim()}::${s.trim()}`}function kl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(wl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function tx(e){if(!(typeof window>"u"))try{window.localStorage.setItem(wl,JSON.stringify(e))}catch{}}function Sl(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=kl().byKey[jl(r,n)])==null?void 0:i.items)||[]}function Nl(e,s,r){var m;const n=String(e||"").trim(),a=String(s||"").trim(),i=ex(r);if(!n||!a||!i)return;const c=kl(),l=jl(n,a),u=((m=c.byKey[l])==null?void 0:m.items)||[],p=[i,...u.filter(f=>f!==i)].slice(0,Zh);c.byKey[l]={items:p},tx(c)}function sx(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 xo(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 Cl(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=xo((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 Il(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function $s(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function Zn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function rx(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Si(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function Ni(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 nx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function ax(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 ox(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 ix({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:a,onOpenConversation:i,onClose:c}){var U;const[l,u]=o.useState(n||((U=e[0])==null?void 0:U.id)||null),[p,m]=o.useState(""),[f,g]=o.useState(null),[w,A]=o.useState(!1);o.useEffect(()=>{var N;u(n||((N=e[0])==null?void 0:N.id)||null)},[n,e]);const d=o.useMemo(()=>e.find(N=>N.id===l)||e[0]||null,[l,e]),b=o.useMemo(()=>r.filter(N=>{if(N.type==="adhdev-daemon"||N.transport!=="pty")return!1;const D=rx(N.daemonId||N.id);return!!(d!=null&&d.id)&&D===d.id}),[d==null?void 0:d.id,r]),y=Jc(d==null?void 0:d.id,{enabled:!!(d!=null&&d.id),includeSessions:!0,limit:6,intervalMs:1e4}),h=y.diagnostics,S=y.loading,_=y.applyDiagnostics,k=o.useMemo(()=>{const N=new Map;for(const D of b){const Y=s.find(q=>q.sessionId===D.sessionId||q.routeId===D.id);D.sessionId&&Y&&N.set(D.sessionId,Y)}return N},[b,s]),I=o.useCallback(async()=>{if(d!=null&&d.id){A(!0);try{const N=await a(d.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),D=Zn(N);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Could not load hosted runtime diagnostics");_(D.diagnostics||D.result||null),m("")}catch(N){const D=N instanceof Error?N.message:"Could not load hosted runtime diagnostics";m(D)}finally{A(!1)}}},[d==null?void 0:d.id,_,a]);o.useEffect(()=>{!(d!=null&&d.id)||h||S||w||I()},[d==null?void 0:d.id,h,S,I,w]);const j=o.useCallback(async(N,D)=>{if(!(d!=null&&d.id)||N==="session_host_stop_session"&&!window.confirm(`Stop ${D.displayName}?
|
|
54
|
+
`,Ie.style.top="52px",Ie.style.height="calc(100% - 52px)";const Ve=Je.querySelector("[data-adhdev-popout-focus]");Ve&&(Ve.onclick=()=>{window.focus()});const re=Je.querySelector("[data-adhdev-popout-dock]");re&&(re.disabled=!_e,re.style.opacity=_e?"1":"0.5",re.style.cursor=_e?"pointer":"default",re.onclick=()=>{var je;_e&&de(_e),(je=oe.defaultView)==null||je.focus()})}},[ce,de]),ve=o.useCallback(P=>{var G;const O=j.current,F=O==null?void 0:O.getPanel(P);if(!(!O||!F)){F.group.model.openPanel(F),F.api.setActive();try{const oe=F.group.model.location;oe.type==="popout"?oe.getWindow().focus():Qn((G=F.group.element)==null?void 0:G.ownerDocument)}catch{}}},[]),K=o.useCallback(P=>{const O=j.current,F=O==null?void 0:O.activePanel,G=(O==null?void 0:O.activeGroup)||(F==null?void 0:F.group);if(!O||!F||!G)return;const oe=G.panels||[];if(oe.length<=1)return;const Ie=oe.findIndex(We=>We.id===F.id);if(Ie<0)return;const _e=(Ie+P+oe.length)%oe.length,Ae=oe[_e];Ae&&(Ae.group.model.openPanel(Ae),Ae.api.setActive())},[]),V=o.useCallback(P=>{var re;const O=j.current,F=(O==null?void 0:O.activeGroup)||((re=O==null?void 0:O.activePanel)==null?void 0:re.group);if(!O||!F)return;const G=O.groups||[],oe=G.find(je=>je.id===F.id);if(!oe)return;const Ie=oe.element.getBoundingClientRect(),_e=Ie.left+Ie.width/2,Ae=Ie.top+Ie.height/2,We=(je,Be,rt,$)=>Math.max(0,Math.min(Be,$)-Math.max(je,rt)),De=je=>{const Be=je.element.getBoundingClientRect(),rt=Be.left+Be.width/2,$=Be.top+Be.height/2;let te=0,fe=0,Ee=0,Le=!1;if(P==="left"?(Le=rt<_e,te=Math.max(0,Ie.left-Be.right),fe=Math.abs($-Ae),Ee=We(Ie.top,Ie.bottom,Be.top,Be.bottom)):P==="right"?(Le=rt>_e,te=Math.max(0,Be.left-Ie.right),fe=Math.abs($-Ae),Ee=We(Ie.top,Ie.bottom,Be.top,Be.bottom)):P==="above"?(Le=$<Ae,te=Math.max(0,Ie.top-Be.bottom),fe=Math.abs(rt-_e),Ee=We(Ie.left,Ie.right,Be.left,Be.right)):(Le=$>Ae,te=Math.max(0,Be.top-Ie.bottom),fe=Math.abs(rt-_e),Ee=We(Ie.left,Ie.right,Be.left,Be.right)),!Le)return Number.POSITIVE_INFINITY;const Ne=Ee>0?0:120;return te*3+fe+Ne};let Je=null,Ve=Number.POSITIVE_INFINITY;for(const je of G){if(je.id===oe.id)continue;const Be=De(je);Number.isFinite(Be)&&(Be>=Ve||(Ve=Be,Je=je))}return Je||void 0},[]),we=o.useCallback(P=>{var G;const O=V(P);if(!O)return;const F=O.activePanel||O.panels[0];F&&(O.model.openPanel(F),F.api.setActive(),Qn((G=O.element)==null?void 0:G.ownerDocument))},[V]),be=o.useCallback((P,O)=>{const F=j.current,G=F==null?void 0:F.activePanel,oe=(F==null?void 0:F.activeGroup)||(G==null?void 0:G.group);if(!F||!G||!oe)return;let Ie=V(P);!Ie&&(O!=null&&O.createGroupIfMissing)&&(Ie=F.addGroup({referenceGroup:oe,direction:P})),Ie&&(G.api.moveTo({group:Ie,position:"center"}),G.group.model.openPanel(G),G.api.setActive())},[V]),{isMac:Q,tabShortcuts:Me,shortcutListening:Oe,setShortcutListening:Pe,saveShortcuts:Ke}=xl({sortedTabKeys:e.map(P=>P.tabKey),onFocus:X,onSelectTab:ve}),Qe=o.useCallback(()=>{var F;const P=j.current;if(!P)return;const O=P.activePanel;if(O){if(ts(O.id)){const G=((F=O.params)==null?void 0:F.routeId)||O.id.slice(7),oe=Wt(e,G);oe!=null&&oe.tabKey&&Pe(oe.tabKey);return}ce.has(O.id)&&Pe(O.id)}},[ce,ve,Pe,e]),Ge=o.useCallback(P=>{const O=[];return P.metaKey&&O.push(Q?"⌘":"Meta"),P.ctrlKey&&O.push("Ctrl"),P.altKey&&O.push(Q?"⌥":"Alt"),P.shiftKey&&P.key.length!==1&&O.push(Q?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(P.key)?null:(O.push(vl(P.key)),O.join("+"))},[Q]),ut=o.useCallback(P=>{var O,F;switch(P){case"splitActiveTabRight":be("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":be("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const G=se();G&&ie(G);return}case"popoutActiveTab":{const G=se();G&&ue(G);return}case"dockActiveTab":{const G=se();if(!G)return;z(G)?de(G):le(G)&&pe(G);return}case"focusLeftPane":we("left");return;case"focusRightPane":we("right");return;case"focusUpPane":we("above");return;case"focusDownPane":we("below");return;case"moveActiveTabToLeftPane":be("left");return;case"moveActiveTabToRightPane":be("right");return;case"moveActiveTabToUpPane":be("above");return;case"moveActiveTabToDownPane":be("below");return;case"selectPreviousGroupTab":K(-1);return;case"selectNextGroupTab":K(1);return;case"setActiveTabShortcut":Qe();return;case"hideCurrentTab":{const G=(F=(O=j.current)==null?void 0:O.activePanel)==null?void 0:F.id;G&&!ts(G)&&ye(G);return}default:return}},[K,pe,we,ie,se,ye,le,z,de,be,ue,Qe]);o.useEffect(()=>{if(!B)return;const P=B.sourceDocument,O=P.defaultView??window,F=G=>{const oe=P.querySelector("[data-dockview-tab-context-menu]");oe&&oe.contains(G.target)||H(null)};return O.addEventListener("mousedown",F,!0),O!==window&&window.addEventListener("mousedown",()=>H(null),!0),()=>{O.removeEventListener("mousedown",F,!0),O!==window&&window.removeEventListener("mousedown",()=>H(null),!0)}},[B]);const it=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:ce,hasDetachedConversationPanels:Se,ides:r,isStandalone:l,hasRegisteredMachines:u,liveSessionInboxState:_,notificationStateBySessionId:S,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:ye,userName:m,scrollToBottomRequest:h,tabShortcuts:Me,openTabContextMenu:({x:P,y:O,tabKey:F,sourceDocument:G})=>H({x:P,y:O,tabKey:F,sourceDocument:G??document}),popoutTab:ue,moveTabBackToMain:de,isTabInPopout:z,floatTab:ie,isTabFloating:le}),[n,s,ce,Se,r,l,u,_,S,a,c,i,ye,m,h,Me,ue,de,z,ie,le]),ht=B?Gh({isTabInPopout:z(B.tabKey),isTabFloating:le(B.tabKey),tabShortcut:Me[B.tabKey],actionShortcuts:g}):[],ze=o.useCallback(P=>{var G;const O=j.current;if((((G=O==null?void 0:O.activePanel)==null?void 0:G.id)??null)===P.id){P.group.model.openPanel(P);return}P.group.model.openPanel(P),P.api.setActive()},[]),xt=o.useCallback(P=>{if(!P)return!1;const O=j.current;if(!O)return!1;const F=O.getPanel(P);return F?(ze(F),y==null||y(),!0):!1},[ze,y]),bt=o.useCallback(()=>{if(L.current)return!1;const P=xt(M.current);return P&&(L.current=!0),P},[xt]),ct=o.useCallback(()=>{var O;const P=j.current;P&&Df(W,{activeTabId:((O=P.activePanel)==null?void 0:O.id)??null,layout:P.toJSON()})},[W]),Te=o.useCallback(()=>{$f(W,ae.current)},[W]),Xe=o.useCallback(P=>{var G,oe,Ie,_e;const O=j.current;if(!O)return{kind:"grid"};const F=O.toJSON();for(const Ae of F.floatingGroups||[])if((oe=(G=Ae.data)==null?void 0:G.views)!=null&&oe.includes(P)&&Ae.position)return{kind:"floating",position:Ae.position};for(const Ae of F.popoutGroups||[])if((_e=(Ie=Ae.data)==null?void 0:Ie.views)!=null&&_e.includes(P))return{kind:"popout",position:Ae.position,popoutUrl:Ae.url};return{kind:"grid"}},[]),Fe=o.useCallback(P=>{const O=j.current;if(!O)return;const F=O.getPanel(P),G=ae.current[P];if(!F||!G||G.kind==="grid")return;if(F.group.model.location.type===G.kind){delete ae.current[P],Te();return}if(G.kind==="floating"){O.addFloatingGroup(F,{x:G.position.left??24,y:G.position.top??24,width:G.position.width,height:G.position.height}),delete ae.current[P],Te();return}delete ae.current[P],Te()},[Te]);o.useEffect(()=>(w==null||w({setShortcutForActiveTab:Qe,restoreHiddenTabToSavedLocation:Fe,activateConversationTab:ve,resetAllPanelsToMain:ne,activatePreviousTabInGroup:()=>K(-1),activateNextTabInGroup:()=>K(1),floatActiveTab:()=>{const P=se();P&&ie(P)},popoutActiveTab:()=>{const P=se();P&&ue(P)},dockActiveTab:()=>{const P=se();P&&(z(P)?de(P):le(P)&&pe(P))},splitActiveTabRight:()=>be("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>be("below",{createGroupIfMissing:!0}),focusLeftPane:()=>we("left"),focusRightPane:()=>we("right"),focusUpPane:()=>we("above"),focusDownPane:()=>we("below"),moveActiveTabToLeftPane:()=>be("left"),moveActiveTabToRightPane:()=>be("right"),moveActiveTabToUpPane:()=>be("above"),moveActiveTabToDownPane:()=>be("below")}),()=>w==null?void 0:w(null)),[K,pe,ie,we,se,le,z,be,de,ue,w,ne,Fe,ve,Qe]);const Ue=o.useCallback(()=>{const P=v.current;if(!P)return;const O=P.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const F of O)F.setAttribute("data-adhdev-force-hidden","true")},[]),kt=o.useCallback(()=>{const P=v.current;if(!P)return;const O=P.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of O)F.removeAttribute("data-adhdev-force-hidden")},[]),yt=o.useCallback(()=>{const P=v.current;if(!P)return;const O=P.querySelectorAll(".dv-drop-target-container");for(const oe of O)oe.remove();const F=P.querySelectorAll(".dv-drop-target-dropzone");for(const oe of F)oe.remove();const G=P.querySelectorAll(".dv-drop-target");for(const oe of G)oe.classList.remove("dv-drop-target")},[]),wt=o.useCallback(()=>{R(!1),N(!1),kt(),Ue(),yt(),!(typeof window>"u")&&(q.current!=null&&window.clearTimeout(q.current),window.requestAnimationFrame(()=>{Ue(),yt()}),q.current=window.setTimeout(()=>{Ue(),yt(),q.current=null},80))},[kt,Ue,yt]),St=o.useCallback(P=>{var F;j.current=P.api;const O=Pf(W);if(M.current=(O==null?void 0:O.activeTabId)??null,O!=null&&O.layout&&P.api.fromJSON(O.layout,{reuseExistingPanels:!1}),E.current=vi({hasStoredLayout:!!(O!=null&&O.layout),initialDataLoaded:p,visibleConversationCount:e.length,ides:r}),E.current||(ki(P.api,e),Si(P.api,e,b)),P.api.totalPanels===0&&e.length>0){const G=Jh(P.api,e,d);if(G){const oe=P.api.getPanel(G);oe&&ze(oe)}}else!E.current&&!xt(d)&&bt();x.current=!0,P.api.onDidActivePanelChange(G=>{var Ie;if(M.current=(G==null?void 0:G.id)??null,L.current=!0,ke(),G&&ts(G.id)){const _e=((Ie=G.params)==null?void 0:Ie.routeId)||G.id.slice(7),Ae=Wt(e,_e);A((Ae==null?void 0:Ae.tabKey)??null),ct();return}if(A((G==null?void 0:G.id)??null),ct(),!G)return;const oe=ce.get(G.id);(oe==null?void 0:oe.streamSource)==="agent-stream"&&oe.agentType&&I(oe.routeId,cl(),{agentType:oe.agentType,...oe.sessionId&&{targetSessionId:oe.sessionId}}).catch(()=>{})}),P.api.onDidLayoutChange(()=>{ct(),ke(),Y(G=>G+1)}),P.api.onWillDragPanel(()=>{R(!0),N(!1),Ue()}),P.api.onWillDragGroup(()=>{R(!0),N(!1),Ue()}),P.api.onWillShowOverlay(()=>{kt(),N(!0)}),P.api.onDidMovePanel(wt),P.api.onDidDrop(wt),P.api.onDidAddGroup(G=>{requestAnimationFrame(()=>{var oe,Ie;try{const _e=(oe=G.element)==null?void 0:oe.ownerDocument;if(!_e||_e===document)return;(Ie=_e.getElementById("dv-popout-window"))==null||Ie.classList.add("adhdev-dockview");const Ae=document.documentElement.getAttribute("data-theme");Ae&&_e.documentElement.setAttribute("data-theme",Ae),_e.body.className=document.body.className;const We=document.documentElement.getAttribute("style");We&&_e.documentElement.setAttribute("style",We)}catch{}ke(),Y(_e=>_e+1)})}),A(((F=P.api.activePanel)==null?void 0:F.id)??null)},[ze,xt,wt,kt,ce,r,p,W,Ue,A,ct,d,b,I,ke,e]);o.useLayoutEffect(()=>{const P=j.current;if(!P||!x.current||E.current&&vi({hasStoredLayout:!0,initialDataLoaded:p,visibleConversationCount:e.length,ides:r}))return;E.current&&(E.current=!1);const O=T.current,F=new Set(O),G=e.map(De=>De.tabKey),oe=new Set(G);let Ie=!1;for(const De of O)oe.has(De)||(ae.current[De]=Xe(De),Ie=!0);Ie&&Te(),ki(P,e),Si(P,e,b);const _e=G.filter(De=>!F.has(De));let Ae=!1;for(const De of _e){const Je=P.getPanel(De),Ve=ae.current[De];if(!Je||!Ve||Ve.kind==="grid")continue;if(Je.group.model.location.type===Ve.kind){delete ae.current[De],Ae=!0;continue}if(Ve.kind==="floating"){P.addFloatingGroup(Je,{x:Ve.position.left??24,y:Ve.position.top??24,width:Ve.position.width,height:Ve.position.height}),delete ae.current[De],Ae=!0;continue}}if(Ae&&Te(),T.current=G,d&&xt(d))return;!P.activePanel&&P.panels[0]&&ze(P.panels[0]),!!(P.activePanel&&P.getPanel(P.activePanel.id))||bt()},[ze,xt,bt,r,p,Te,Xe,d,b,e]),o.useEffect(()=>{x.current&&xt(d)},[xt,d]),o.useEffect(()=>{if(!C||typeof window>"u")return;const P=()=>wt();return window.addEventListener("pointerup",P),window.addEventListener("mouseup",P),window.addEventListener("dragend",P),()=>{window.removeEventListener("pointerup",P),window.removeEventListener("mouseup",P),window.removeEventListener("dragend",P)}},[wt,C]),o.useEffect(()=>()=>{typeof window>"u"||q.current!=null&&window.clearTimeout(q.current)},[]),o.useEffect(()=>{const P=F=>{const G=F.target;if(!G)return;const oe=G.querySelector("[data-tab-key]")||G.closest("[data-tab-key]");if(oe){const Ie=oe.getAttribute("data-tab-key");if(Ie&&F.dataTransfer){const _e=G.closest(".dv-tab")||oe.closest(".dv-tab")||oe;F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/tab-key",Ie),_e instanceof HTMLElement&&F.dataTransfer.setDragImage(_e,Math.max(12,Math.round(_e.clientWidth/2)),Math.max(10,Math.round(_e.clientHeight/2)))}}};window.addEventListener("dragstart",P);const O=ji(j.current);for(const F of O)F.addEventListener("dragstart",P);return()=>{window.removeEventListener("dragstart",P);for(const F of O)F.removeEventListener("dragstart",P)}},[D]),o.useEffect(()=>{var O;const P=(O=v.current)==null?void 0:O.querySelector(".adhdev-dockview");P instanceof HTMLElement&&Gr(P,k),J(),ke(),Z()},[ke,Z,J,k]),o.useEffect(()=>{ke(),Z()},[ke,Z]),o.useEffect(()=>{const P=O=>{if(O.defaultPrevented||Oe)return;const F=Ge(O);if(!F)return;const G=O.metaKey||O.ctrlKey||O.altKey;Ia(O.target)&&!G||hn(Q).setActiveTabShortcut!==F||(O.preventDefault(),O.stopPropagation(),Qe())};return window.addEventListener("keydown",P,!0),()=>window.removeEventListener("keydown",P,!0)},[Ge,Q,Oe,Qe]),o.useEffect(()=>{const P=v.current;if(!P)return;const O=F=>{var Ae,We;if(!F.isTrusted)return;const G=(We=(Ae=F.target)==null?void 0:Ae.closest)==null?void 0:We.call(Ae,".dv-scrollable");if(!G)return;F.preventDefault(),F.stopPropagation();const oe=Math.abs(F.deltaX),Ie=Math.abs(F.deltaY),_e=oe>Ie?F.deltaX:F.deltaY;G.dispatchEvent(new WheelEvent("wheel",{deltaY:_e,deltaMode:F.deltaMode,bubbles:!1,cancelable:!0}))};return P.addEventListener("wheel",O,{passive:!1,capture:!0}),()=>P.removeEventListener("wheel",O,{capture:!0})},[]),o.useEffect(()=>{const P=ji(j.current);if(P.length===0)return;const O=P.map(F=>{let G=[],oe=null;const Ie=()=>{oe!=null&&F.clearTimeout(oe),oe=null,G=[]},_e=()=>{oe!=null&&F.clearTimeout(oe),oe=F.setTimeout(()=>{oe=null,G=[]},1200)},Ae=De=>{if(!De.ctrlKey&&!De.metaKey&&!De.altKey)return;const Je=Ge(De);if(!Je)return;const Ve=hl();for(const[re,je]of Object.entries(Ve))if(e.some(Be=>Be.tabKey===re)&&je===Je){De.preventDefault(),ve(re);return}},We=De=>{if(De.defaultPrevented||Oe)return;const Je=Ge(De);if(!Je)return;const Ve=De.metaKey||De.ctrlKey||De.altKey;if(Ia(De.target)&&!Ve)return;const re=hn(Q),je=Object.entries(re).filter(([Ne,et])=>!!et&&(Ne==="splitActiveTabRight"||Ne==="splitActiveTabDown"||Ne==="floatActiveTab"||Ne==="popoutActiveTab"||Ne==="dockActiveTab"||Ne==="focusLeftPane"||Ne==="focusRightPane"||Ne==="focusUpPane"||Ne==="focusDownPane"||Ne==="moveActiveTabToLeftPane"||Ne==="moveActiveTabToRightPane"||Ne==="moveActiveTabToUpPane"||Ne==="moveActiveTabToDownPane"||Ne==="selectPreviousGroupTab"||Ne==="selectNextGroupTab"||Ne==="setActiveTabShortcut"||Ne==="hideCurrentTab")),Be=Ve?[Je]:[...G.slice(-1),Je].slice(-2),rt=Be.join(" "),$=Be[Be.length-1],te=je.find(([,Ne])=>Ne===rt);if(te){De.preventDefault(),Ie(),ut(te[0]);return}if(je.some(([,Ne])=>Ne.startsWith(`${rt} `))){De.preventDefault(),G=Be,_e();return}const Ee=je.find(([,Ne])=>Ne===$);if(Ee){De.preventDefault(),Ie(),ut(Ee[0]);return}if(je.some(([,Ne])=>Ne.startsWith(`${$} `))){De.preventDefault(),G=[$],_e();return}Ie()};return F.addEventListener("keydown",Ae),F.addEventListener("keydown",We),()=>{Ie(),F.removeEventListener("keydown",Ae),F.removeEventListener("keydown",We)}});return()=>{for(const F of O)F()}},[Ge,Q,D,ve,Oe,ut,e]);const Ht=k==="light"?ua:ma,Mt=((Re=(ee=(Tt=j.current)==null?void 0:Tt.activePanel)==null?void 0:ee.group.element)==null?void 0:Re.ownerDocument)??document;return t.jsxs(wl.Provider,{value:it,children:[t.jsx("div",{ref:v,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(fd,{className:`h-full min-h-0 min-w-0 adhdev-dockview${C?" is-dragging-dockview":""}${U?" is-showing-dockview-overlay":""}`,components:{conversation:Qh,remote:Zh},defaultTabComponent:tx,watermarkComponent:ex,onReady:St,singleTabMode:"default",tabAnimation:"smooth",theme:Ht,popoutUrl:"/popout.html"})}),B&&pr.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:B.x,top:B.y},children:ht.map(P=>{if(P.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},P.id);let O=t.jsx(tu,{size:13,className:"shrink-0 opacity-70"}),F=()=>{};switch(P.id){case"dockInWindow":case"dockBackToGrid":O=t.jsx(ru,{size:13,className:"shrink-0 opacity-70"}),F=()=>{pe(B.tabKey),H(null)};break;case"moveBackToMain":O=t.jsx(eu,{size:13,className:"shrink-0 opacity-70"}),F=()=>{de(B.tabKey),H(null)};break;case"floatAsPanel":O=t.jsx(su,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ie(B.tabKey),H(null)};break;case"openInNewWindow":O=t.jsx(Zd,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ue(B.tabKey),H(null)};break;case"setShortcut":F=G=>{G.stopPropagation(),Pe(B.tabKey),H(null)};break;case"removeShortcut":O=t.jsx(At,{size:13,className:"shrink-0 opacity-70"}),F=()=>{const G={...Me};delete G[B.tabKey],Ke(G),H(null)};break;case"hideTab":O=t.jsx(Yi,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ye(B.tabKey),H(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 ${P.tone==="muted"?"text-text-muted":""}`,onClick:F,children:[O,t.jsx("span",{className:"flex-1 min-w-0",children:P.label}),P.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:P.shortcut}):null]},P.id)})}),B.sourceDocument.body),Oe&&pr.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:()=>Pe(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.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"})]})}),Mt.body)]})}const jl="adhdev-recent-launch-args-v1",rx=8;function nx(e){return String(e||"").trim().replace(/\s+/g," ")}function kl(e,s){return`${e.trim()}::${s.trim()}`}function Sl(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(jl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function ax(e){if(!(typeof window>"u"))try{window.localStorage.setItem(jl,JSON.stringify(e))}catch{}}function Nl(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Sl().byKey[kl(r,n)])==null?void 0:i.items)||[]}function Cl(e,s,r){var m;const n=String(e||"").trim(),a=String(s||"").trim(),i=nx(r);if(!n||!a||!i)return;const c=Sl(),l=kl(n,a),u=((m=c.byKey[l])==null?void 0:m.items)||[],p=[i,...u.filter(f=>f!==i)].slice(0,rx);c.byKey[l]={items:p},ax(c)}function ox(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 xo(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 Il(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=xo((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 Al(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function $s(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function Zn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function ix(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Ni(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function Ci(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 cx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function lx(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 dx(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 ux({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:a,onOpenConversation:i,onClose:c}){var U;const[l,u]=o.useState(n||((U=e[0])==null?void 0:U.id)||null),[p,m]=o.useState(""),[f,g]=o.useState(null),[w,A]=o.useState(!1);o.useEffect(()=>{var N;u(n||((N=e[0])==null?void 0:N.id)||null)},[n,e]);const d=o.useMemo(()=>e.find(N=>N.id===l)||e[0]||null,[l,e]),b=o.useMemo(()=>r.filter(N=>{if(N.type==="adhdev-daemon"||N.transport!=="pty")return!1;const D=ix(N.daemonId||N.id);return!!(d!=null&&d.id)&&D===d.id}),[d==null?void 0:d.id,r]),y=Qc(d==null?void 0:d.id,{enabled:!!(d!=null&&d.id),includeSessions:!0,limit:6,intervalMs:1e4}),h=y.diagnostics,S=y.loading,_=y.applyDiagnostics,k=o.useMemo(()=>{const N=new Map;for(const D of b){const Y=s.find(q=>q.sessionId===D.sessionId||q.routeId===D.id);D.sessionId&&Y&&N.set(D.sessionId,Y)}return N},[b,s]),I=o.useCallback(async()=>{if(d!=null&&d.id){A(!0);try{const N=await a(d.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),D=Zn(N);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Could not load hosted runtime diagnostics");_(D.diagnostics||D.result||null),m("")}catch(N){const D=N instanceof Error?N.message:"Could not load hosted runtime diagnostics";m(D)}finally{A(!1)}}},[d==null?void 0:d.id,_,a]);o.useEffect(()=>{!(d!=null&&d.id)||h||S||w||I()},[d==null?void 0:d.id,h,S,I,w]);const j=o.useCallback(async(N,D)=>{if(!(d!=null&&d.id)||N==="session_host_stop_session"&&!window.confirm(`Stop ${D.displayName}?
|
|
55
55
|
This will terminate the hosted runtime.`))return;const Y=`${N}:${D.sessionId}`;g(Y);try{const q=await a(d.id,N,{sessionId:D.sessionId}),W=Zn(q);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Session host action failed");const ae=N==="session_host_resume_session"?"resumed":N==="session_host_restart_session"?"restarted":"stopped";st.showToast(`Session host ${ae}: ${D.displayName}`,"success"),await I()}catch(q){const W=q instanceof Error?q.message:"Session host action failed";m(W),st.showToast(W,"warning")}finally{g(q=>q===Y?null:q)}},[d==null?void 0:d.id,I,a]),v=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.`))){g("session_host_prune_duplicate_sessions");try{const D=await a(d.id,"session_host_prune_duplicate_sessions",{}),Y=Zn(D);if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Duplicate prune failed");const q=Y.result||{},W=Array.isArray(q.prunedSessionIds)?q.prunedSessionIds.length:0,ae=typeof q.duplicateGroupCount=="number"?q.duplicateGroupCount:0;st.showToast(`Pruned ${W} duplicate runtime(s) across ${ae} group(s)`,"success"),await I()}catch(D){const Y=D instanceof Error?D.message:"Duplicate prune failed";m(Y),st.showToast(Y,"warning")}finally{g(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[d==null?void 0:d.id,I,a]),x=o.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((N,D)=>(D.lastActivityAt||0)-(N.lastActivityAt||0)),[h==null?void 0:h.sessions]),E=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)||[]}:Cl(x),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,x]),L=E.liveRuntimes,M=E.recoverySnapshots,T=E.inactiveRecords,B=o.useMemo(()=>ox(L),[L]),H=o.useMemo(()=>[...(h==null?void 0:h.recentLogs)||[]].reverse().find(N=>N.level==="warn"||N.level==="error")||null,[h==null?void 0:h.recentLogs]),C=o.useMemo(()=>[...(h==null?void 0:h.recentTransitions)||[]].slice(-3).reverse(),[h==null?void 0:h.recentTransitions]),R=(N,D)=>{var Z,ue;const Y=k.get(N.sessionId),q=b.find(de=>de.sessionId===N.sessionId),W=f===`session_host_resume_session:${N.sessionId}`,ae=f===`session_host_restart_session:${N.sessionId}`,ce=f===`session_host_stop_session:${N.sessionId}`,Se=xo(N.meta),X=typeof((Z=N.meta)==null?void 0:Z.runtimeRecoveryError)=="string"?String(N.meta.runtimeRecoveryError):"",he=D==="recovery"?"Recover":"Resume",J=Il(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:N.displayName||(q==null?void 0:q.runtimeDisplayName)||(q==null?void 0:q.cliName)||N.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${ax(N.lifecycle)}`,children:N.lifecycle}),Se&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:Se})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:N.workspaceLabel||(q==null?void 0:q.runtimeWorkspaceLabel)||N.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:N.runtimeKey}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:((ue=N.writeOwner)==null?void 0:ue.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:nx(N.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(Pa,{size:11})," ",N.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",Ni(N.lastActivityAt),N.osPid?` · pid ${N.osPid}`:"",` · Next: ${J}`]}),X&&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:X})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[Y&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(Y),c()},children:"Open chat"}),D==="recovery"&&(N.lifecycle==="interrupted"||N.lifecycle==="failed"||N.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",N)},children:W?`${he}ing…`:he}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!f,onClick:()=>{j("session_host_restart_session",N)},children:ae?"Restarting…":"Restart"}),D==="live"&&(N.lifecycle==="running"||N.lifecycle==="starting"||N.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",N)},children:ce?"Stopping…":"Stop"})]})]},N.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:N=>N.stopPropagation(),children:[t.jsx("div",{className:"mx-auto mt-3 h-1.5 w-12 rounded-full bg-border-subtle"}),t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 pt-4 pb-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Qt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(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:()=>{I()},disabled:S||w,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(Gs,{size:16})}),t.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:c,"aria-label":"Close hosted runtime recovery",children:t.jsx(At,{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(N=>t.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${N.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(N.id),children:N.label},N.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(ks,{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:Ni(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:Si(h.hostStartedAt)})]})]}),H&&t.jsxs("div",{className:"rounded-2xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-4 py-3",children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200",children:[t.jsx(ks,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:H.message})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(gn,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[B>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:f==="session_host_prune_duplicate_sessions",onClick:()=>{v()},children:f==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${B}`}),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:$s("live")}),L.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No live hosted CLI runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:L.map(N=>R(N,"live"))}),t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recovery snapshots"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:$s("recovery")}),M.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No recovery snapshots need attention."}):t.jsx("div",{className:"space-y-2",children:M.map(N=>R(N,"recovery"))})]}),T.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Inactive records"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:$s("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:T.map(N=>R(N,"inactive"))})]}),C.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:C.map(N=>{const D=x.find(Y=>Y.sessionId===N.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)||N.sessionId}),t.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[N.action,N.lifecycle?` · ${N.lifecycle}`:"",N.detail?` · ${N.detail}`:"",N.error?` · ${N.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${N.success===!1?"text-red-300":"text-text-secondary"}`,children:Si(N.timestamp)})]},`${N.sessionId}:${N.timestamp}:${N.action}`)})})]})]})]})]})})}function Al(e){return!e.hasLoadedInitialResults&&!e.isLoading}function or({title:e,description:s,action:r,children:n,className:a="",contentClassName:i=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),s&&t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:s})]}),r?t.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?t.jsx("div",{className:s||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function Ml({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?dl(n):null;return t.jsxs(or,{title:"Saved history",description:Ja(),action:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||s,onClick:a,children:s?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:i,children:fp()})]}),children:[l?t.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),t.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:l.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:l.providerSessionId}),t.jsx("div",{className:"mt-1",children:l.metaLine}),l.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:l.updatedLabel}),l.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:l.preview})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:c,disabled:e,children:"Clear"})]})}):t.jsx("div",{className:"text-[11px] text-text-muted",children:"Start fresh, or open saved history when you want continuity."}),r&&t.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function ea(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 qr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function cx({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:u,sendDaemonCommand:p,onOpenConversation:m}){var Mt,Tt;const f=Sr(),g=o.useMemo(()=>[...e].sort(Wa),[e]),[w,A]=o.useState(((Mt=g[0])==null?void 0:Mt.id)||""),d=o.useMemo(()=>g.find(ee=>ee.id===w)||g[0],[w,g]),b=o.useMemo(()=>((d==null?void 0:d.workspaces)||[]).map(ee=>({id:ee.id,path:ee.path,label:ee.label})),[d]),y=(d==null?void 0:d.defaultWorkspaceId)||null,[h,S]=o.useState(""),[_,k]=o.useState(""),[I,j]=o.useState(ea(g[0])),[v,x]=o.useState(""),[E,L]=o.useState(""),[M,T]=o.useState([]),[B,H]=o.useState(""),[C,R]=o.useState([]),[U,N]=o.useState(!1),[D,Y]=o.useState(!1),[q,W]=o.useState(""),[ae,ce]=o.useState(!1),[Se,X]=o.useState(()=>jt()),[he,J]=o.useState(!1),[Z,ue]=o.useState(null),[de,z]=o.useState(!1),[ye,ie]=o.useState(""),[le,se]=o.useState(!1),[pe,ne]=o.useState(""),[ke,ve]=o.useState([]),[K,V]=o.useState(!1),[we,be]=o.useState(""),[Q,Me]=o.useState(!1),Oe=o.useRef(null),Pe=o.useRef(0);o.useEffect(()=>{var ee;!w&&((ee=g[0])!=null&&ee.id)&&A(g[0].id)},[w,g]),o.useEffect(()=>{!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||f(d.id,{minFreshMs:3e4}).catch(()=>{})},[f,d]);const Ke=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(ee=>ee.category==="cli"&&ee.installed!==!1),[d]),Qe=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(ee=>ee.category==="acp"&&ee.installed!==!1),[d]),Ge=o.useMemo(()=>((d==null?void 0:d.detectedIdes)||[]).map(ee=>({id:ee.type,label:ee.name||ee.type,meta:ee.running?"Detected locally":"Available to open"})),[d]),ut=o.useMemo(()=>I==="cli"?Ke.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"CLI provider"})):I==="acp"?Qe.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"ACP provider"})):Ge,[Qe,I,Ke,Ge]);o.useEffect(()=>{var Re;if(!d)return;if(Oe.current!==d.id){Oe.current=d.id,S(y||((Re=b[0])==null?void 0:Re.id)||"__home__"),k(""),j(ea(d)),x(""),L(""),H(""),R([]),Y(!1),W(""),X(jt()),ie("");return}S(P=>{var O;return P==="__custom__"||P==="__home__"||b.some(F=>F.id===P)?P:y||((O=b[0])==null?void 0:O.id)||"__home__"}),j(P=>P==="ide"&&Ge.length>0||P==="cli"&&Ke.length>0||P==="acp"&&Qe.length>0?P:ea(d))},[Qe.length,Ke.length,y,Ge.length,d,b]),o.useEffect(()=>{var ee;I&&(ut.some(Re=>Re.id===v)||x(((ee=ut[0])==null?void 0:ee.id)||""))},[I,ut,v]);const it=o.useCallback(async(ee,Re)=>{const P=Pe.current+1;return Pe.current=P,N(!0),W(""),u(ee,Re).then(O=>{Pe.current===P&&R(O)}).catch(O=>{Pe.current===P&&(R([]),W(O instanceof Error?O.message:"Could not load saved sessions"))}).finally(()=>{Pe.current===P&&(N(!1),Y(!0))})},[u]),ht=o.useCallback((ee,Re)=>{T(Sl(ee,Re))},[]);o.useEffect(()=>{Pe.current+=1,H(""),X(jt()),!d||!v||I==="ide"?T([]):ht(d.id,v),Y(!1),R([]),W(""),N(!1)},[I,ht,it,d,v]),o.useEffect(()=>{if(!B)return;const ee=C.find(Re=>Re.providerSessionId===B);ee!=null&&ee.canResume||H("")},[C,B]);const ze=h==="__custom__"?_.trim():h==="__home__"?"":((Tt=b.find(ee=>ee.id===h))==null?void 0:Tt.path)||"",xt=o.useMemo(()=>d?r.filter(ee=>ee.id!==d.id&&ee.daemonId===d.id).map(ee=>ee.workspace):[],[r,d]),bt=o.useMemo(()=>((d==null?void 0:d.recentLaunches)||[]).map(ee=>ee.workspace),[d]),ct=o.useCallback(ee=>{const Re=String(ee.workspace||"").trim();if(!Re)return;const P=b.find(O=>qr(O.path)===qr(Re));if(P){S(P.id),k("");return}S("__custom__"),k(Re)},[b]),Te=o.useCallback(ee=>{const Re=String(ee.workspace||"").trim();if(!Re)return{workspaceId:null,workspacePath:null};const P=b.find(O=>qr(O.path)===qr(Re));return P?{workspaceId:P.id,workspacePath:null}:{workspaceId:null,workspacePath:Re}},[b]),Xe=o.useMemo(()=>C.find(ee=>ee.providerSessionId===B)||null,[C,B]),Fe=o.useMemo(()=>{var Re;if(I!=="cli"||!d||!v)return null;const ee=((Re=Ke.find(P=>P.type===v))==null?void 0:Re.displayName)||v;return{routeId:d.id,daemonId:d.id,providerSessionId:B||void 0,transport:"pty",mode:"chat",agentName:ee,agentType:v,status:"idle",title:ee,messages:[],ideType:v,workspaceName:ze,displayPrimary:ee,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${d.id}:${v}`,machineName:_t(d,{fallbackId:d.id})}},[I,Ke,ze,d,B,v]),Ue=o.useCallback(()=>{var Re;if(!d)return;S("__custom__"),se(!0),be("");const ee=Nn(d.platform,Sn(_.trim(),ze,xt,bt,d.defaultWorkspacePath,(Re=b.find(P=>P.id===y))==null?void 0:Re.path,b.map(P=>P.path)));V(!0),a(d.id,ee).then(P=>{ne(P.path),k(P.path),ve(P.directories)}).catch(P=>{be(P instanceof Error?P.message:"Could not load folder")}).finally(()=>V(!1))},[_,y,bt,xt,a,ze,d,b]),kt=o.useCallback(ee=>{d&&(V(!0),be(""),a(d.id,ee).then(Re=>{ne(Re.path),k(Re.path),ve(Re.directories)}).catch(Re=>{be(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>V(!1)))},[a,d]),yt=o.useCallback(async()=>{if(!d||!ze)return;Me(!0),ie("");const ee=await i(d.id,ze);if(Me(!1),!ee.ok){ie(ee.error||"Could not save workspace");return}ie("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,ze,d]),wt=o.useCallback(async()=>{if(!d||!I||!v)return;z(!0),ie("");const ee=E.trim()?E.trim().split(/\s+/).filter(Boolean):[],Re=I==="ide"?await c(d.id,v,{workspacePath:ze||null}):await l(d.id,I,v,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&ze||null,resumeSessionId:I==="cli"&&B?B:null,cliArgs:ee});if(z(!1),!Re.ok){ie(Re.error||"Could not start session");return}I!=="ide"&&E.trim()&&(Nl(d.id,v,E),ht(d.id,v)),n()},[I,E,ht,n,c,l,ze,d,B,v,h]),St=I?Ec(I,I==="cli"&&!!B):"Start",Ht=I?$c(I,I==="cli"&&!!B):"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(At,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[t.jsx(or,{title:"Machine",children:t.jsx("select",{value:d.id,onChange:ee=>A(ee.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:de,children:g.map(ee=>t.jsx("option",{value:ee.id,children:_t(ee,{fallbackId:ee.id})},ee.id))})}),I==="cli"&&t.jsx(or,{title:"Hosted runtimes",description:"Review live runtimes, recovery snapshots, and recover or restart options without leaving this launch flow.",action:t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:de||!d,onClick:()=>J(!0),children:[t.jsx(Qt,{size:14}),mp()]})}),t.jsxs(or,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ue,disabled:de,children:"Browse…"}),children:[t.jsxs("select",{value:h,onChange:ee=>{const Re=ee.target.value;S(Re),Re==="__custom__"?Ue():ie("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:de,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),b.map(ee=>t.jsxs("option",{value:ee.id,children:[ee.id===y?"⭐ ":"",jn(ee.path,ee.label)||ee.path]},ee.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.":ze||"Select a workspace folder."}),h==="__custom__"&&ze&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ue,disabled:de,children:[t.jsx(Bs,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:yt,disabled:de||Q,children:Q?"Saving…":"Save workspace"})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:Ke.length>0},{id:"ide",label:"IDE",enabled:Ge.length>0},{id:"acp",label:"ACP",enabled:Qe.length>0}].map(ee=>t.jsx("button",{type:"button",className:`btn btn-sm ${I===ee.id?"btn-primary":"btn-secondary"}`,onClick:()=>j(ee.id),disabled:!ee.enabled||de,children:ee.label},ee.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:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[ut.map(ee=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===ee.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>x(ee.id),disabled:de,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ee.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ee.meta})]},ee.id)),ut.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."})]})]}),I!=="ide"&&t.jsxs(or,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:E,onChange:ee=>L(ee.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:de}),M.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:M.map(ee=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>L(ee),disabled:de,title:ee,children:ee},ee))})]}),I==="cli"&&t.jsx(Ml,{busy:de,savedSessionsLoading:U,savedSessionsError:q,selectedSession:Xe,onRefresh:()=>{!d||!v||it(d.id,v)},onOpenHistory:()=>{!d||!v||(ce(!0),Al({hasLoadedInitialResults:D,isLoading:U})&&it(d.id,v))},onClearSelection:()=>H("")}),ye&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ye.includes("saved")||ye.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:ye})]}),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:de,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:wt,disabled:de||!I||!v||h==="__custom__"&&!ze,children:[t.jsx(Ea,{size:14}),de?Ht:St]})]})]})}),le&&t.jsx(In,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:pe,directories:ke,busy:K,error:we,onClose:()=>se(!1),onNavigate:kt,onConfirm:ee=>{k(ee),ne(ee),S("__custom__"),se(!1)}}),ae&&Fe&&t.jsx(eo,{activeConv:Fe,ides:[],isCreatingChat:!1,isRefreshingHistory:U,savedSessions:C,isSavedSessionsLoading:U,isResumingSavedSessionId:Z,savedHistoryFilters:Se,onSavedHistoryFiltersChange:X,onClose:()=>ce(!1),onNewChat:()=>{H(""),ce(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!d||!v||it(d.id,v)},onResumeSavedSession:ee=>{if(!d||!v||Z||!ee.canResume)return;const Re=Te(ee);H(ee.providerSessionId),ct(ee),ue(ee.providerSessionId),ce(!1),z(!0),ie(""),l(d.id,"cli",v,{workspaceId:Re.workspaceId,workspacePath:Re.workspacePath,resumeSessionId:ee.providerSessionId}).then(P=>{if(!P.ok){ie(P.error||"Could not resume session");return}n()}).finally(()=>{z(!1),ue(P=>P===ee.providerSessionId?null:P)})}}),he&&d&&t.jsx(ix,{machineCards:[{id:d.id,label:_t(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",ml(d)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:d.id,sendDaemonCommand:p,onOpenConversation:ee=>{J(!1),n(),m(ee)},onClose:()=>J(!1)})]}):null}function lx(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 dx(e){return e instanceof Error?e.message:String(e||"")}function ux(e){const s=dx(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function mx({showMobileChatMode:e,isMobile:s,activeConv:r,chatIdes:n,wsStatus:a,isConnected:i,onOpenHistory:c,onOpenRemote:l,onStopCli:u,activeCliViewMode:p,onSetActiveCliViewMode:m,mobileChatConversations:f,hiddenConversations:g,ides:w,actionLogs:A,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,initialDataLoaded:S,userName:_,requestedMobileTabKey:k,onRequestedMobileTabConsumed:I,requestedMachineId:j,onRequestedMachineConsumed:v,requestedMobileSection:x,onRequestedMobileSectionConsumed:E,containerRef:L,isSplitMode:M,numGroups:T,groupSizes:B,groupedConvs:H,clearedTabs:C,focusedGroup:R,setFocusedGroup:U,moveTabToGroup:N,splitTabRelative:D,closeGroup:Y,handleResizeStart:q,groupActiveTabIds:W,setGroupActiveTabIds:ae,groupTabOrders:ce,setGroupTabOrders:Se,toggleHiddenTab:X,visibleConversations:he,requestedDesktopTabKey:J,onRequestedDesktopTabConsumed:Z,onDesktopActiveTabChange:ue,onHideConversation:de,onShowHiddenConversation:z,onShowAllHiddenConversations:ye,scrollToBottomRequest:ie,machineEntries:le,onBrowseMachineDirectory:se,onSaveMachineWorkspace:pe,onLaunchMachineIde:ne,onLaunchMachineProvider:ke,onListMachineSavedSessions:ve,notifications:K,notificationUnreadCount:V,notificationStateBySessionId:we,liveSessionInboxState:be,onMarkNotificationRead:Q,onMarkNotificationUnread:Me,onDeleteNotification:Oe,onMarkNotificationTargetRead:Pe}){const Ke=at.useRef(null),[Qe,Ge]=at.useState(!1),[ut,it]=at.useState(!1),[ht,ze]=at.useState(!1),[xt,bt]=at.useState(!1),ct=at.useCallback(re=>{var je;pr.flushSync(()=>{z(re)}),(je=Ke.current)==null||je.restoreHiddenTabToSavedLocation(re.tabKey)},[z]),Te=at.useCallback(re=>{var Be;const je=f.find(rt=>hr(rt,re))||g.find(rt=>hr(rt,re));je&&(g.some(rt=>rt.tabKey===je.tabKey)&&ct(je),ue(je.tabKey),(Be=Ke.current)==null||Be.activateConversationTab(je.tabKey)),Q(re.id),(re.sessionId||re.providerSessionId||re.tabKey||re.routeId)&&Pe({sessionId:re.sessionId,providerSessionId:re.providerSessionId,tabKey:re.tabKey,routeId:re.routeId}),Ge(!1)},[ct,g,f,ue,Q,Pe]),[Xe,Fe]=at.useState(!1),[Ue,kt]=at.useState("quickstart"),[yt,wt]=at.useState("workspace"),St=!e&&!s,Ht=at.useCallback(re=>{Ge(re),re&&it(!1)},[]),Mt=at.useCallback(re=>{it(re),re&&Ge(!1)},[]),Tt=at.useCallback(()=>{var je;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((je=Ke.current)==null||je.resetAllPanelsToMain(),it(!1))},[]),ee=at.useCallback(()=>{kt(he.length===0?"quickstart":"shortcuts"),wt("workspace"),ze(!0),Ge(!1),it(!1)},[he.length]),Re=at.useCallback(async re=>{var te;if(!r)return;const je=(te=r.modalButtons)==null?void 0:te[re];if(!je)return;const Be=gr(r);if(!Be)return;const rt=je.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),$=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(rt);try{await d(Be,"resolve_action",{button:je,action:$?"approve":"reject",buttonIndex:re,...Es(r)})}catch(fe){ux(fe)||console.error("[Shortcut approval] Failed:",fe)}},[r,d]),{isMac:P,actionDefinitions:O,actionShortcuts:F,shortcutListening:G,shortcutListeningDraft:oe,setShortcutListening:Ie,setShortcutListeningDraft:_e,saveShortcuts:Ae}=Hh({enabled:St&&!ht,onTrigger:re=>{var je,Be,rt,$,te,fe,Ee,Le,Ne,et,$e,mt,es,Ys,Xs,Ir;if(re==="openShortcutHelp"){ee();return}if(re==="hideCurrentTab"){r&&de(r);return}if(re==="toggleHiddenTabs"){Mt(!ut);return}if(re==="openHistoryForActiveTab"){r&&!Ze(r)&&c(r);return}if(re==="openRemoteForActiveTab"){r&&!tt(r)&&!Ze(r)&&l(r);return}if(re==="splitActiveTabRight"){(je=Ke.current)==null||je.splitActiveTabRight();return}if(re==="splitActiveTabDown"){(Be=Ke.current)==null||Be.splitActiveTabDown();return}if(re==="floatActiveTab"){(rt=Ke.current)==null||rt.floatActiveTab();return}if(re==="popoutActiveTab"){($=Ke.current)==null||$.popoutActiveTab();return}if(re==="dockActiveTab"){(te=Ke.current)==null||te.dockActiveTab();return}if(re==="focusLeftPane"){(fe=Ke.current)==null||fe.focusLeftPane();return}if(re==="focusRightPane"){(Ee=Ke.current)==null||Ee.focusRightPane();return}if(re==="focusUpPane"){(Le=Ke.current)==null||Le.focusUpPane();return}if(re==="focusDownPane"){(Ne=Ke.current)==null||Ne.focusDownPane();return}if(re==="moveActiveTabToLeftPane"){(et=Ke.current)==null||et.moveActiveTabToLeftPane();return}if(re==="moveActiveTabToRightPane"){($e=Ke.current)==null||$e.moveActiveTabToRightPane();return}if(re==="moveActiveTabToUpPane"){(mt=Ke.current)==null||mt.moveActiveTabToUpPane();return}if(re==="moveActiveTabToDownPane"){(es=Ke.current)==null||es.moveActiveTabToDownPane();return}if(re==="triggerPrimaryApprovalAction"){Re(0);return}if(re==="triggerSecondaryApprovalAction"){Re(1);return}if(re==="triggerTertiaryApprovalAction"){Re(2);return}if(re==="setActiveTabShortcut"){(Ys=Ke.current)==null||Ys.setShortcutForActiveTab();return}if(re==="selectPreviousGroupTab"){(Xs=Ke.current)==null||Xs.activatePreviousTabInGroup();return}if(re==="selectNextGroupTab"){(Ir=Ke.current)==null||Ir.activateNextTabInGroup();return}!r||!tt(r)||Ze(r)||re==="toggleCliView"&&m(p==="chat"?"terminal":"chat")}}),We=at.useCallback(()=>{ze(!1),Ie(null),_e([])},[Ie,_e]),De=at.useMemo(()=>yt==="all"?O:O.filter(re=>lx(re)===yt),[O,yt]),Je=at.useCallback(()=>{const re=Object.fromEntries(O.map(je=>[je.id,""]));Ae(re)},[O,Ae]),Ve=at.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const re=Object.fromEntries(O.map(je=>[je.id,je.defaultShortcut]));Ae(re)},[O,Ae]);return at.useEffect(()=>{const re=je=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?je.metaKey&&je.key.toLowerCase()==="w":je.ctrlKey&&je.key.toLowerCase()==="w")&&(je.preventDefault(),r&&de&&de(r))};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[r,de]),at.useEffect(()=>{if(!ht||G)return;const re=je=>{je.key==="Escape"&&(je.preventDefault(),We())};return window.addEventListener("keydown",re,!0),()=>window.removeEventListener("keydown",re,!0)},[We,ht,G]),at.useEffect(()=>{if(!St){Fe(!1);return}Fe(!0);const re=window.setTimeout(()=>{Fe(!1)},1e4);return()=>window.clearTimeout(re)},[St]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(ip,{activeConv:r,agentCount:n.length,wsStatus:a,isConnected:i,conversations:he,hiddenConversations:g,onOpenHistory:c,onHideConversation:de,onShowConversation:ct,onShowAllHidden:ye,onResetPanelsToMain:Tt,notifications:K,notificationUnreadCount:V,onOpenNotification:Te,onMarkNotificationRead:Q,onMarkNotificationUnread:Me,onDeleteNotification:Oe,inboxOpen:Qe,onInboxOpenChange:Ht,hiddenOpen:ut,onHiddenOpenChange:Mt,onOpenNewSession:s?void 0:()=>bt(!0),actionShortcuts:F,onOpenRemote:()=>{!r||tt(r)||Ze(r)||l(r)},onStopCli:u,activeCliViewMode:p,onSetCliViewMode:m}),e?t.jsx(Th,{conversations:f,hiddenConversations:g,ides:w,actionLogs:A,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,userName:_,requestedActiveTabKey:k,onRequestedActiveTabConsumed:I,requestedMachineId:j,onRequestedMachineConsumed:v,requestedMobileSection:x,onRequestedMobileSectionConsumed:E,onOpenHistory:c,onOpenRemote:l,onStopCli:u,wsStatus:a,isConnected:i,onShowHiddenConversation:ct,onShowAllHiddenConversations:ye,onOpenNewSession:()=>bt(!0),notificationStateBySessionId:we,liveSessionInboxState:be,onMarkNotificationTargetRead:Pe}):s?t.jsx(Kh,{containerRef:L,isSplitMode:M,numGroups:T,groupSizes:B,groupedConvs:H,clearedTabs:C,ides:w,actionLogs:A,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,hasRegisteredMachines:le.length>0,userName:_,focusedGroup:R,setFocusedGroup:U,moveTabToGroup:N,splitTabRelative:D,closeGroup:Y,handleResizeStart:q,groupActiveTabIds:W,setGroupActiveTabIds:ae,groupTabOrders:ce,setGroupTabOrders:Se,toggleHiddenTab:X,allowTabShortcuts:!1,notificationStateBySessionId:we,liveSessionInboxState:be}):t.jsx(Qh,{visibleConversations:he,clearedTabs:C,ides:w,actionLogs:A,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,hasRegisteredMachines:le.length>0,initialDataLoaded:S,userName:_,toggleHiddenTab:X,actionShortcuts:F,registerActionHandlers:re=>{Ke.current=re},notificationStateBySessionId:we,liveSessionInboxState:be,onActiveTabChange:ue,requestedActiveTabKey:J,onRequestedActiveTabConsumed:Z,scrollToBottomRequest:ie}),xt&&t.jsx(cx,{machines:le,conversations:f,ides:w,onClose:()=>bt(!1),onBrowseDirectory:se,onSaveWorkspace:pe,onLaunchIde:ne,onLaunchProvider:ke,onListSavedSessions:ve,sendDaemonCommand:d,onOpenConversation:re=>{bt(!1),z(re),ue(re.tabKey)}}),ht&&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:We,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:re=>re.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:We,"aria-label":"Close dashboard guide",children:t.jsx(At,{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(re=>t.jsx("button",{type:"button",className:`btn btn-sm ${Ue===re.id?"btn-primary":"btn-secondary"}`,onClick:()=>kt(re.id),children:re.label},re.id))}),Ue==="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 ",P?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Ue==="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."]})]})]})]}),Ue==="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(re=>t.jsx("button",{type:"button",className:`btn btn-sm ${yt===re.id?"btn-primary":"btn-secondary"}`,onClick:()=>wt(re.id),children:re.label},re.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Je,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:Ve,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:De.map(re=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${G===re.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:re.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:re.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:re.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:G===re.id?oe.length>0?`${oe.join(" ")} ...`:"Listening...":F[re.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Ie(re.id),_e([])},children:G===re.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const je={...F};je[re.id]="",Ae(je)},children:"Disable"})]})]})},re.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",P?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:ee,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 ${Xe?"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:"?"}),Xe&&t.jsx("span",{children:"Guide"})]})]})}const ta=[{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 px({onClose:e}){const[s,r]=o.useState(0),n=ta[s],a=s===ta.length-1;return t.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.stopPropagation()},children:[t.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[t.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:t.jsx(At,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:ta.map((i,c)=>t.jsx("div",{style:{width:c===s?24:8,height:8,borderRadius:4,background:c===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),t.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),t.jsxs("div",{style:{textAlign:"center"},children:[t.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[t.jsx("span",{children:n.icon})," ",n.title]}),t.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&t.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[t.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),t.jsx("div",{className:"flex justify-end items-center mt-6",children:t.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),t.jsx("style",{children:`
|
|
56
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){g("session_host_prune_duplicate_sessions");try{const D=await a(d.id,"session_host_prune_duplicate_sessions",{}),Y=Zn(D);if(!(Y!=null&&Y.success))throw new Error((Y==null?void 0:Y.error)||"Duplicate prune failed");const q=Y.result||{},W=Array.isArray(q.prunedSessionIds)?q.prunedSessionIds.length:0,ae=typeof q.duplicateGroupCount=="number"?q.duplicateGroupCount:0;st.showToast(`Pruned ${W} duplicate runtime(s) across ${ae} group(s)`,"success"),await I()}catch(D){const Y=D instanceof Error?D.message:"Duplicate prune failed";m(Y),st.showToast(Y,"warning")}finally{g(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[d==null?void 0:d.id,I,a]),x=o.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((N,D)=>(D.lastActivityAt||0)-(N.lastActivityAt||0)),[h==null?void 0:h.sessions]),E=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)||[]}:Il(x),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,x]),L=E.liveRuntimes,M=E.recoverySnapshots,T=E.inactiveRecords,B=o.useMemo(()=>dx(L),[L]),H=o.useMemo(()=>[...(h==null?void 0:h.recentLogs)||[]].reverse().find(N=>N.level==="warn"||N.level==="error")||null,[h==null?void 0:h.recentLogs]),C=o.useMemo(()=>[...(h==null?void 0:h.recentTransitions)||[]].slice(-3).reverse(),[h==null?void 0:h.recentTransitions]),R=(N,D)=>{var Z,ue;const Y=k.get(N.sessionId),q=b.find(de=>de.sessionId===N.sessionId),W=f===`session_host_resume_session:${N.sessionId}`,ae=f===`session_host_restart_session:${N.sessionId}`,ce=f===`session_host_stop_session:${N.sessionId}`,Se=xo(N.meta),X=typeof((Z=N.meta)==null?void 0:Z.runtimeRecoveryError)=="string"?String(N.meta.runtimeRecoveryError):"",he=D==="recovery"?"Recover":"Resume",J=Al(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:N.displayName||(q==null?void 0:q.runtimeDisplayName)||(q==null?void 0:q.cliName)||N.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${lx(N.lifecycle)}`,children:N.lifecycle}),Se&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:Se})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:N.workspaceLabel||(q==null?void 0:q.runtimeWorkspaceLabel)||N.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:N.runtimeKey}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:((ue=N.writeOwner)==null?void 0:ue.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:cx(N.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(Pa,{size:11})," ",N.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",Ci(N.lastActivityAt),N.osPid?` · pid ${N.osPid}`:"",` · Next: ${J}`]}),X&&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:X})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[Y&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(Y),c()},children:"Open chat"}),D==="recovery"&&(N.lifecycle==="interrupted"||N.lifecycle==="failed"||N.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",N)},children:W?`${he}ing…`:he}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!f,onClick:()=>{j("session_host_restart_session",N)},children:ae?"Restarting…":"Restart"}),D==="live"&&(N.lifecycle==="running"||N.lifecycle==="starting"||N.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",N)},children:ce?"Stopping…":"Stop"})]})]},N.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:N=>N.stopPropagation(),children:[t.jsx("div",{className:"mx-auto mt-3 h-1.5 w-12 rounded-full bg-border-subtle"}),t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 pt-4 pb-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Qt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(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:()=>{I()},disabled:S||w,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(Gs,{size:16})}),t.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:c,"aria-label":"Close hosted runtime recovery",children:t.jsx(At,{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(N=>t.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${N.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(N.id),children:N.label},N.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(ks,{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:Ci(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:Ni(h.hostStartedAt)})]})]}),H&&t.jsxs("div",{className:"rounded-2xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-4 py-3",children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200",children:[t.jsx(ks,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:H.message})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(gn,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[B>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:f==="session_host_prune_duplicate_sessions",onClick:()=>{v()},children:f==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${B}`}),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:$s("live")}),L.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No live hosted CLI runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:L.map(N=>R(N,"live"))}),t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recovery snapshots"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:$s("recovery")}),M.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No recovery snapshots need attention."}):t.jsx("div",{className:"space-y-2",children:M.map(N=>R(N,"recovery"))})]}),T.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Inactive records"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:$s("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:T.map(N=>R(N,"inactive"))})]}),C.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:C.map(N=>{const D=x.find(Y=>Y.sessionId===N.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)||N.sessionId}),t.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[N.action,N.lifecycle?` · ${N.lifecycle}`:"",N.detail?` · ${N.detail}`:"",N.error?` · ${N.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${N.success===!1?"text-red-300":"text-text-secondary"}`,children:Ni(N.timestamp)})]},`${N.sessionId}:${N.timestamp}:${N.action}`)})})]})]})]})]})})}function Ml(e){return!e.hasLoadedInitialResults&&!e.isLoading}function or({title:e,description:s,action:r,children:n,className:a="",contentClassName:i=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),s&&t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:s})]}),r?t.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?t.jsx("div",{className:s||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function Tl({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?ul(n):null;return t.jsxs(or,{title:"Saved history",description:Ja(),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:yp()})]}),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 ea(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 qr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function mx({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:u,sendDaemonCommand:p,onOpenConversation:m}){var Mt,Tt;const f=Sr(),g=o.useMemo(()=>[...e].sort(Wa),[e]),[w,A]=o.useState(((Mt=g[0])==null?void 0:Mt.id)||""),d=o.useMemo(()=>g.find(ee=>ee.id===w)||g[0],[w,g]),b=o.useMemo(()=>((d==null?void 0:d.workspaces)||[]).map(ee=>({id:ee.id,path:ee.path,label:ee.label})),[d]),y=(d==null?void 0:d.defaultWorkspaceId)||null,[h,S]=o.useState(""),[_,k]=o.useState(""),[I,j]=o.useState(ea(g[0])),[v,x]=o.useState(""),[E,L]=o.useState(""),[M,T]=o.useState([]),[B,H]=o.useState(""),[C,R]=o.useState([]),[U,N]=o.useState(!1),[D,Y]=o.useState(!1),[q,W]=o.useState(""),[ae,ce]=o.useState(!1),[Se,X]=o.useState(()=>jt()),[he,J]=o.useState(!1),[Z,ue]=o.useState(null),[de,z]=o.useState(!1),[ye,ie]=o.useState(""),[le,se]=o.useState(!1),[pe,ne]=o.useState(""),[ke,ve]=o.useState([]),[K,V]=o.useState(!1),[we,be]=o.useState(""),[Q,Me]=o.useState(!1),Oe=o.useRef(null),Pe=o.useRef(0);o.useEffect(()=>{var ee;!w&&((ee=g[0])!=null&&ee.id)&&A(g[0].id)},[w,g]),o.useEffect(()=>{!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||f(d.id,{minFreshMs:3e4}).catch(()=>{})},[f,d]);const Ke=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(ee=>ee.category==="cli"&&ee.installed!==!1),[d]),Qe=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(ee=>ee.category==="acp"&&ee.installed!==!1),[d]),Ge=o.useMemo(()=>((d==null?void 0:d.detectedIdes)||[]).map(ee=>({id:ee.type,label:ee.name||ee.type,meta:ee.running?"Detected locally":"Available to open"})),[d]),ut=o.useMemo(()=>I==="cli"?Ke.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"CLI provider"})):I==="acp"?Qe.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"ACP provider"})):Ge,[Qe,I,Ke,Ge]);o.useEffect(()=>{var Re;if(!d)return;if(Oe.current!==d.id){Oe.current=d.id,S(y||((Re=b[0])==null?void 0:Re.id)||"__home__"),k(""),j(ea(d)),x(""),L(""),H(""),R([]),Y(!1),W(""),X(jt()),ie("");return}S(P=>{var O;return P==="__custom__"||P==="__home__"||b.some(F=>F.id===P)?P:y||((O=b[0])==null?void 0:O.id)||"__home__"}),j(P=>P==="ide"&&Ge.length>0||P==="cli"&&Ke.length>0||P==="acp"&&Qe.length>0?P:ea(d))},[Qe.length,Ke.length,y,Ge.length,d,b]),o.useEffect(()=>{var ee;I&&(ut.some(Re=>Re.id===v)||x(((ee=ut[0])==null?void 0:ee.id)||""))},[I,ut,v]);const it=o.useCallback(async(ee,Re)=>{const P=Pe.current+1;return Pe.current=P,N(!0),W(""),u(ee,Re).then(O=>{Pe.current===P&&R(O)}).catch(O=>{Pe.current===P&&(R([]),W(O instanceof Error?O.message:"Could not load saved sessions"))}).finally(()=>{Pe.current===P&&(N(!1),Y(!0))})},[u]),ht=o.useCallback((ee,Re)=>{T(Nl(ee,Re))},[]);o.useEffect(()=>{Pe.current+=1,H(""),X(jt()),!d||!v||I==="ide"?T([]):ht(d.id,v),Y(!1),R([]),W(""),N(!1)},[I,ht,it,d,v]),o.useEffect(()=>{if(!B)return;const ee=C.find(Re=>Re.providerSessionId===B);ee!=null&&ee.canResume||H("")},[C,B]);const ze=h==="__custom__"?_.trim():h==="__home__"?"":((Tt=b.find(ee=>ee.id===h))==null?void 0:Tt.path)||"",xt=o.useMemo(()=>d?r.filter(ee=>ee.id!==d.id&&ee.daemonId===d.id).map(ee=>ee.workspace):[],[r,d]),bt=o.useMemo(()=>((d==null?void 0:d.recentLaunches)||[]).map(ee=>ee.workspace),[d]),ct=o.useCallback(ee=>{const Re=String(ee.workspace||"").trim();if(!Re)return;const P=b.find(O=>qr(O.path)===qr(Re));if(P){S(P.id),k("");return}S("__custom__"),k(Re)},[b]),Te=o.useCallback(ee=>{const Re=String(ee.workspace||"").trim();if(!Re)return{workspaceId:null,workspacePath:null};const P=b.find(O=>qr(O.path)===qr(Re));return P?{workspaceId:P.id,workspacePath:null}:{workspaceId:null,workspacePath:Re}},[b]),Xe=o.useMemo(()=>C.find(ee=>ee.providerSessionId===B)||null,[C,B]),Fe=o.useMemo(()=>{var Re;if(I!=="cli"||!d||!v)return null;const ee=((Re=Ke.find(P=>P.type===v))==null?void 0:Re.displayName)||v;return{routeId:d.id,daemonId:d.id,providerSessionId:B||void 0,transport:"pty",mode:"chat",agentName:ee,agentType:v,status:"idle",title:ee,messages:[],ideType:v,workspaceName:ze,displayPrimary:ee,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${d.id}:${v}`,machineName:_t(d,{fallbackId:d.id})}},[I,Ke,ze,d,B,v]),Ue=o.useCallback(()=>{var Re;if(!d)return;S("__custom__"),se(!0),be("");const ee=Nn(d.platform,Sn(_.trim(),ze,xt,bt,d.defaultWorkspacePath,(Re=b.find(P=>P.id===y))==null?void 0:Re.path,b.map(P=>P.path)));V(!0),a(d.id,ee).then(P=>{ne(P.path),k(P.path),ve(P.directories)}).catch(P=>{be(P instanceof Error?P.message:"Could not load folder")}).finally(()=>V(!1))},[_,y,bt,xt,a,ze,d,b]),kt=o.useCallback(ee=>{d&&(V(!0),be(""),a(d.id,ee).then(Re=>{ne(Re.path),k(Re.path),ve(Re.directories)}).catch(Re=>{be(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>V(!1)))},[a,d]),yt=o.useCallback(async()=>{if(!d||!ze)return;Me(!0),ie("");const ee=await i(d.id,ze);if(Me(!1),!ee.ok){ie(ee.error||"Could not save workspace");return}ie("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,ze,d]),wt=o.useCallback(async()=>{if(!d||!I||!v)return;z(!0),ie("");const ee=E.trim()?E.trim().split(/\s+/).filter(Boolean):[],Re=I==="ide"?await c(d.id,v,{workspacePath:ze||null}):await l(d.id,I,v,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&ze||null,resumeSessionId:I==="cli"&&B?B:null,cliArgs:ee});if(z(!1),!Re.ok){ie(Re.error||"Could not start session");return}I!=="ide"&&E.trim()&&(Cl(d.id,v,E),ht(d.id,v)),n()},[I,E,ht,n,c,l,ze,d,B,v,h]),St=I?$c(I,I==="cli"&&!!B):"Start",Ht=I?Kc(I,I==="cli"&&!!B):"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(At,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[t.jsx(or,{title:"Machine",children:t.jsx("select",{value:d.id,onChange:ee=>A(ee.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:de,children:g.map(ee=>t.jsx("option",{value:ee.id,children:_t(ee,{fallbackId:ee.id})},ee.id))})}),I==="cli"&&t.jsx(or,{title:"Hosted runtimes",description:"Review live runtimes, recovery snapshots, and recover or restart options without leaving this launch flow.",action:t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:de||!d,onClick:()=>J(!0),children:[t.jsx(Qt,{size:14}),bp()]})}),t.jsxs(or,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ue,disabled:de,children:"Browse…"}),children:[t.jsxs("select",{value:h,onChange:ee=>{const Re=ee.target.value;S(Re),Re==="__custom__"?Ue():ie("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:de,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),b.map(ee=>t.jsxs("option",{value:ee.id,children:[ee.id===y?"⭐ ":"",jn(ee.path,ee.label)||ee.path]},ee.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.":ze||"Select a workspace folder."}),h==="__custom__"&&ze&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ue,disabled:de,children:[t.jsx(Bs,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:yt,disabled:de||Q,children:Q?"Saving…":"Save workspace"})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:Ke.length>0},{id:"ide",label:"IDE",enabled:Ge.length>0},{id:"acp",label:"ACP",enabled:Qe.length>0}].map(ee=>t.jsx("button",{type:"button",className:`btn btn-sm ${I===ee.id?"btn-primary":"btn-secondary"}`,onClick:()=>j(ee.id),disabled:!ee.enabled||de,children:ee.label},ee.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:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[ut.map(ee=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===ee.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>x(ee.id),disabled:de,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ee.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ee.meta})]},ee.id)),ut.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."})]})]}),I!=="ide"&&t.jsxs(or,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:E,onChange:ee=>L(ee.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:de}),M.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:M.map(ee=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>L(ee),disabled:de,title:ee,children:ee},ee))})]}),I==="cli"&&t.jsx(Tl,{busy:de,savedSessionsLoading:U,savedSessionsError:q,selectedSession:Xe,onRefresh:()=>{!d||!v||it(d.id,v)},onOpenHistory:()=>{!d||!v||(ce(!0),Ml({hasLoadedInitialResults:D,isLoading:U})&&it(d.id,v))},onClearSelection:()=>H("")}),ye&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ye.includes("saved")||ye.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:ye})]}),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:de,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:wt,disabled:de||!I||!v||h==="__custom__"&&!ze,children:[t.jsx(Ea,{size:14}),de?Ht:St]})]})]})}),le&&t.jsx(In,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:pe,directories:ke,busy:K,error:we,onClose:()=>se(!1),onNavigate:kt,onConfirm:ee=>{k(ee),ne(ee),S("__custom__"),se(!1)}}),ae&&Fe&&t.jsx(eo,{activeConv:Fe,ides:[],isCreatingChat:!1,isRefreshingHistory:U,savedSessions:C,isSavedSessionsLoading:U,isResumingSavedSessionId:Z,savedHistoryFilters:Se,onSavedHistoryFiltersChange:X,onClose:()=>ce(!1),onNewChat:()=>{H(""),ce(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!d||!v||it(d.id,v)},onResumeSavedSession:ee=>{if(!d||!v||Z||!ee.canResume)return;const Re=Te(ee);H(ee.providerSessionId),ct(ee),ue(ee.providerSessionId),ce(!1),z(!0),ie(""),l(d.id,"cli",v,{workspaceId:Re.workspaceId,workspacePath:Re.workspacePath,resumeSessionId:ee.providerSessionId}).then(P=>{if(!P.ok){ie(P.error||"Could not resume session");return}n()}).finally(()=>{z(!1),ue(P=>P===ee.providerSessionId?null:P)})}}),he&&d&&t.jsx(ux,{machineCards:[{id:d.id,label:_t(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",pl(d)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:d.id,sendDaemonCommand:p,onOpenConversation:ee=>{J(!1),n(),m(ee)},onClose:()=>J(!1)})]}):null}function px(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 fx(e){return e instanceof Error?e.message:String(e||"")}function hx(e){const s=fx(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function xx({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:g,ides:w,actionLogs:A,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,initialDataLoaded:S,userName:_,requestedMobileTabKey:k,onRequestedMobileTabConsumed:I,requestedMachineId:j,onRequestedMachineConsumed:v,requestedMobileSection:x,onRequestedMobileSectionConsumed:E,containerRef:L,isSplitMode:M,numGroups:T,groupSizes:B,groupedConvs:H,clearedTabs:C,focusedGroup:R,setFocusedGroup:U,moveTabToGroup:N,splitTabRelative:D,closeGroup:Y,handleResizeStart:q,groupActiveTabIds:W,setGroupActiveTabIds:ae,groupTabOrders:ce,setGroupTabOrders:Se,toggleHiddenTab:X,visibleConversations:he,requestedDesktopTabKey:J,onRequestedDesktopTabConsumed:Z,onDesktopActiveTabChange:ue,onHideConversation:de,onShowHiddenConversation:z,onShowAllHiddenConversations:ye,scrollToBottomRequest:ie,machineEntries:le,onBrowseMachineDirectory:se,onSaveMachineWorkspace:pe,onLaunchMachineIde:ne,onLaunchMachineProvider:ke,onListMachineSavedSessions:ve,notifications:K,notificationUnreadCount:V,notificationStateBySessionId:we,liveSessionInboxState:be,onMarkNotificationRead:Q,onMarkNotificationUnread:Me,onDeleteNotification:Oe,onMarkNotificationTargetRead:Pe}){const Ke=at.useRef(null),[Qe,Ge]=at.useState(!1),[ut,it]=at.useState(!1),[ht,ze]=at.useState(!1),[xt,bt]=at.useState(!1),ct=at.useCallback(re=>{var je;pr.flushSync(()=>{z(re)}),(je=Ke.current)==null||je.restoreHiddenTabToSavedLocation(re.tabKey)},[z]),Te=at.useCallback(re=>{var Be;const je=f.find(rt=>hr(rt,re))||g.find(rt=>hr(rt,re));je&&(g.some(rt=>rt.tabKey===je.tabKey)&&ct(je),ue(je.tabKey),(Be=Ke.current)==null||Be.activateConversationTab(je.tabKey)),Q(re.id),(re.sessionId||re.providerSessionId||re.tabKey||re.routeId)&&Pe({sessionId:re.sessionId,providerSessionId:re.providerSessionId,tabKey:re.tabKey,routeId:re.routeId}),Ge(!1)},[ct,g,f,ue,Q,Pe]),[Xe,Fe]=at.useState(!1),[Ue,kt]=at.useState("quickstart"),[yt,wt]=at.useState("workspace"),St=!e&&!s,Ht=at.useCallback(re=>{Ge(re),re&&it(!1)},[]),Mt=at.useCallback(re=>{it(re),re&&Ge(!1)},[]),Tt=at.useCallback(()=>{var je;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((je=Ke.current)==null||je.resetAllPanelsToMain(),it(!1))},[]),ee=at.useCallback(()=>{kt(he.length===0?"quickstart":"shortcuts"),wt("workspace"),ze(!0),Ge(!1),it(!1)},[he.length]),Re=at.useCallback(async re=>{var te;if(!r)return;const je=(te=r.modalButtons)==null?void 0:te[re];if(!je)return;const Be=gr(r);if(!Be)return;const rt=je.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),$=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(rt);try{await d(Be,"resolve_action",{button:je,action:$?"approve":"reject",buttonIndex:re,...Es(r)})}catch(fe){hx(fe)||console.error("[Shortcut approval] Failed:",fe)}},[r,d]),{isMac:P,actionDefinitions:O,actionShortcuts:F,shortcutListening:G,shortcutListeningDraft:oe,setShortcutListening:Ie,setShortcutListeningDraft:_e,saveShortcuts:Ae}=Vh({enabled:St&&!ht,onTrigger:re=>{var je,Be,rt,$,te,fe,Ee,Le,Ne,et,$e,mt,es,Ys,Xs,Ir;if(re==="openShortcutHelp"){ee();return}if(re==="hideCurrentTab"){r&&de(r);return}if(re==="toggleHiddenTabs"){Mt(!ut);return}if(re==="openHistoryForActiveTab"){r&&!Ze(r)&&c(r);return}if(re==="openRemoteForActiveTab"){r&&!tt(r)&&!Ze(r)&&l(r);return}if(re==="splitActiveTabRight"){(je=Ke.current)==null||je.splitActiveTabRight();return}if(re==="splitActiveTabDown"){(Be=Ke.current)==null||Be.splitActiveTabDown();return}if(re==="floatActiveTab"){(rt=Ke.current)==null||rt.floatActiveTab();return}if(re==="popoutActiveTab"){($=Ke.current)==null||$.popoutActiveTab();return}if(re==="dockActiveTab"){(te=Ke.current)==null||te.dockActiveTab();return}if(re==="focusLeftPane"){(fe=Ke.current)==null||fe.focusLeftPane();return}if(re==="focusRightPane"){(Ee=Ke.current)==null||Ee.focusRightPane();return}if(re==="focusUpPane"){(Le=Ke.current)==null||Le.focusUpPane();return}if(re==="focusDownPane"){(Ne=Ke.current)==null||Ne.focusDownPane();return}if(re==="moveActiveTabToLeftPane"){(et=Ke.current)==null||et.moveActiveTabToLeftPane();return}if(re==="moveActiveTabToRightPane"){($e=Ke.current)==null||$e.moveActiveTabToRightPane();return}if(re==="moveActiveTabToUpPane"){(mt=Ke.current)==null||mt.moveActiveTabToUpPane();return}if(re==="moveActiveTabToDownPane"){(es=Ke.current)==null||es.moveActiveTabToDownPane();return}if(re==="triggerPrimaryApprovalAction"){Re(0);return}if(re==="triggerSecondaryApprovalAction"){Re(1);return}if(re==="triggerTertiaryApprovalAction"){Re(2);return}if(re==="setActiveTabShortcut"){(Ys=Ke.current)==null||Ys.setShortcutForActiveTab();return}if(re==="selectPreviousGroupTab"){(Xs=Ke.current)==null||Xs.activatePreviousTabInGroup();return}if(re==="selectNextGroupTab"){(Ir=Ke.current)==null||Ir.activateNextTabInGroup();return}!r||!tt(r)||Ze(r)||re==="toggleCliView"&&m(p==="chat"?"terminal":"chat")}}),We=at.useCallback(()=>{ze(!1),Ie(null),_e([])},[Ie,_e]),De=at.useMemo(()=>yt==="all"?O:O.filter(re=>px(re)===yt),[O,yt]),Je=at.useCallback(()=>{const re=Object.fromEntries(O.map(je=>[je.id,""]));Ae(re)},[O,Ae]),Ve=at.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const re=Object.fromEntries(O.map(je=>[je.id,je.defaultShortcut]));Ae(re)},[O,Ae]);return at.useEffect(()=>{const re=je=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?je.metaKey&&je.key.toLowerCase()==="w":je.ctrlKey&&je.key.toLowerCase()==="w")&&(je.preventDefault(),r&&de&&de(r))};return window.addEventListener("keydown",re),()=>window.removeEventListener("keydown",re)},[r,de]),at.useEffect(()=>{if(!ht||G)return;const re=je=>{je.key==="Escape"&&(je.preventDefault(),We())};return window.addEventListener("keydown",re,!0),()=>window.removeEventListener("keydown",re,!0)},[We,ht,G]),at.useEffect(()=>{if(!St){Fe(!1);return}Fe(!0);const re=window.setTimeout(()=>{Fe(!1)},1e4);return()=>window.clearTimeout(re)},[St]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(mp,{activeConv:r,agentCount:n.length,wsStatus:a,isConnected:i,conversations:he,hiddenConversations:g,onOpenHistory:c,onHideConversation:de,onShowConversation:ct,onShowAllHidden:ye,onResetPanelsToMain:Tt,notifications:K,notificationUnreadCount:V,onOpenNotification:Te,onMarkNotificationRead:Q,onMarkNotificationUnread:Me,onDeleteNotification:Oe,inboxOpen:Qe,onInboxOpenChange:Ht,hiddenOpen:ut,onHiddenOpenChange:Mt,onOpenNewSession:s?void 0:()=>bt(!0),actionShortcuts:F,onOpenRemote:()=>{!r||tt(r)||Ze(r)||l(r)},onStopCli:u,activeCliViewMode:p,onSetCliViewMode:m}),e?t.jsx(Ph,{conversations:f,hiddenConversations:g,ides:w,actionLogs:A,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,userName:_,requestedActiveTabKey:k,onRequestedActiveTabConsumed:I,requestedMachineId:j,onRequestedMachineConsumed:v,requestedMobileSection:x,onRequestedMobileSectionConsumed:E,onOpenHistory:c,onOpenRemote:l,onStopCli:u,wsStatus:a,isConnected:i,onShowHiddenConversation:ct,onShowAllHiddenConversations:ye,onOpenNewSession:()=>bt(!0),notificationStateBySessionId:we,liveSessionInboxState:be,onMarkNotificationTargetRead:Pe}):s?t.jsx(Hh,{containerRef:L,isSplitMode:M,numGroups:T,groupSizes:B,groupedConvs:H,clearedTabs:C,ides:w,actionLogs:A,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,hasRegisteredMachines:le.length>0,userName:_,focusedGroup:R,setFocusedGroup:U,moveTabToGroup:N,splitTabRelative:D,closeGroup:Y,handleResizeStart:q,groupActiveTabIds:W,setGroupActiveTabIds:ae,groupTabOrders:ce,setGroupTabOrders:Se,toggleHiddenTab:X,allowTabShortcuts:!1,notificationStateBySessionId:we,liveSessionInboxState:be}):t.jsx(sx,{visibleConversations:he,clearedTabs:C,ides:w,actionLogs:A,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,hasRegisteredMachines:le.length>0,initialDataLoaded:S,userName:_,toggleHiddenTab:X,actionShortcuts:F,registerActionHandlers:re=>{Ke.current=re},notificationStateBySessionId:we,liveSessionInboxState:be,onActiveTabChange:ue,requestedActiveTabKey:J,onRequestedActiveTabConsumed:Z,scrollToBottomRequest:ie}),xt&&t.jsx(mx,{machines:le,conversations:f,ides:w,onClose:()=>bt(!1),onBrowseDirectory:se,onSaveWorkspace:pe,onLaunchIde:ne,onLaunchProvider:ke,onListSavedSessions:ve,sendDaemonCommand:d,onOpenConversation:re=>{bt(!1),z(re),ue(re.tabKey)}}),ht&&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:We,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:re=>re.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:We,"aria-label":"Close dashboard guide",children:t.jsx(At,{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(re=>t.jsx("button",{type:"button",className:`btn btn-sm ${Ue===re.id?"btn-primary":"btn-secondary"}`,onClick:()=>kt(re.id),children:re.label},re.id))}),Ue==="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 ",P?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Ue==="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."]})]})]})]}),Ue==="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(re=>t.jsx("button",{type:"button",className:`btn btn-sm ${yt===re.id?"btn-primary":"btn-secondary"}`,onClick:()=>wt(re.id),children:re.label},re.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Je,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:Ve,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:De.map(re=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${G===re.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:re.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:re.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:re.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:G===re.id?oe.length>0?`${oe.join(" ")} ...`:"Listening...":F[re.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Ie(re.id),_e([])},children:G===re.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const je={...F};je[re.id]="",Ae(je)},children:"Disable"})]})]})},re.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",P?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:ee,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 ${Xe?"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:"?"}),Xe&&t.jsx("span",{children:"Guide"})]})]})}const ta=[{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 bx({onClose:e}){const[s,r]=o.useState(0),n=ta[s],a=s===ta.length-1;return t.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.stopPropagation()},children:[t.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[t.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:t.jsx(At,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:ta.map((i,c)=>t.jsx("div",{style:{width:c===s?24:8,height:8,borderRadius:4,background:c===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),t.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),t.jsxs("div",{style:{textAlign:"center"},children:[t.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[t.jsx("span",{children:n.icon})," ",n.title]}),t.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&t.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[t.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),t.jsx("div",{className:"flex justify-end items-center mt-6",children:t.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),t.jsx("style",{children:`
|
|
57
57
|
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
58
58
|
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
59
|
-
`})]})}function fx({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 hx({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),u=o.useMemo(()=>Bc(s),[s]),p=o.useMemo(()=>e?to(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]),g=o.useMemo(()=>e?Wt(p,e.id):null,[p,e]);o.useEffect(()=>{i&&l(i)},[i]),o.useEffect(()=>{if(i||!g)return;const b=g.streamSource==="native"?"native":g.tabKey;!b||c===b||c==="native"&&l(b)},[c,g,i]),o.useEffect(()=>{var b;c!=="native"&&(f.some(y=>y.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 w=o.useMemo(()=>c==="native"&&m?m:f.find(b=>b.tabKey===c)||g||m||f[0],[c,m,g,f]),A=o.useMemo(()=>f.map(b=>({tabKey:b.tabKey,title:Rc(b)||a,status:b.status})),[f,a]),d=o.useCallback(b=>{if(b)return p.find(y=>hr(y,{sessionId:b,routeId:b,tabKey:b,providerSessionId:b}))},[p]);return{activeChatTab:c,setActiveChatTab:l,activeConv:w,conversations:p,extensionTabs:A,hasExtensions:A.length>0,resolveConversationByTarget:d}}function xx({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:g,onClose:w}){const[A,d]=o.useState("split"),[b,y]=o.useState(()=>ns(e)?"native":e.tabKey),h=o.useRef(null),S=o.useMemo(()=>s||r.find(N=>N.id===e.routeId),[e.routeId,s,r]),_=o.useMemo(()=>ot((S==null?void 0:S.type)||""),[S==null?void 0:S.type]),{conversations:k,extensionTabs:I,hasExtensions:j}=hx({ideData:S,allIdes:r,connectionStates:n,localUserMessages:i,ideName:_||"IDE",preferredTabKey:ns(e)?void 0:e.tabKey}),v=o.useMemo(()=>S?Wt(k,S.id):null,[S,k]);o.useEffect(()=>{const N=h.current,D={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=D,!(N&&N.routeId===D.routeId&&N.tabKey===D.tabKey&&N.streamSource===D.streamSource)){if(ns(e)){y("native");return}y(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(b==="native"){if(k.some(N=>N.streamSource==="native"))return;(v==null?void 0:v.streamSource)==="agent-stream"&&y(v.tabKey);return}if(!k.some(N=>N.tabKey===b)){if((v==null?void 0:v.streamSource)==="agent-stream"){y(v.tabKey);return}y("native")}},[k,b,v]);const x=o.useMemo(()=>b==="native"?k.find(N=>N.streamSource==="native")||e:k.find(N=>N.tabKey===b)||e,[e,k,b]),E=Qc(x),L=o.useMemo(()=>E.status||E.modalMessage||E.modalButtons?{...x,...E.status?{status:E.status}:{},...E.modalMessage!==void 0?{modalMessage:E.modalMessage}:{},...E.modalButtons!==void 0?{modalButtons:E.modalButtons}:{}}:x,[x,E]),M=kr(L),T=kn({sendDaemonCommand:c,activeConv:L,setLocalUserMessages:l,setActionLogs:u,isStandalone:p}),{connScreenshot:B,screenshotUsage:H,handleRemoteAction:C}=xl({doId:M,targetSessionId:bc(L),connState:L.connectionState||"new",viewMode:A}),R=o.useMemo(()=>a.filter(N=>N.routeId===L.tabKey),[a,L.tabKey]);o.useEffect(()=>{g==null||g(L)},[L,g]),o.useEffect(()=>{const N=D=>{D.key==="Escape"&&w()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[w]);const U=o.useCallback(N=>{N.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:w,children:t.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:U,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(Rt,{size:16})}),t.jsx("span",{className:"truncate",children:Ua(x)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:w,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(N=>{const D=A===N;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(N),title:N==="split"?"Split view":"Remote only",children:N==="split"?t.jsx(Bd,{size:15}):t.jsx(Rt,{size:15})},N)})}),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(Da,{size:14,className:"md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"History"})]}),t.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:w,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${A==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[A!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${A==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(fx,{hasExtensions:j,ideName:_||"IDE",activeChatTab:b,extensionTabs:I,onSelectTab:y}),t.jsx(rc,{activeConv:L,onModalButton:T.handleModalButton}),t.jsx(va,{activeConv:L,ideEntry:S,showMetaChips:!1,handleSendChat:T.handleSendChat,isSendingChat:T.isSendingChat,sendFeedbackMessage:T.sendFeedbackMessage,handleFocusAgent:T.handleFocusAgent,isFocusingAgent:T.isFocusingAgent,actionLogs:R,userName:m})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${A==="split"?"order-1 md:order-2":""}`,children:t.jsx(Zi,{addLog:()=>{},connState:L.connectionState||"new",connScreenshot:B,screenshotUsage:H,transportType:L.transport,onAction:C})})]})]})})}function bx({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=rp(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 gx({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:g,remoteDialogConv:w,remoteDialogIdeEntry:A,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:h,setLocalUserMessages:S,setActionLogs:_,isStandalone:k,userName:I,onOpenRemoteHistory:j,onRemoteConversationChange:v,onCloseRemoteDialog:x,cliStopDialogOpen:E,cliStopTargetConv:L,onCancelCliStop:M,onStopCliNow:T,onSaveCliAndStop:B,toasts:H,onDismissToast:C,onClickToast:R,showOnboarding:U,onCloseOnboarding:N}){var q;const[D,Y]=at.useState(()=>jt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(eo,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:D,onSavedHistoryFiltersChange:Y,onClose:u,onNewChat:p,onSwitchSession:m,onRefreshHistory:f,onResumeSavedSession:g}),w&&t.jsx(xx,{activeConv:w,ideEntry:A,ides:r,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:h,setLocalUserMessages:S,setActionLogs:_,isStandalone:k,userName:I,onOpenHistory:j,onConversationChange:v,onClose:x}),E&&L&&(tt(L)||Ze(L))&&t.jsx(bx,{activeConv:L,canSaveAndStop:tt(L)&&!Ze(L)&&!!((q=L.resume)!=null&&q.supported),onCancel:M,onStopNow:T,onSaveAndStop:B}),t.jsx(Kc,{toasts:H,onDismiss:C,onClickToast:R}),U&&t.jsx(px,{onClose:N})]})}function yx({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:t.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[t.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:t.jsx(Gs,{size:14})}),t.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[t.jsxs("span",{children:[r?"Daemon update required":"Update available",s?t.jsxs(t.Fragment,{children:[": ",t.jsxs("strong",{children:["v",s]})]}):null]}),e.map(c=>{const l=_t(c,{fallbackId:c.id}),u=n[c.id],p=c.version||c.daemonVersion||"unknown",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(At,{size:16})})]})}function vx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function wx(e){const s=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?s===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function jx(e){const s=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",s,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&s&&s!==r),autoReadKey:i,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function kx(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Ci(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Sx(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Nx(){var ko,So,No,Co,Io;const{sendCommand:e}=Pt(),s=Sr(),r=_a(),n=Vs(),[a,i]=fd(),c=a.get("activeTab"),l=((ko=r.state)==null?void 0:ko.openRemoteForTabKey)||null,u=((So=r.state)==null?void 0:So.openMachineId)||null,p=((No=r.state)==null?void 0:No.mobileSection)||null,m=Ac(),f=m.ides||[],g=m.initialLoaded??!0,{updateRouteChats:w,setToasts:A}=m,[d,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=m.toasts||[],h=m.wsStatus||"connected",S=m.isConnected??!0,_=m.connectionStates||{},k=m.showReconnected||!1,{groupAssignments:I,setGroupAssignments:j,focusedGroup:v,setFocusedGroup:x,groupActiveTabIds:E,setGroupActiveTabIds:L,groupTabOrders:M,setGroupTabOrders:T,groupSizes:B,setGroupSizes:H,isMobile:C,hasHydratedStoredLayout:R,hydrateStoredLayout:U}=Df(),[N,D]=o.useState(!1),[Y,q]=o.useState(!1),[W,ae]=o.useState(null),[ce,Se]=o.useState([]),[X,he]=o.useState(!1),[J,Z]=o.useState(null),[ue,de]=o.useState(()=>ao());o.useEffect(()=>ef(de),[]);const z=o.useMemo(()=>vx({isMobile:C,mobileViewMode:ue}),[C,ue]),[ye,ie]=o.useState([]),[le,se]=o.useState({}),[pe,ne]=o.useState({}),[ke,ve]=o.useState({}),[K,V]=o.useState(null),[we,be]=o.useState(null),[Q,Me]=o.useState(null),Oe=o.useRef(null);wr("Dashboard",{ideCount:f.length,toastCount:y.length,focusedGroup:v,groupCount:Object.keys(I).length,localMessageTabs:Object.keys(le).length,actionLogCount:ye.length});const Pe=f.find(me=>me.type==="adhdev-daemon"),Ke=o.useMemo(()=>f.filter(me=>me.type==="adhdev-daemon").sort(Wa),[f]),Qe=!!Pe;o.useEffect(()=>{!Pe||!(!Pe.detectedIdes||!Pe.availableProviders||!Pe.recentLaunches||!Pe.workspaces)||s(Pe.id,{minFreshMs:3e4}).catch(()=>{})},[Pe,s]);const Ge=(Pe==null?void 0:Pe.terminalBackend)||null,ut=Pe?_t(Pe,{fallbackId:Pe.id}):null,it=(Pe==null?void 0:Pe.id)||null,ht=o.useMemo(()=>df(f,pe),[f,pe]),{hiddenTabs:ze,hideTab:xt,toggleTab:bt,showTab:ct,showAllTabs:Te}=lf(),{chatIdes:Xe,conversations:Fe,visibleConversations:Ue,visibleTabKeys:kt,resolveConversationBySessionId:yt,resolveConversationByTarget:wt}=jf({ides:ht,connectionStates:_,localUserMessages:le,clearedTabs:ke,hiddenTabs:ze}),St=o.useMemo(()=>new Map(Fe.map(me=>[me.tabKey,Wr(me)])),[Fe]),Ht=o.useCallback(me=>{const ge=St.get(me)||Wr({tabKey:me});xt(ge)},[St,xt]),Mt=o.useCallback(me=>{const ge=St.get(me)||Wr({tabKey:me});bt(ge)},[St,bt]),Tt=o.useCallback(me=>{const ge=St.get(me)||Wr({tabKey:me});ct(ge)},[St,ct]);zm(Ue,z),o.useEffect(()=>{Object.keys(pe).length!==0&&ne(me=>uf(me,f))},[f,pe]);const ee=o.useMemo(()=>vu(f),[f]),{notifications:Re,unreadCount:P,notificationStateBySessionId:O,markRead:F,markUnread:G,markTargetRead:oe,deleteNotification:Ie}=oh({conversations:Fe,liveSessionInboxState:ee}),_e=o.useCallback(me=>{const ge=Re.find(xe=>xe.id===me),Ce=Math.max(Date.now(),(ge==null?void 0:ge.updatedAt)||0);F(me,Ce),ge!=null&&ge.sessionId&&e(ge.machineId||ge.routeId,"mark_session_seen",{sessionId:ge.sessionId,seenAt:Ce}).catch(()=>{})},[F,Re,e]),Ae=o.useCallback(me=>{const ge=Re.find(Ce=>Ce.id===me);G(me),ge!=null&&ge.sessionId&&e(ge.machineId||ge.routeId,"mark_notification_unread",{sessionId:ge.sessionId,notificationId:ge.id}).catch(()=>{})},[G,Re,e]),We=o.useCallback(me=>{const ge=Re.find(Ce=>Ce.id===me);Ie(me),ge!=null&&ge.sessionId&&e(ge.machineId||ge.routeId,"delete_notification",{sessionId:ge.sessionId,notificationId:ge.id}).catch(()=>{})},[Ie,Re,e]),De=o.useRef(null),Je=o.useRef(null),Ve=o.useRef(null),re=o.useRef(null),je=o.useRef(null),{containerRef:Be,normalizedGroupAssignments:rt,numGroups:$,isSplitMode:te,groupedConvs:fe,moveTabToGroup:Ee,closeGroup:Le,handleResizeStart:Ne,splitTabRelative:et}=Ff({groupAssignments:I,setGroupAssignments:j,setFocusedGroup:x,setGroupActiveTabIds:L,setGroupTabOrders:T,groupSizes:B,setGroupSizes:H,isMobile:C,visibleConversations:Ue,visibleTabKeys:kt}),$e=o.useMemo(()=>{var ge,Ce;if(!C){if(K){const xe=Fe.find(qe=>qe.tabKey===K);if(xe)return xe}return Ue[0]}const me=E[v];if(me){const xe=Fe.find(qe=>qe.tabKey===me);if(xe)return xe}return((ge=fe[v])==null?void 0:ge[0])||((Ce=fe[0])==null?void 0:Ce[0])},[K,C,E,v,Fe,fe,Ue]);o.useEffect(()=>{const me=()=>{Ve.current&&(clearTimeout(Ve.current),Ve.current=null),re.current&&(clearTimeout(re.current),re.current=null),je.current&&(document.removeEventListener("visibilitychange",je.current),je.current=null),Je.current=null};if(C){me(),De.current=null;return}if(!($e!=null&&$e.sessionId)){me(),De.current=null;return}const ge=ln($e,ee),Ce=jx({tabKey:$e.tabKey,historySessionId:jr($e)||"",lastMessageHash:$e.lastMessageHash||"",lastMessageAt:Number($e.lastMessageAt||0),timestamp:ps($e),liveState:ge}),xe=Ce.autoReadKey,qe=wx({autoReadKey:xe,shouldMarkSeen:Ce.shouldMarkSeen,completedKey:De.current,pendingKey:Je.current});if(!Ce.shouldMarkSeen){qe.shouldCancelPending&&me(),De.current=xe;return}if(!qe.shouldSchedule)return;qe.shouldCancelPending&&me();const pt=tc($e),Dt=()=>{if(document.visibilityState!=="visible"||De.current===xe)return;De.current=xe,Je.current=null,Ve.current=null,re.current=null,je.current&&(document.removeEventListener("visibilitychange",je.current),je.current=null);const gt=Ce.readAt;oe({...pt},gt),e($e.daemonId||$e.routeId,"mark_session_seen",{sessionId:$e.sessionId,seenAt:gt}).catch(()=>{})};if(Je.current=qe.nextPendingKey,document.visibilityState==="visible"){Ve.current=setTimeout(Dt,1500);const gt=()=>{document.visibilityState!=="visible"&&Ve.current&&(clearTimeout(Ve.current),Ve.current=null)};je.current=gt,document.addEventListener("visibilitychange",gt);return}const qt=()=>{document.visibilityState==="visible"&&(re.current&&clearTimeout(re.current),re.current=setTimeout(Dt,800),je.current&&(document.removeEventListener("visibilitychange",je.current),je.current=null))};je.current=qt,document.addEventListener("visibilitychange",qt)},[$e,C,ee,oe,e]),o.useEffect(()=>()=>{Ve.current&&clearTimeout(Ve.current),re.current&&clearTimeout(re.current),je.current&&document.removeEventListener("visibilitychange",je.current)},[]);const{requestedDesktopTabKey:mt,requestedMobileTabKey:es,consumeRequestedActiveTab:Ys}=kf({isMobile:C,urlActiveTab:c,resolveConversationBySessionId:yt,setSearchParams:i}),{remoteDialogConv:Xs,remoteDialogIdeEntry:Ir,remoteDialogActiveConv:Dl,setRemoteDialogActiveConv:Ln,openRemoteDialog:El,closeRemoteDialog:$l}=Kf({isMobile:C,location:r,navigate:n,requestedRemoteTabTarget:l,requestedDesktopTabKey:mt,conversations:Fe,ides:f,resolveConversationByTarget:wt}),dt=Dl||Xs||$e,Ft=!!dt&&tt(dt)&&!Ze(dt),Ar=o.useMemo(()=>{if(!dt||!Ft)return null;const me=dt.daemonId||dt.routeId||"",ge=Bt(dt);return`${me}:${ge}`},[dt,Ft]),Kl=o.useMemo(()=>Ue,[Ue]),Mr=C&&ue==="chat",Bl=o.useMemo(()=>Fe.filter(me=>oo(ze,me)),[Fe,ze]),Tr=o.useCallback(me=>{const ge=new URLSearchParams(a);ge.set("activeTab",me),i(ge,{replace:!0})},[a,i]),Ol=o.useCallback(async(me,ge)=>Cn(e,me,ge),[e]),Wl=o.useCallback(async(me,ge)=>{if(!ge.trim())return{ok:!1,error:"Choose a workspace path first."};try{const Ce=await e(me,"workspace_add",{path:ge.trim()});return Ce!=null&&Ce.success?{ok:!0}:{ok:!1,error:(Ce==null?void 0:Ce.error)||"Could not save workspace"}}catch(Ce){return{ok:!1,error:Ce instanceof Error?Ce.message:"Could not save workspace"}}},[e]),Hl=o.useCallback(async(me,ge,Ce)=>{var xe;try{const qe={ideType:ge,enableCdp:!0};(xe=Ce==null?void 0:Ce.workspacePath)!=null&&xe.trim()&&(qe.workspace=Ce.workspacePath.trim());const pt=await e(me,"launch_ide",qe);return!(pt!=null&&pt.success)&&(pt==null?void 0:pt.success)!==void 0?{ok:!1,error:(pt==null?void 0:pt.error)||"Could not launch IDE"}:(Me({machineId:me,kind:"ide",providerType:ge,workspacePath:(Ce==null?void 0:Ce.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(qe){return{ok:!1,error:qe instanceof Error?qe.message:"Could not launch IDE"}}},[e]),Fl=o.useCallback(async(me,ge,Ce,xe)=>{var pt,Dt,qt;const qe=Date.now();try{const gt={cliType:Ce};(pt=xe==null?void 0:xe.workspacePath)!=null&&pt.trim()?gt.dir=xe.workspacePath.trim():xe!=null&&xe.workspaceId&&(gt.workspaceId=xe.workspaceId),(Dt=xe==null?void 0:xe.resumeSessionId)!=null&&Dt.trim()&&(gt.resumeSessionId=xe.resumeSessionId.trim()),Array.isArray(xe==null?void 0:xe.cliArgs)&&xe.cliArgs.length>0&&(gt.cliArgs=xe.cliArgs),(qt=xe==null?void 0:xe.initialModel)!=null&&qt.trim()&&(gt.initialModel=xe.initialModel.trim());const vt=await e(me,"launch_cli",gt),Et=(vt==null?void 0:vt.result)||vt,Js=(Et==null?void 0:Et.sessionId)||(Et==null?void 0:Et.id);return vt!=null&&vt.success&&Js?(Tr(Js),{ok:!0}):vt!=null&&vt.success?(Me({machineId:me,kind:ge,providerType:Ce,workspacePath:(xe==null?void 0:xe.workspacePath)||null,resumeSessionId:(xe==null?void 0:xe.resumeSessionId)||null,startedAt:qe}),{ok:!0}):{ok:!1,error:(vt==null?void 0:vt.error)||(Et==null?void 0:Et.error)||`Could not launch ${ge.toUpperCase()} session`}}catch(gt){return Sx(gt)?(Me({machineId:me,kind:ge,providerType:Ce,workspacePath:(xe==null?void 0:xe.workspacePath)||null,resumeSessionId:(xe==null?void 0:xe.resumeSessionId)||null,startedAt:qe}),{ok:!0}):{ok:!1,error:gt instanceof Error?gt.message:`Could not launch ${ge.toUpperCase()} session`}}},[Tr,e]),Ul=o.useCallback(async(me,ge)=>{if(!me||!ge)return[];try{const Ce=await e(me,"list_saved_sessions",{providerType:ge,kind:"cli",limit:30}),xe=(Ce==null?void 0:Ce.result)??Ce;return Array.isArray(xe==null?void 0:xe.sessions)?xe.sessions:[]}catch(Ce){return console.error("List saved sessions failed",Ce),[]}},[e]);o.useEffect(()=>{if(!Q)return;const me=Ci(Q.workspacePath),ge=f.find(xe=>{var gt,vt,Et,Js;if(!xe||xe.type==="adhdev-daemon"||kx(xe.daemonId||xe.id)!==Q.machineId||(xr(xe)?"cli":Ps(xe)?"acp":"ide")!==Q.kind||String(xe.agentType||xe.type||"")!==Q.providerType)return!1;if(Q.resumeSessionId)return String(xe.providerSessionId||"")===Q.resumeSessionId;if(me){const Rn=Ci(xe.workspace||xe.runtimeWorkspaceLabel);return Rn?Rn===me:!1}return Number(xe.lastUpdated||xe._lastUpdate||xe.timestamp||((Js=(Et=(vt=(gt=xe.activeChat)==null?void 0:gt.messages)==null?void 0:vt.at)==null?void 0:Et.call(vt,-1))==null?void 0:Js.timestamp)||0)>=Q.startedAt-5e3});if(!ge)return;const Ce=vc({entrySessionId:ge.sessionId,entryInstanceId:ge.instanceId,entryRouteId:ge.id,conversations:Fe});Ce&&(Me(null),Tr(Ce))},[Fe,Tr,f,Q]),o.useEffect(()=>{if(!Q)return;const me=window.setTimeout(()=>{Me(ge=>!ge||ge.startedAt!==Q.startedAt?ge:null)},45e3);return()=>window.clearTimeout(me)},[Q]),mf({visibleConversations:Ue,clearedTabs:ke,setClearedTabs:ve,setActionLogs:ie}),Sf({ides:f,sendDaemonCommand:e,setToasts:A,setLocalUserMessages:se,resolveConversationByTarget:wt});const{isRefreshingHistory:zl,handleRefreshHistory:Vl}=oi({sendDaemonCommand:e,activeConv:$e,chats:(Co=f.find(me=>me.id===($e==null?void 0:$e.routeId)))==null?void 0:Co.chats,updateRouteChats:w,setToasts:A,setLocalUserMessages:se,setClearedTabs:ve}),{isCreatingChat:Gl,isRefreshingHistory:ql,handleSwitchSession:Yl,handleNewChat:Xl,handleRefreshHistory:Jl}=oi({sendDaemonCommand:e,activeConv:dt,chats:(Io=f.find(me=>me.id===(dt==null?void 0:dt.routeId)))==null?void 0:Io.chats,updateRouteChats:w,setToasts:A,setLocalUserMessages:se,setClearedTabs:ve}),_n=o.useCallback(async()=>{if(!(!dt||!Ft||X)){he(!0);try{const me=dt.daemonId||dt.routeId,ge=Bt(dt),Ce=await e(me,"list_saved_sessions",{agentType:ge,providerType:ge,kind:"cli",limit:50}),xe=(Ce==null?void 0:Ce.result)??Ce;Se(Array.isArray(xe==null?void 0:xe.sessions)?xe.sessions:[])}catch(me){console.error("Refresh saved sessions failed",me),Se([])}finally{he(!1)}}},[dt,X,Ft,e]);o.useEffect(()=>{if(!N){Oe.current=null;return}if(!Ft){Oe.current=null,Se([]),he(!1);return}!Ar||X||Oe.current!==Ar&&(Oe.current=Ar,_n())},[_n,N,X,Ft,Ar]);const Ql=o.useCallback(async me=>{if(!dt||!Ft||!me.providerSessionId||!me.workspace)return;const ge=dt.daemonId||dt.routeId,Ce=Bt(dt);try{Z(me.providerSessionId);const xe=await e(ge,"launch_cli",{cliType:Ce,dir:me.workspace,resumeSessionId:me.providerSessionId,initialModel:cc(me.summaryMetadata,"model",{preferShortValue:!0})||void 0}),qe=(xe==null?void 0:xe.result)??xe,pt=typeof(qe==null?void 0:qe.sessionId)=="string"?qe.sessionId:typeof(qe==null?void 0:qe.id)=="string"?qe.id:"";pt&&i(Dt=>{const qt=new URLSearchParams(Dt);return qt.set("activeTab",pt),qt},{replace:!0}),D(!1)}catch(xe){console.error("Resume saved session failed",xe)}finally{Z(null)}},[dt,Ft,e,i]);$f({urlActiveTab:C&&!Mr?c:null,conversations:Fe,resolveConversationBySessionId:yt,normalizedGroupAssignments:rt,hasHydratedStoredLayout:C&&!Mr?R:!0,hydrateStoredLayout:C&&!Mr?U:()=>{},setGroupActiveTabIds:L,setFocusedGroup:x,setSearchParams:i,historyModalOpen:N,activeConv:$e,isRefreshingHistory:zl,ides:f,handleRefreshHistory:Vl});const yo=o.useCallback(async(me,ge)=>{const Ce=ge||W||$e;if(!Ce||!tt(Ce)&&!Ze(Ce))return;const xe=Bt(Ce),qe=Ce.routeId||Ce.daemonId||"";try{await e(qe,"stop_cli",{cliType:xe,targetSessionId:Ce.sessionId,mode:me})}catch(pt){console.error("Stop CLI failed:",pt)}},[$e,W,e]),Zl=o.useCallback(async me=>{const ge=me||$e;!ge||!tt(ge)&&!Ze(ge)||(ae(ge),q(!0))},[$e]),ed=o.useMemo(()=>!$e||!tt($e)||Ze($e)?null:Hs($e),[$e]),td=o.useCallback(async me=>{if(!$e||!tt($e)||Ze($e))return;const ge=Hs($e);if(ge===me)return;const Ce=$e.sessionId;Ce&&ne(xe=>({...xe,[Ce]:me}));try{await e(is($e)||$e.routeId,"set_cli_view_mode",{targetSessionId:$e.sessionId,cliType:Bt($e),mode:me})}catch(xe){const qe=co(xe);Ce&&!qe&&ne(pt=>{const Dt={...pt};return ge===tl(f,Ce)?delete Dt[Ce]:Dt[Ce]=ge,Dt}),io(xe)?console.warn(qe?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",xe instanceof Error?xe.message:String(xe)):console.error("Failed to switch CLI view mode:",xe)}},[$e,f,e]),{versionMismatchDaemons:sd,hasRequiredVersionDaemons:vo,appVersion:rd,versionBannerDismissed:nd,setVersionBannerDismissed:ad,upgradingDaemons:od,handleBannerUpgrade:id}=Uf({ides:f,sendDaemonCommand:e}),wo=o.useCallback(me=>{V(me.tabKey),i(ge=>{const Ce=new URLSearchParams(ge),xe=fm(me);return xe?Ce.set("activeTab",xe):Ce.delete("activeTab"),Ce},{replace:!0})},[i]),jo=o.useCallback(me=>{Tt(me.tabKey),wo(me)},[wo,Tt]),cd=o.useCallback(me=>{Ht(me.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(ap,{wsStatus:h,showReconnected:k}),t.jsx(op,{terminalBackend:Ge,isStandalone:Qe,machineLabel:ut,machineKey:it}),(!nd||vo)&&t.jsx(yx,{daemons:sd,targetVersion:rd,required:vo,upgradingDaemons:od,onUpgrade:id,onDismiss:()=>ad(!0)}),t.jsx(mx,{showMobileChatMode:Mr,isMobile:C,activeConv:$e,chatIdes:Xe,wsStatus:h,isConnected:S,onOpenHistory:me=>{me&&Ln(me),D(!0)},onOpenRemote:El,onStopCli:Zl,activeCliViewMode:ed,onSetActiveCliViewMode:td,mobileChatConversations:Kl,ides:f,actionLogs:ye,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:ie,isStandalone:Qe,initialDataLoaded:g,userName:m.userName,requestedMobileTabKey:es,onRequestedMobileTabConsumed:Ys,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:Be,isSplitMode:te,numGroups:$,groupSizes:B,groupedConvs:fe,clearedTabs:ke,focusedGroup:v,setFocusedGroup:x,moveTabToGroup:Ee,splitTabRelative:et,closeGroup:Le,handleResizeStart:Ne,groupActiveTabIds:E,setGroupActiveTabIds:L,groupTabOrders:M,setGroupTabOrders:T,toggleHiddenTab:Mt,visibleConversations:Ue,hiddenConversations:Bl,requestedDesktopTabKey:mt,onRequestedDesktopTabConsumed:Ys,onDesktopActiveTabChange:V,onHideConversation:cd,onShowHiddenConversation:jo,onShowAllHiddenConversations:Te,scrollToBottomRequest:we,machineEntries:Ke,onBrowseMachineDirectory:Ol,onSaveMachineWorkspace:Wl,onLaunchMachineIde:Hl,onLaunchMachineProvider:Fl,onListMachineSavedSessions:Ul,notifications:Re,notificationUnreadCount:P,notificationStateBySessionId:O,liveSessionInboxState:ee,onMarkNotificationRead:_e,onMarkNotificationUnread:Ae,onDeleteNotification:We,onMarkNotificationTargetRead:oe}),t.jsx("style",{children:`
|
|
59
|
+
`})]})}function gx({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 yx({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),u=o.useMemo(()=>Oc(s),[s]),p=o.useMemo(()=>e?to(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]),g=o.useMemo(()=>e?Wt(p,e.id):null,[p,e]);o.useEffect(()=>{i&&l(i)},[i]),o.useEffect(()=>{if(i||!g)return;const b=g.streamSource==="native"?"native":g.tabKey;!b||c===b||c==="native"&&l(b)},[c,g,i]),o.useEffect(()=>{var b;c!=="native"&&(f.some(y=>y.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 w=o.useMemo(()=>c==="native"&&m?m:f.find(b=>b.tabKey===c)||g||m||f[0],[c,m,g,f]),A=o.useMemo(()=>f.map(b=>({tabKey:b.tabKey,title:Pc(b)||a,status:b.status})),[f,a]),d=o.useCallback(b=>{if(b)return p.find(y=>hr(y,{sessionId:b,routeId:b,tabKey:b,providerSessionId:b}))},[p]);return{activeChatTab:c,setActiveChatTab:l,activeConv:w,conversations:p,extensionTabs:A,hasExtensions:A.length>0,resolveConversationByTarget:d}}function vx({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:g,onClose:w}){const[A,d]=o.useState("split"),[b,y]=o.useState(()=>ns(e)?"native":e.tabKey),h=o.useRef(null),S=o.useMemo(()=>s||r.find(N=>N.id===e.routeId),[e.routeId,s,r]),_=o.useMemo(()=>ot((S==null?void 0:S.type)||""),[S==null?void 0:S.type]),{conversations:k,extensionTabs:I,hasExtensions:j}=yx({ideData:S,allIdes:r,connectionStates:n,localUserMessages:i,ideName:_||"IDE",preferredTabKey:ns(e)?void 0:e.tabKey}),v=o.useMemo(()=>S?Wt(k,S.id):null,[S,k]);o.useEffect(()=>{const N=h.current,D={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=D,!(N&&N.routeId===D.routeId&&N.tabKey===D.tabKey&&N.streamSource===D.streamSource)){if(ns(e)){y("native");return}y(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(b==="native"){if(k.some(N=>N.streamSource==="native"))return;(v==null?void 0:v.streamSource)==="agent-stream"&&y(v.tabKey);return}if(!k.some(N=>N.tabKey===b)){if((v==null?void 0:v.streamSource)==="agent-stream"){y(v.tabKey);return}y("native")}},[k,b,v]);const x=o.useMemo(()=>b==="native"?k.find(N=>N.streamSource==="native")||e:k.find(N=>N.tabKey===b)||e,[e,k,b]),E=Zc(x),L=o.useMemo(()=>E.status||E.modalMessage||E.modalButtons?{...x,...E.status?{status:E.status}:{},...E.modalMessage!==void 0?{modalMessage:E.modalMessage}:{},...E.modalButtons!==void 0?{modalButtons:E.modalButtons}:{}}:x,[x,E]),M=kr(L),T=kn({sendDaemonCommand:c,activeConv:L,setLocalUserMessages:l,setActionLogs:u,isStandalone:p}),{connScreenshot:B,screenshotUsage:H,handleRemoteAction:C}=bl({doId:M,targetSessionId:gc(L),connState:L.connectionState||"new",viewMode:A}),R=o.useMemo(()=>a.filter(N=>N.routeId===L.tabKey),[a,L.tabKey]);o.useEffect(()=>{g==null||g(L)},[L,g]),o.useEffect(()=>{const N=D=>{D.key==="Escape"&&w()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[w]);const U=o.useCallback(N=>{N.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:w,children:t.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:U,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(Rt,{size:16})}),t.jsx("span",{className:"truncate",children:Ua(x)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:w,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(N=>{const D=A===N;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(N),title:N==="split"?"Split view":"Remote only",children:N==="split"?t.jsx(Od,{size:15}):t.jsx(Rt,{size:15})},N)})}),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(Da,{size:14,className:"md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"History"})]}),t.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:w,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${A==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[A!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${A==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(gx,{hasExtensions:j,ideName:_||"IDE",activeChatTab:b,extensionTabs:I,onSelectTab:y}),t.jsx(nc,{activeConv:L,onModalButton:T.handleModalButton}),t.jsx(va,{activeConv:L,ideEntry:S,showMetaChips:!1,handleSendChat:T.handleSendChat,isSendingChat:T.isSendingChat,sendFeedbackMessage:T.sendFeedbackMessage,handleFocusAgent:T.handleFocusAgent,isFocusingAgent:T.isFocusingAgent,actionLogs:R,userName:m})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${A==="split"?"order-1 md:order-2":""}`,children:t.jsx(ec,{addLog:()=>{},connState:L.connectionState||"new",connScreenshot:B,screenshotUsage:H,transportType:L.transport,onAction:C})})]})]})})}function wx({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=cp(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 jx({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:g,remoteDialogConv:w,remoteDialogIdeEntry:A,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:h,setLocalUserMessages:S,setActionLogs:_,isStandalone:k,userName:I,onOpenRemoteHistory:j,onRemoteConversationChange:v,onCloseRemoteDialog:x,cliStopDialogOpen:E,cliStopTargetConv:L,onCancelCliStop:M,onStopCliNow:T,onSaveCliAndStop:B,toasts:H,onDismissToast:C,onClickToast:R,showOnboarding:U,onCloseOnboarding:N}){var q;const[D,Y]=at.useState(()=>jt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(eo,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:D,onSavedHistoryFiltersChange:Y,onClose:u,onNewChat:p,onSwitchSession:m,onRefreshHistory:f,onResumeSavedSession:g}),w&&t.jsx(vx,{activeConv:w,ideEntry:A,ides:r,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:h,setLocalUserMessages:S,setActionLogs:_,isStandalone:k,userName:I,onOpenHistory:j,onConversationChange:v,onClose:x}),E&&L&&(tt(L)||Ze(L))&&t.jsx(wx,{activeConv:L,canSaveAndStop:tt(L)&&!Ze(L)&&!!((q=L.resume)!=null&&q.supported),onCancel:M,onStopNow:T,onSaveAndStop:B}),t.jsx(Bc,{toasts:H,onDismiss:C,onClickToast:R}),U&&t.jsx(bx,{onClose:N})]})}function kx({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:t.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[t.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:t.jsx(Gs,{size:14})}),t.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[t.jsxs("span",{children:[r?"Daemon update required":"Update available",s?t.jsxs(t.Fragment,{children:[": ",t.jsxs("strong",{children:["v",s]})]}):null]}),e.map(c=>{const l=_t(c,{fallbackId:c.id}),u=n[c.id],p=c.version||c.daemonVersion||"unknown",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(At,{size:16})})]})}function Sx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Nx(e){const s=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?s===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function Cx(e){const s=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",s,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&s&&s!==r),autoReadKey:i,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Ix(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Ii(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ax(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Mx(){var ko,So,No,Co,Io;const{sendCommand:e}=Pt(),s=Sr(),r=_a(),n=Vs(),[a,i]=hd(),c=a.get("activeTab"),l=((ko=r.state)==null?void 0:ko.openRemoteForTabKey)||null,u=((So=r.state)==null?void 0:So.openMachineId)||null,p=((No=r.state)==null?void 0:No.mobileSection)||null,m=Mc(),f=m.ides||[],g=m.initialLoaded??!0,{updateRouteChats:w,setToasts:A}=m,[d,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=m.toasts||[],h=m.wsStatus||"connected",S=m.isConnected??!0,_=m.connectionStates||{},k=m.showReconnected||!1,{groupAssignments:I,setGroupAssignments:j,focusedGroup:v,setFocusedGroup:x,groupActiveTabIds:E,setGroupActiveTabIds:L,groupTabOrders:M,setGroupTabOrders:T,groupSizes:B,setGroupSizes:H,isMobile:C,hasHydratedStoredLayout:R,hydrateStoredLayout:U}=Bf(),[N,D]=o.useState(!1),[Y,q]=o.useState(!1),[W,ae]=o.useState(null),[ce,Se]=o.useState([]),[X,he]=o.useState(!1),[J,Z]=o.useState(null),[ue,de]=o.useState(()=>ao());o.useEffect(()=>af(de),[]);const z=o.useMemo(()=>Sx({isMobile:C,mobileViewMode:ue}),[C,ue]),[ye,ie]=o.useState([]),[le,se]=o.useState({}),[pe,ne]=o.useState({}),[ke,ve]=o.useState({}),[K,V]=o.useState(null),[we,be]=o.useState(null),[Q,Me]=o.useState(null),Oe=o.useRef(null);wr("Dashboard",{ideCount:f.length,toastCount:y.length,focusedGroup:v,groupCount:Object.keys(I).length,localMessageTabs:Object.keys(le).length,actionLogCount:ye.length});const Pe=f.find(me=>me.type==="adhdev-daemon"),Ke=o.useMemo(()=>f.filter(me=>me.type==="adhdev-daemon").sort(Wa),[f]),Qe=!!Pe;o.useEffect(()=>{!Pe||!(!Pe.detectedIdes||!Pe.availableProviders||!Pe.recentLaunches||!Pe.workspaces)||s(Pe.id,{minFreshMs:3e4}).catch(()=>{})},[Pe,s]);const Ge=(Pe==null?void 0:Pe.terminalBackend)||null,ut=Pe?_t(Pe,{fallbackId:Pe.id}):null,it=(Pe==null?void 0:Pe.id)||null,ht=o.useMemo(()=>ff(f,pe),[f,pe]),{hiddenTabs:ze,hideTab:xt,toggleTab:bt,showTab:ct,showAllTabs:Te}=pf(),{chatIdes:Xe,conversations:Fe,visibleConversations:Ue,visibleTabKeys:kt,resolveConversationBySessionId:yt,resolveConversationByTarget:wt}=Cf({ides:ht,connectionStates:_,localUserMessages:le,clearedTabs:ke,hiddenTabs:ze}),St=o.useMemo(()=>new Map(Fe.map(me=>[me.tabKey,Wr(me)])),[Fe]),Ht=o.useCallback(me=>{const ge=St.get(me)||Wr({tabKey:me});xt(ge)},[St,xt]),Mt=o.useCallback(me=>{const ge=St.get(me)||Wr({tabKey:me});bt(ge)},[St,bt]),Tt=o.useCallback(me=>{const ge=St.get(me)||Wr({tabKey:me});ct(ge)},[St,ct]);Xm(Ue,z),o.useEffect(()=>{Object.keys(pe).length!==0&&ne(me=>hf(me,f))},[f,pe]);const ee=o.useMemo(()=>wu(f),[f]),{notifications:Re,unreadCount:P,notificationStateBySessionId:O,markRead:F,markUnread:G,markTargetRead:oe,deleteNotification:Ie}=dh({conversations:Fe,liveSessionInboxState:ee}),_e=o.useCallback(me=>{const ge=Re.find(xe=>xe.id===me),Ce=Math.max(Date.now(),(ge==null?void 0:ge.updatedAt)||0);F(me,Ce),ge!=null&&ge.sessionId&&e(ge.machineId||ge.routeId,"mark_session_seen",{sessionId:ge.sessionId,seenAt:Ce}).catch(()=>{})},[F,Re,e]),Ae=o.useCallback(me=>{const ge=Re.find(Ce=>Ce.id===me);G(me),ge!=null&&ge.sessionId&&e(ge.machineId||ge.routeId,"mark_notification_unread",{sessionId:ge.sessionId,notificationId:ge.id}).catch(()=>{})},[G,Re,e]),We=o.useCallback(me=>{const ge=Re.find(Ce=>Ce.id===me);Ie(me),ge!=null&&ge.sessionId&&e(ge.machineId||ge.routeId,"delete_notification",{sessionId:ge.sessionId,notificationId:ge.id}).catch(()=>{})},[Ie,Re,e]),De=o.useRef(null),Je=o.useRef(null),Ve=o.useRef(null),re=o.useRef(null),je=o.useRef(null),{containerRef:Be,normalizedGroupAssignments:rt,numGroups:$,isSplitMode:te,groupedConvs:fe,moveTabToGroup:Ee,closeGroup:Le,handleResizeStart:Ne,splitTabRelative:et}=Gf({groupAssignments:I,setGroupAssignments:j,setFocusedGroup:x,setGroupActiveTabIds:L,setGroupTabOrders:T,groupSizes:B,setGroupSizes:H,isMobile:C,visibleConversations:Ue,visibleTabKeys:kt}),$e=o.useMemo(()=>{var ge,Ce;if(!C){if(K){const xe=Fe.find(qe=>qe.tabKey===K);if(xe)return xe}return Ue[0]}const me=E[v];if(me){const xe=Fe.find(qe=>qe.tabKey===me);if(xe)return xe}return((ge=fe[v])==null?void 0:ge[0])||((Ce=fe[0])==null?void 0:Ce[0])},[K,C,E,v,Fe,fe,Ue]);o.useEffect(()=>{const me=()=>{Ve.current&&(clearTimeout(Ve.current),Ve.current=null),re.current&&(clearTimeout(re.current),re.current=null),je.current&&(document.removeEventListener("visibilitychange",je.current),je.current=null),Je.current=null};if(C){me(),De.current=null;return}if(!($e!=null&&$e.sessionId)){me(),De.current=null;return}const ge=ln($e,ee),Ce=Cx({tabKey:$e.tabKey,historySessionId:jr($e)||"",lastMessageHash:$e.lastMessageHash||"",lastMessageAt:Number($e.lastMessageAt||0),timestamp:ps($e),liveState:ge}),xe=Ce.autoReadKey,qe=Nx({autoReadKey:xe,shouldMarkSeen:Ce.shouldMarkSeen,completedKey:De.current,pendingKey:Je.current});if(!Ce.shouldMarkSeen){qe.shouldCancelPending&&me(),De.current=xe;return}if(!qe.shouldSchedule)return;qe.shouldCancelPending&&me();const pt=sc($e),Dt=()=>{if(document.visibilityState!=="visible"||De.current===xe)return;De.current=xe,Je.current=null,Ve.current=null,re.current=null,je.current&&(document.removeEventListener("visibilitychange",je.current),je.current=null);const gt=Ce.readAt;oe({...pt},gt),e($e.daemonId||$e.routeId,"mark_session_seen",{sessionId:$e.sessionId,seenAt:gt}).catch(()=>{})};if(Je.current=qe.nextPendingKey,document.visibilityState==="visible"){Ve.current=setTimeout(Dt,1500);const gt=()=>{document.visibilityState!=="visible"&&Ve.current&&(clearTimeout(Ve.current),Ve.current=null)};je.current=gt,document.addEventListener("visibilitychange",gt);return}const qt=()=>{document.visibilityState==="visible"&&(re.current&&clearTimeout(re.current),re.current=setTimeout(Dt,800),je.current&&(document.removeEventListener("visibilitychange",je.current),je.current=null))};je.current=qt,document.addEventListener("visibilitychange",qt)},[$e,C,ee,oe,e]),o.useEffect(()=>()=>{Ve.current&&clearTimeout(Ve.current),re.current&&clearTimeout(re.current),je.current&&document.removeEventListener("visibilitychange",je.current)},[]);const{requestedDesktopTabKey:mt,requestedMobileTabKey:es,consumeRequestedActiveTab:Ys}=If({isMobile:C,urlActiveTab:c,resolveConversationBySessionId:yt,setSearchParams:i}),{remoteDialogConv:Xs,remoteDialogIdeEntry:Ir,remoteDialogActiveConv:El,setRemoteDialogActiveConv:Ln,openRemoteDialog:$l,closeRemoteDialog:Kl}=Hf({isMobile:C,location:r,navigate:n,requestedRemoteTabTarget:l,requestedDesktopTabKey:mt,conversations:Fe,ides:f,resolveConversationByTarget:wt}),dt=El||Xs||$e,Ft=!!dt&&tt(dt)&&!Ze(dt),Ar=o.useMemo(()=>{if(!dt||!Ft)return null;const me=dt.daemonId||dt.routeId||"",ge=Bt(dt);return`${me}:${ge}`},[dt,Ft]),Bl=o.useMemo(()=>Ue,[Ue]),Mr=C&&ue==="chat",Ol=o.useMemo(()=>Fe.filter(me=>oo(ze,me)),[Fe,ze]),Tr=o.useCallback(me=>{const ge=new URLSearchParams(a);ge.set("activeTab",me),i(ge,{replace:!0})},[a,i]),Wl=o.useCallback(async(me,ge)=>Cn(e,me,ge),[e]),Hl=o.useCallback(async(me,ge)=>{if(!ge.trim())return{ok:!1,error:"Choose a workspace path first."};try{const Ce=await e(me,"workspace_add",{path:ge.trim()});return Ce!=null&&Ce.success?{ok:!0}:{ok:!1,error:(Ce==null?void 0:Ce.error)||"Could not save workspace"}}catch(Ce){return{ok:!1,error:Ce instanceof Error?Ce.message:"Could not save workspace"}}},[e]),Fl=o.useCallback(async(me,ge,Ce)=>{var xe;try{const qe={ideType:ge,enableCdp:!0};(xe=Ce==null?void 0:Ce.workspacePath)!=null&&xe.trim()&&(qe.workspace=Ce.workspacePath.trim());const pt=await e(me,"launch_ide",qe);return!(pt!=null&&pt.success)&&(pt==null?void 0:pt.success)!==void 0?{ok:!1,error:(pt==null?void 0:pt.error)||"Could not launch IDE"}:(Me({machineId:me,kind:"ide",providerType:ge,workspacePath:(Ce==null?void 0:Ce.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(qe){return{ok:!1,error:qe instanceof Error?qe.message:"Could not launch IDE"}}},[e]),Ul=o.useCallback(async(me,ge,Ce,xe)=>{var pt,Dt,qt;const qe=Date.now();try{const gt={cliType:Ce};(pt=xe==null?void 0:xe.workspacePath)!=null&&pt.trim()?gt.dir=xe.workspacePath.trim():xe!=null&&xe.workspaceId&&(gt.workspaceId=xe.workspaceId),(Dt=xe==null?void 0:xe.resumeSessionId)!=null&&Dt.trim()&&(gt.resumeSessionId=xe.resumeSessionId.trim()),Array.isArray(xe==null?void 0:xe.cliArgs)&&xe.cliArgs.length>0&&(gt.cliArgs=xe.cliArgs),(qt=xe==null?void 0:xe.initialModel)!=null&&qt.trim()&&(gt.initialModel=xe.initialModel.trim());const vt=await e(me,"launch_cli",gt),Et=(vt==null?void 0:vt.result)||vt,Js=(Et==null?void 0:Et.sessionId)||(Et==null?void 0:Et.id);return vt!=null&&vt.success&&Js?(Tr(Js),{ok:!0}):vt!=null&&vt.success?(Me({machineId:me,kind:ge,providerType:Ce,workspacePath:(xe==null?void 0:xe.workspacePath)||null,resumeSessionId:(xe==null?void 0:xe.resumeSessionId)||null,startedAt:qe}),{ok:!0}):{ok:!1,error:(vt==null?void 0:vt.error)||(Et==null?void 0:Et.error)||`Could not launch ${ge.toUpperCase()} session`}}catch(gt){return Ax(gt)?(Me({machineId:me,kind:ge,providerType:Ce,workspacePath:(xe==null?void 0:xe.workspacePath)||null,resumeSessionId:(xe==null?void 0:xe.resumeSessionId)||null,startedAt:qe}),{ok:!0}):{ok:!1,error:gt instanceof Error?gt.message:`Could not launch ${ge.toUpperCase()} session`}}},[Tr,e]),zl=o.useCallback(async(me,ge)=>{if(!me||!ge)return[];try{const Ce=await e(me,"list_saved_sessions",{providerType:ge,kind:"cli",limit:30}),xe=(Ce==null?void 0:Ce.result)??Ce;return Array.isArray(xe==null?void 0:xe.sessions)?xe.sessions:[]}catch(Ce){return console.error("List saved sessions failed",Ce),[]}},[e]);o.useEffect(()=>{if(!Q)return;const me=Ii(Q.workspacePath),ge=f.find(xe=>{var gt,vt,Et,Js;if(!xe||xe.type==="adhdev-daemon"||Ix(xe.daemonId||xe.id)!==Q.machineId||(xr(xe)?"cli":Ps(xe)?"acp":"ide")!==Q.kind||String(xe.agentType||xe.type||"")!==Q.providerType)return!1;if(Q.resumeSessionId)return String(xe.providerSessionId||"")===Q.resumeSessionId;if(me){const Rn=Ii(xe.workspace||xe.runtimeWorkspaceLabel);return Rn?Rn===me:!1}return Number(xe.lastUpdated||xe._lastUpdate||xe.timestamp||((Js=(Et=(vt=(gt=xe.activeChat)==null?void 0:gt.messages)==null?void 0:vt.at)==null?void 0:Et.call(vt,-1))==null?void 0:Js.timestamp)||0)>=Q.startedAt-5e3});if(!ge)return;const Ce=wc({entrySessionId:ge.sessionId,entryInstanceId:ge.instanceId,entryRouteId:ge.id,conversations:Fe});Ce&&(Me(null),Tr(Ce))},[Fe,Tr,f,Q]),o.useEffect(()=>{if(!Q)return;const me=window.setTimeout(()=>{Me(ge=>!ge||ge.startedAt!==Q.startedAt?ge:null)},45e3);return()=>window.clearTimeout(me)},[Q]),xf({visibleConversations:Ue,clearedTabs:ke,setClearedTabs:ve,setActionLogs:ie}),Af({ides:f,sendDaemonCommand:e,setToasts:A,setLocalUserMessages:se,resolveConversationByTarget:wt});const{isRefreshingHistory:Vl,handleRefreshHistory:Gl}=ii({sendDaemonCommand:e,activeConv:$e,chats:(Co=f.find(me=>me.id===($e==null?void 0:$e.routeId)))==null?void 0:Co.chats,updateRouteChats:w,setToasts:A,setLocalUserMessages:se,setClearedTabs:ve}),{isCreatingChat:ql,isRefreshingHistory:Yl,handleSwitchSession:Xl,handleNewChat:Jl,handleRefreshHistory:Ql}=ii({sendDaemonCommand:e,activeConv:dt,chats:(Io=f.find(me=>me.id===(dt==null?void 0:dt.routeId)))==null?void 0:Io.chats,updateRouteChats:w,setToasts:A,setLocalUserMessages:se,setClearedTabs:ve}),_n=o.useCallback(async()=>{if(!(!dt||!Ft||X)){he(!0);try{const me=dt.daemonId||dt.routeId,ge=Bt(dt),Ce=await e(me,"list_saved_sessions",{agentType:ge,providerType:ge,kind:"cli",limit:50}),xe=(Ce==null?void 0:Ce.result)??Ce;Se(Array.isArray(xe==null?void 0:xe.sessions)?xe.sessions:[])}catch(me){console.error("Refresh saved sessions failed",me),Se([])}finally{he(!1)}}},[dt,X,Ft,e]);o.useEffect(()=>{if(!N){Oe.current=null;return}if(!Ft){Oe.current=null,Se([]),he(!1);return}!Ar||X||Oe.current!==Ar&&(Oe.current=Ar,_n())},[_n,N,X,Ft,Ar]);const Zl=o.useCallback(async me=>{if(!dt||!Ft||!me.providerSessionId||!me.workspace)return;const ge=dt.daemonId||dt.routeId,Ce=Bt(dt);try{Z(me.providerSessionId);const xe=await e(ge,"launch_cli",{cliType:Ce,dir:me.workspace,resumeSessionId:me.providerSessionId,initialModel:lc(me.summaryMetadata,"model",{preferShortValue:!0})||void 0}),qe=(xe==null?void 0:xe.result)??xe,pt=typeof(qe==null?void 0:qe.sessionId)=="string"?qe.sessionId:typeof(qe==null?void 0:qe.id)=="string"?qe.id:"";pt&&i(Dt=>{const qt=new URLSearchParams(Dt);return qt.set("activeTab",pt),qt},{replace:!0}),D(!1)}catch(xe){console.error("Resume saved session failed",xe)}finally{Z(null)}},[dt,Ft,e,i]);Wf({urlActiveTab:C&&!Mr?c:null,conversations:Fe,resolveConversationBySessionId:yt,normalizedGroupAssignments:rt,hasHydratedStoredLayout:C&&!Mr?R:!0,hydrateStoredLayout:C&&!Mr?U:()=>{},setGroupActiveTabIds:L,setFocusedGroup:x,setSearchParams:i,historyModalOpen:N,activeConv:$e,isRefreshingHistory:Vl,ides:f,handleRefreshHistory:Gl});const yo=o.useCallback(async(me,ge)=>{const Ce=ge||W||$e;if(!Ce||!tt(Ce)&&!Ze(Ce))return;const xe=Bt(Ce),qe=Ce.routeId||Ce.daemonId||"";try{await e(qe,"stop_cli",{cliType:xe,targetSessionId:Ce.sessionId,mode:me})}catch(pt){console.error("Stop CLI failed:",pt)}},[$e,W,e]),ed=o.useCallback(async me=>{const ge=me||$e;!ge||!tt(ge)&&!Ze(ge)||(ae(ge),q(!0))},[$e]),td=o.useMemo(()=>!$e||!tt($e)||Ze($e)?null:Hs($e),[$e]),sd=o.useCallback(async me=>{if(!$e||!tt($e)||Ze($e))return;const ge=Hs($e);if(ge===me)return;const Ce=$e.sessionId;Ce&&ne(xe=>({...xe,[Ce]:me}));try{await e(is($e)||$e.routeId,"set_cli_view_mode",{targetSessionId:$e.sessionId,cliType:Bt($e),mode:me})}catch(xe){const qe=co(xe);Ce&&!qe&&ne(pt=>{const Dt={...pt};return ge===sl(f,Ce)?delete Dt[Ce]:Dt[Ce]=ge,Dt}),io(xe)?console.warn(qe?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",xe instanceof Error?xe.message:String(xe)):console.error("Failed to switch CLI view mode:",xe)}},[$e,f,e]),{versionMismatchDaemons:rd,hasRequiredVersionDaemons:vo,appVersion:nd,versionBannerDismissed:ad,setVersionBannerDismissed:od,upgradingDaemons:id,handleBannerUpgrade:cd}=qf({ides:f,sendDaemonCommand:e}),wo=o.useCallback(me=>{V(me.tabKey),i(ge=>{const Ce=new URLSearchParams(ge),xe=hm(me);return xe?Ce.set("activeTab",xe):Ce.delete("activeTab"),Ce},{replace:!0})},[i]),jo=o.useCallback(me=>{Tt(me.tabKey),wo(me)},[wo,Tt]),ld=o.useCallback(me=>{Ht(me.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(dp,{wsStatus:h,showReconnected:k}),t.jsx(up,{terminalBackend:Ge,isStandalone:Qe,machineLabel:ut,machineKey:it}),(!ad||vo)&&t.jsx(kx,{daemons:rd,targetVersion:nd,required:vo,upgradingDaemons:id,onUpgrade:cd,onDismiss:()=>od(!0)}),t.jsx(xx,{showMobileChatMode:Mr,isMobile:C,activeConv:$e,chatIdes:Xe,wsStatus:h,isConnected:S,onOpenHistory:me=>{me&&Ln(me),D(!0)},onOpenRemote:$l,onStopCli:ed,activeCliViewMode:td,onSetActiveCliViewMode:sd,mobileChatConversations:Bl,ides:f,actionLogs:ye,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:ie,isStandalone:Qe,initialDataLoaded:g,userName:m.userName,requestedMobileTabKey:es,onRequestedMobileTabConsumed:Ys,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:Be,isSplitMode:te,numGroups:$,groupSizes:B,groupedConvs:fe,clearedTabs:ke,focusedGroup:v,setFocusedGroup:x,moveTabToGroup:Ee,splitTabRelative:et,closeGroup:Le,handleResizeStart:Ne,groupActiveTabIds:E,setGroupActiveTabIds:L,groupTabOrders:M,setGroupTabOrders:T,toggleHiddenTab:Mt,visibleConversations:Ue,hiddenConversations:Ol,requestedDesktopTabKey:mt,onRequestedDesktopTabConsumed:Ys,onDesktopActiveTabChange:V,onHideConversation:ld,onShowHiddenConversation:jo,onShowAllHiddenConversations:Te,scrollToBottomRequest:we,machineEntries:Ke,onBrowseMachineDirectory:Wl,onSaveMachineWorkspace:Hl,onLaunchMachineIde:Fl,onLaunchMachineProvider:Ul,onListMachineSavedSessions:zl,notifications:Re,notificationUnreadCount:P,notificationStateBySessionId:O,liveSessionInboxState:ee,onMarkNotificationRead:_e,onMarkNotificationUnread:Ae,onDeleteNotification:We,onMarkNotificationTargetRead:oe}),t.jsx("style",{children:`
|
|
60
60
|
body { overflow: hidden; overscroll-behavior: none; }
|
|
61
|
-
`}),t.jsx(
|
|
61
|
+
`}),t.jsx(jx,{historyModalOpen:N,historyTargetConv:dt,ides:f,isHistoryCreatingChat:ql,isHistoryRefreshingHistory:Ft?!1:Yl,savedHistorySessions:ce,isSavedHistoryLoading:X,isResumingSavedHistorySessionId:J,onCloseHistory:()=>D(!1),onNewHistoryChat:Jl,onSwitchHistorySession:Xl,onRefreshHistory:Ft?_n:Ql,onResumeSavedHistorySession:Zl,remoteDialogConv:Xs,remoteDialogIdeEntry:Ir,connectionStates:_,actionLogs:ye,localUserMessages:le,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:ie,isStandalone:Qe,userName:m.userName,onOpenRemoteHistory:me=>{me&&Ln(me),D(!0)},onRemoteConversationChange:Ln,onCloseRemoteDialog:Kl,cliStopDialogOpen:Y,cliStopTargetConv:W,onCancelCliStop:()=>{q(!1),ae(null)},onStopCliNow:async()=>{q(!1),await yo("hard",W),ae(null)},onSaveCliAndStop:async()=>{q(!1),await yo("save",W),ae(null)},toasts:y,onDismissToast:me=>A(ge=>ge.filter(Ce=>Ce.id!==me)),onClickToast:me=>{if(me.targetKey){const ge=wt(me.targetKey);ge&&(x(rt.get(ge.tabKey)??0),jo(ge),be({tabKey:ge.tabKey,nonce:Date.now()}))}},showOnboarding:d,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function Tx({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,g]=o.useState(!1),[w,A]=o.useState(null),[d,b]=o.useState(!1),[y,h]=o.useState(""),S=o.useRef(null),_=o.useCallback(N=>{S.current=N},[]),k=o.useCallback((N,D,Y=!1)=>{c(q=>[...q.slice(-100),{timestamp:Date.now(),level:N,message:D}]),setTimeout(()=>{var q;return(q=a.current)==null?void 0:q.scrollIntoView({behavior:"smooth"})},100),Y&&st.showToast(D,N==="error"||N==="warn"?"warning":"success")},[a]),I=o.useCallback(N=>{const D=N instanceof Error?N.message:String(N||"");return D.includes("P2P command timeout")||D.includes("P2P not connected")||D.includes("P2P not available")},[]),j=o.useCallback(async(N,D)=>{var Y;if(!e||l)return!1;u(N),k("info",`Launching ${ot(N)}${D!=null&&D.workspace?` in ${D.workspace}`:""}...`);try{const q={ideType:N,enableCdp:!0};(Y=D==null?void 0:D.workspace)!=null&&Y.trim()?q.workspace=D.workspace.trim():D!=null&&D.useDefaultWorkspace&&(q.useDefaultWorkspace=!0);const W=await r(e,"launch_ide",q);return k(W!=null&&W.success?"info":"error",W!=null&&W.success?`${ot(N)} launched`:`Failed: ${W==null?void 0:W.error}`,!0),!!(W!=null&&W.success)}catch(q){return k("error",`Launch error: ${q.message}`,!0),!1}finally{u(null)}},[e,l,k,r]),v=o.useCallback(async N=>{if(!e)return{success:!1};const{cliType:D,dir:Y,workspaceId:q,useDefaultWorkspace:W,useHome:ae,argsStr:ce,model:Se,resumeSessionId:X}=N;if(!D)return k("warn","Select a CLI or ACP provider first",!0),{success:!1};const he=ce?ce.split(/\s+/).filter(Boolean):void 0,J=(Y==null?void 0:Y.trim())||(q?"(saved id)":W?"(default workspace)":ae?"(home)":"");k("info",`Launching ${D}${J?` in ${J}`:""}${Se?` (model: ${Se})`:""}...`),m(D);try{const Z={cliType:D,cliArgs:he,initialModel:Se||void 0};Y!=null&&Y.trim()?Z.dir=Y.trim():q?Z.workspaceId=q:W?Z.useDefaultWorkspace=!0:ae&&(Z.useHome=!0),X&&(Z.resumeSessionId=X);const ue=await r(e,"launch_cli",Z),de=(ue==null?void 0:ue.result)||ue;return ue!=null&&ue.success?(k("info",`${D} launched`,!0),(de==null?void 0:de.launchSource)==="home"?k("info","📂 Running in home directory (explicit choice)"):(de==null?void 0:de.launchSource)==="defaultWorkspace"&&k("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:de==null?void 0:de.sessionId}):(k("error",`Failed: ${(ue==null?void 0:ue.error)||(de==null?void 0:de.error)}`,!0),(ue==null?void 0:ue.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&A({cliType:D,argsStr:ce,model:Se}),{success:!1,sessionId:de==null?void 0:de.sessionId})}catch(Z){return I(Z)?(k("warn",`${D} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(k("error",`Launch error: ${Z.message}`,!0),{success:!1})}finally{m(null)}},[e,k,I,r]),x=o.useCallback(async(N,D,Y,q)=>e?N?D.trim()?v({cliType:N,dir:D,argsStr:Y,model:q}):(A({cliType:N,argsStr:Y,model:q}),{success:!1}):(k("warn","Select a provider",!0),{success:!1}):{success:!1},[e,k,v]),E=o.useCallback(async(N,D,Y)=>{if(e&&window.confirm(`Stop ${N}?
|
|
62
62
|
This will terminate the process.`))try{const q=await r(e,"stop_cli",{cliType:N,dir:D,targetSessionId:Y});q!=null&&q.success?k("info",`${N} stopped`,!0):k("error",`Stop failed: ${(q==null?void 0:q.error)||"Unknown error"}`,!0)}catch(q){k("error",`Stop failed: ${q.message}`,!0)}},[e,k,r]),L=o.useCallback(async N=>{try{await r(N.daemonId,"restart_ide",{ideType:N.type}),k("info",`${ot(N.type)} restart initiated`,!0)}catch(D){k("error",`Restart failed: ${D.message}`,!0)}},[k,r]),M=o.useCallback(async N=>{if(window.confirm(`Stop ${ot(N.type)}?
|
|
63
|
-
This will disconnect CDP and optionally kill the process.`))try{const D=await r(N.daemonId,"stop_ide",{ideType:N.type,killProcess:!0});D!=null&&D.success?k("info",`${ot(N.type)} stopped`,!0):k("error",`Stop failed: ${(D==null?void 0:D.error)||"Unknown error"}`,!0)}catch(D){k("error",`Stop failed: ${D.message}`,!0)}},[k,r]),T=o.useCallback(async()=>{if(e)try{const N=await r(e,"detect_ides",{});k("info",`Found ${((N==null?void 0:N.result)||[]).length} IDE(s)`,!0)}catch(N){k("error",`Detection failed: ${N.message}`,!0)}},[e,k,r]),B=o.useCallback(async N=>{if(!e||!N.trim())return!1;g(!0);try{const D=await r(e,"workspace_add",{path:N.trim()});return D!=null&&D.success?(k("info",`Workspace added: ${N.trim()}`),!0):(k("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return k("error",D.message),!1}finally{g(!1)}},[e,k,r]),H=o.useCallback(async N=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const D=await r(e,"workspace_remove",{id:N});D!=null&&D.success?k("info","Workspace removed",!0):k("error",(D==null?void 0:D.error)||"workspace_remove failed",!0)}catch(D){k("error",D.message,!0)}finally{g(!1)}}},[e,k,r]),C=o.useCallback(async N=>{var D;if(e){g(!0);try{const Y=await r(e,"workspace_set_default",N===null?{clear:!0}:{id:N});if(Y!=null&&Y.success){k("info",N?"Default workspace updated":"Default workspace cleared",!0);const q=typeof Y.defaultWorkspacePath=="string"?Y.defaultWorkspacePath:"";q&&((D=S.current)==null||D.call(S,q))}else k("error",(Y==null?void 0:Y.error)||"workspace_set_default failed",!0)}catch(Y){k("error",Y.message,!0)}finally{g(!1)}}},[e,k,r]),R=o.useCallback(async N=>{var Y;if(!e||!N.trim())return;const D=N.trim();g(!0);try{const q=await r(e,"workspace_set_default",{path:D});q!=null&&q.success?(k("info","Default workspace set from history"),(Y=S.current)==null||Y.call(S,D)):k("error",(q==null?void 0:q.error)||"Could not set default (path missing on disk?)")}catch(q){k("error",q.message)}finally{g(!1)}},[e,k,r]),U=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:y})}catch(N){k("warn",`Live nickname updated, but account sync failed: ${N.message}`)}k("info",`Nickname set to "${y||"(cleared)"}"`),b(!1)}catch(N){k("error",`Failed: ${N.message}`)}},[e,y,s,k,n,r]);return{logs:i,launchingIde:l,launchingAgentType:p,workspaceBusy:f,launchPick:w,setLaunchPick:A,editingNickname:d,setEditingNickname:b,nicknameInput:y,setNicknameInput:h,addLog:k,handleLaunchIde:j,runLaunchCliCore:v,handleLaunchCli:x,handleStopCli:E,handleRestartIde:L,handleStopIde:M,handleDetectIdes:T,handleWorkspaceAdd:B,handleWorkspaceRemove:H,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:R,handleSaveNickname:U,setOnDefaultWorkspaceChanged:_}}function
|
|
63
|
+
This will disconnect CDP and optionally kill the process.`))try{const D=await r(N.daemonId,"stop_ide",{ideType:N.type,killProcess:!0});D!=null&&D.success?k("info",`${ot(N.type)} stopped`,!0):k("error",`Stop failed: ${(D==null?void 0:D.error)||"Unknown error"}`,!0)}catch(D){k("error",`Stop failed: ${D.message}`,!0)}},[k,r]),T=o.useCallback(async()=>{if(e)try{const N=await r(e,"detect_ides",{});k("info",`Found ${((N==null?void 0:N.result)||[]).length} IDE(s)`,!0)}catch(N){k("error",`Detection failed: ${N.message}`,!0)}},[e,k,r]),B=o.useCallback(async N=>{if(!e||!N.trim())return!1;g(!0);try{const D=await r(e,"workspace_add",{path:N.trim()});return D!=null&&D.success?(k("info",`Workspace added: ${N.trim()}`),!0):(k("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return k("error",D.message),!1}finally{g(!1)}},[e,k,r]),H=o.useCallback(async N=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const D=await r(e,"workspace_remove",{id:N});D!=null&&D.success?k("info","Workspace removed",!0):k("error",(D==null?void 0:D.error)||"workspace_remove failed",!0)}catch(D){k("error",D.message,!0)}finally{g(!1)}}},[e,k,r]),C=o.useCallback(async N=>{var D;if(e){g(!0);try{const Y=await r(e,"workspace_set_default",N===null?{clear:!0}:{id:N});if(Y!=null&&Y.success){k("info",N?"Default workspace updated":"Default workspace cleared",!0);const q=typeof Y.defaultWorkspacePath=="string"?Y.defaultWorkspacePath:"";q&&((D=S.current)==null||D.call(S,q))}else k("error",(Y==null?void 0:Y.error)||"workspace_set_default failed",!0)}catch(Y){k("error",Y.message,!0)}finally{g(!1)}}},[e,k,r]),R=o.useCallback(async N=>{var Y;if(!e||!N.trim())return;const D=N.trim();g(!0);try{const q=await r(e,"workspace_set_default",{path:D});q!=null&&q.success?(k("info","Default workspace set from history"),(Y=S.current)==null||Y.call(S,D)):k("error",(q==null?void 0:q.error)||"Could not set default (path missing on disk?)")}catch(q){k("error",q.message)}finally{g(!1)}},[e,k,r]),U=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:y})}catch(N){k("warn",`Live nickname updated, but account sync failed: ${N.message}`)}k("info",`Nickname set to "${y||"(cleared)"}"`),b(!1)}catch(N){k("error",`Failed: ${N.message}`)}},[e,y,s,k,n,r]);return{logs:i,launchingIde:l,launchingAgentType:p,workspaceBusy:f,launchPick:w,setLaunchPick:A,editingNickname:d,setEditingNickname:b,nicknameInput:y,setNicknameInput:h,addLog:k,handleLaunchIde:j,runLaunchCliCore:v,handleLaunchCli:x,handleStopCli:E,handleRestartIde:L,handleStopIde:M,handleDetectIdes:T,handleWorkspaceAdd:B,handleWorkspaceRemove:H,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:R,handleSaveNickname:U,setOnDefaultWorkspaceChanged:_}}function Lx({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var L;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:m}=i,[f,g]=o.useState(!1),[w,A]=o.useState(""),[d,b]=o.useState([]),[y,h]=o.useState(!1),[S,_]=o.useState(""),k=o.useCallback(async M=>{h(!0),_("");try{const T=await Cn(c,e,M);A(T.path),b(T.directories)}catch(T){_(T instanceof Error?T.message:"Could not load folder")}finally{h(!1)}},[e,c]),I=o.useCallback(()=>{g(!0);const M=[...r.map(B=>B.workspace),...n.map(B=>B.workspace),...a.map(B=>B.workspace)],T=Nn(s.platform,Sn(M,s.defaultWorkspacePath,(s.workspaces||[]).map(B=>B.path)));k(T)},[a,n,r,k,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,v=s.availableMem??s.freeMem??s.totalMem,x=j&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-v)/s.totalMem*100))):0,E=((L=s.loadavg)==null?void 0:L[0])||0;return t.jsxs("div",{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[t.jsx(Pr,{icon:t.jsx(Xi,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Nu(s.uptime):"Waiting…"}),t.jsx(Pr,{icon:t.jsx(Rt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(Pr,{icon:t.jsx(gn,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(Pr,{icon:t.jsx(Fd,{size:16}),label:"ACPs",value:`${a.length}`})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),t.jsxs("div",{className:"flex gap-6",children:[t.jsx($o,{value:j?Math.min(Math.round(E/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:j?`${E.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx($o,{value:x,max:100,label:"Memory",color:"#3b82f6",detail:j?`${Kn(s.totalMem-v)} / ${Kn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Kn(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(Bs,{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:I,children:"Select workspace…"}),t.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&t.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(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:jn(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(In,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:d,busy:y,error:S,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:M=>{k(M)},onConfirm:M=>{(async()=>{if(!M)return;await u(M)&&g(!1)})()}})]})}function _x(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function Rx(e,s,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=i;if(c.length===0)continue;const l=s.find(u=>u.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function sa(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 Ai(e){if(!e||typeof e!="object")return null;if(sa(e))return e;const s=e,r=s.result;return sa(r)?r:sa(s.sourceConfig)?s.sourceConfig:null}function Px(e){const s=e.trim();return s||null}const Mi=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Dx=[{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 Ex({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(""),[g,w]=o.useState([]),[A,d]=o.useState(""),b=o.useRef(null),y=o.useRef(null),h=v=>{p(x=>x.includes(v)?x.filter(E=>E!==v):[...x,v])},S=()=>p([...Mi]),_=()=>p([]);o.useEffect(()=>{var v;(v=b.current)==null||v.scrollIntoView({behavior:"smooth"})},[g]),o.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const k=o.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const v=await r(e,"provider_auto_fix_status",{providerType:s.type});(v==null?void 0:v.running)===!1&&a==="running"&&(i("done"),w(x=>[...x,`
|
|
64
64
|
✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,s.type,r,a]),I=async()=>{if(u.length!==0){i("running"),w(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),d("");try{const v=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...m?{comment:m}:{}});v!=null&&v.success&&(v!=null&&v.started||v!=null&&v.running)?(w(x=>[...x,"✅ Agent started. Monitoring progress..."]),k()):(i("error"),d((v==null?void 0:v.error)||"Failed to start auto-fix"))}catch(v){i("error"),d((v==null?void 0:v.message)||"Connection failed")}}},j=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),w(v=>[...v,`
|
|
65
|
-
⚠️ Auto-fix cancelled.`]),i("done"),y.current&&clearInterval(y.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:v=>v.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:Lx.map(v=>t.jsxs("button",{onClick:()=>l(v.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===v.value?v.color+"66":"var(--border-subtle)",background:c===v.value?v.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===v.value?v.color:"var(--text-primary)"},children:v.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:v.desc})]},v.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:S,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:_,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Ai.map(v=>t.jsxs("button",{onClick:()=>h(v),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(v)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(v)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(v)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(v)?"☑ ":"☐ ",v]},v))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:m,onChange:v=>f(v.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[g.map((v,x)=>t.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},x)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:b})]}),A&&t.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:A})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&u.length>0&&`${u.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[a==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:I,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"),w([]),d("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Rx({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var k;const i=s.filter(I=>I.category==="ide"),[c,l]=o.useState(((k=i[0])==null?void 0:k.type)||""),[u,p]=o.useState(""),[m,f]=o.useState(""),[g,w]=o.useState(!1),[A,d]=o.useState(""),[b,y]=o.useState(!1),h=I=>{const j=I.toLowerCase().replace(/[^a-z0-9-]/g,"");p(j),(!m||m===S(u))&&f(S(j))},S=I=>I.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),_=async()=>{if(!(!u||!m||!c)){w(!0),d("");try{const I=await r(e,"provider_clone",{type:u,name:m,category:"ide",location:"user",cloneFrom:c});I!=null&&I.success||I!=null&&I.created?(y(!0),a==null||a(u)):d((I==null?void 0:I.error)||"Failed to create provider")}catch(I){d((I==null?void 0:I.message)||"Connection failed")}w(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:I=>I.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children: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(I=>t.jsxs("button",{onClick:()=>l(I.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===I.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===I.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:I.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===I.type?"#a78bfa":"var(--text-secondary)"},children:I.displayName})]},I.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:u,onChange:I=>h(I.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",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:I=>f(I.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),A&&t.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:A})]})}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children: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:_,disabled:!u||!m||g,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||g?.4:1},children:g?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Px({machineId:e,providers:s,sendDaemonCommand:r}){var L;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[p,m]=o.useState("all"),[f,g]=o.useState(null),[w,A]=o.useState(!1),[d,b]=o.useState(null),[y,h]=o.useState("normal"),[S,_]=o.useState(""),[k,I]=o.useState(!1),j=o.useCallback(async()=>{if(e)try{const M=await r(e,"get_provider_source_config",{}),T=Ii(M);T&&(b(T),h(T.sourceMode),_(T.explicitProviderDir||""))}catch{}},[e,r]),v=o.useCallback(async()=>{if(e){c(!0);try{const M=await r(e,"get_provider_settings",{}),T=Ax(M);if(T){const B=Mx(T,s);B.sort((H,C)=>H.category.localeCompare(C.category)||H.displayName.localeCompare(C.displayName)),a(B)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&v(),d||j()},[]);const x=async(M,T,B)=>{u(`${M}.${T}`),a(H=>H.map(C=>C.type===M?{...C,values:{...C.values,[T]:B}}:C));try{const H=await r(e,"set_provider_setting",{providerType:M,key:T,value:B});H!=null&&H.success||v()}catch{v()}u(null)},E=async()=>{I(!0);try{const M=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Tx(S)}),T=Ii(M);T?(b(T),h(T.sourceMode),_(T.explicitProviderDir||"")):await j(),await v()}catch{await j()}I(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(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:()=>A(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),t.jsx("button",{onClick:v,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick: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:y,onChange:M=>h(M.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:S,onChange:M=>_(M.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void E(),disabled:k,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:k?"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:"})," ",((L=d==null?void 0:d.providerRoots)==null?void 0:L.join(" → "))||"loading…"]})]})]}),p!=="all"&&n.filter(M=>M.category===p).length>1&&(()=>{const M=n.filter(C=>C.category===p),T=new Map;for(const C of M)for(const R of C.schema){if(R.type!=="boolean")continue;const U=T.get(R.key),N=!!(C.values[R.key]??R.default);U?(U.onCount+=N?1:0,U.total+=1):T.set(R.key,{label:R.label||R.key,onCount:N?1:0,total:1})}const B=[...T.entries()].filter(([,C])=>C.total===M.length);if(B.length===0)return null;const H=async(C,R)=>{for(const U of M)await x(U.type,C,R)};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:B.map(([C,R])=>{const U=R.onCount===R.total,N=R.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:R.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",R.onCount,"/",R.total,")"]}),t.jsx("button",{onClick:()=>void H(C,!0),disabled:U,className:`machine-btn text-[9px] px-1.5 py-px ${U?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void H(C,!1),disabled:N,className:`machine-btn text-[9px] px-1.5 py-px ${N?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},C)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(M=>p==="all"||M.category===p).map(M=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:M.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:M.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:M.category==="acp"?"rgba(139,92,246,0.08)":M.category==="cli"?"rgba(59,130,246,0.08)":M.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:M.category==="acp"?"#a78bfa":M.category==="cli"?"#60a5fa":M.category==="ide"?"#86efac":"var(--status-warning)"},children:M.category}),M.category==="ide"&&t.jsx("button",{onClick:()=>g(s.find(T=>T.type===M.type)||{type:M.type,name:M.displayName,displayName:M.displayName,icon:M.icon,category:M.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),t.jsx("div",{className:"flex flex-col gap-2",children:M.schema.map(T=>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:[T.label||T.key,l===`${M.type}.${T.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),T.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:T.description})]}),t.jsx("div",{className:"shrink-0",children:T.type==="boolean"?t.jsx("button",{onClick:()=>x(M.type,T.key,!(M.values[T.key]??T.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:M.values[T.key]??T.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[T.key]??T.default?21:3}})}):T.type==="number"?t.jsx("input",{type:"number",value:Number(M.values[T.key]??T.default??0)||0,min:T.min,max:T.max,onChange:B=>{const H=parseInt(B.target.value)||0;T.min!==void 0&&H<T.min||T.max!==void 0&&H>T.max||x(M.type,T.key,H)},className:"machine-input w-20 text-center text-[11px]"}):T.type==="select"&&T.options?t.jsx("select",{value:String(M.values[T.key]??T.default??""),onChange:B=>x(M.type,T.key,B.target.value),className:"machine-input text-[11px]",children:T.options.map(B=>t.jsx("option",{value:B,children:B},B))}):t.jsx("input",{type:"text",value:String(M.values[T.key]??T.default??""),onBlur:B=>x(M.type,T.key,B.target.value),className:"machine-input w-[120px] text-[11px]"})})]},T.key))})]},M.type))}),f&&t.jsx(_x,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>g(null)}),w&&t.jsx(Rx,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>A(!1),onCreated:()=>{A(!1),v()}})]})}const Dx=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Ex({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function $x(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Kx(e){return e.trim().toLowerCase()}function Mn(e,s){const r=Kx(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function bo(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function yr(e,s=220){const r=bo(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function Bx(e){const s=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(s))return{kind:s.length>0?"structured":"empty",entries:s.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof s=="string"){const r=s.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function Tl(e,s){return e.filter(r=>Mn([r.level,r.message],s))}function Ox(e,s){return e.split(`
|
|
66
|
-
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Mn([r],s))}function
|
|
65
|
+
⚠️ Auto-fix cancelled.`]),i("done"),y.current&&clearInterval(y.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:v=>v.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:Dx.map(v=>t.jsxs("button",{onClick:()=>l(v.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===v.value?v.color+"66":"var(--border-subtle)",background:c===v.value?v.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===v.value?v.color:"var(--text-primary)"},children:v.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:v.desc})]},v.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:S,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:_,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Mi.map(v=>t.jsxs("button",{onClick:()=>h(v),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(v)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(v)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(v)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(v)?"☑ ":"☐ ",v]},v))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:m,onChange:v=>f(v.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[g.map((v,x)=>t.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},x)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:b})]}),A&&t.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:A})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&u.length>0&&`${u.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[a==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:I,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"),w([]),d("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function $x({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var k;const i=s.filter(I=>I.category==="ide"),[c,l]=o.useState(((k=i[0])==null?void 0:k.type)||""),[u,p]=o.useState(""),[m,f]=o.useState(""),[g,w]=o.useState(!1),[A,d]=o.useState(""),[b,y]=o.useState(!1),h=I=>{const j=I.toLowerCase().replace(/[^a-z0-9-]/g,"");p(j),(!m||m===S(u))&&f(S(j))},S=I=>I.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),_=async()=>{if(!(!u||!m||!c)){w(!0),d("");try{const I=await r(e,"provider_clone",{type:u,name:m,category:"ide",location:"user",cloneFrom:c});I!=null&&I.success||I!=null&&I.created?(y(!0),a==null||a(u)):d((I==null?void 0:I.error)||"Failed to create provider")}catch(I){d((I==null?void 0:I.message)||"Connection failed")}w(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:I=>I.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children: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(I=>t.jsxs("button",{onClick:()=>l(I.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===I.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===I.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:I.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===I.type?"#a78bfa":"var(--text-secondary)"},children:I.displayName})]},I.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:u,onChange:I=>h(I.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",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:I=>f(I.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),A&&t.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:A})]})}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children: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:_,disabled:!u||!m||g,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||g?.4:1},children:g?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Kx({machineId:e,providers:s,sendDaemonCommand:r}){var L;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[p,m]=o.useState("all"),[f,g]=o.useState(null),[w,A]=o.useState(!1),[d,b]=o.useState(null),[y,h]=o.useState("normal"),[S,_]=o.useState(""),[k,I]=o.useState(!1),j=o.useCallback(async()=>{if(e)try{const M=await r(e,"get_provider_source_config",{}),T=Ai(M);T&&(b(T),h(T.sourceMode),_(T.explicitProviderDir||""))}catch{}},[e,r]),v=o.useCallback(async()=>{if(e){c(!0);try{const M=await r(e,"get_provider_settings",{}),T=_x(M);if(T){const B=Rx(T,s);B.sort((H,C)=>H.category.localeCompare(C.category)||H.displayName.localeCompare(C.displayName)),a(B)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&v(),d||j()},[]);const x=async(M,T,B)=>{u(`${M}.${T}`),a(H=>H.map(C=>C.type===M?{...C,values:{...C.values,[T]:B}}:C));try{const H=await r(e,"set_provider_setting",{providerType:M,key:T,value:B});H!=null&&H.success||v()}catch{v()}u(null)},E=async()=>{I(!0);try{const M=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Px(S)}),T=Ai(M);T?(b(T),h(T.sourceMode),_(T.explicitProviderDir||"")):await j(),await v()}catch{await j()}I(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(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:()=>A(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),t.jsx("button",{onClick:v,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick: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:y,onChange:M=>h(M.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:S,onChange:M=>_(M.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void E(),disabled:k,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:k?"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:"})," ",((L=d==null?void 0:d.providerRoots)==null?void 0:L.join(" → "))||"loading…"]})]})]}),p!=="all"&&n.filter(M=>M.category===p).length>1&&(()=>{const M=n.filter(C=>C.category===p),T=new Map;for(const C of M)for(const R of C.schema){if(R.type!=="boolean")continue;const U=T.get(R.key),N=!!(C.values[R.key]??R.default);U?(U.onCount+=N?1:0,U.total+=1):T.set(R.key,{label:R.label||R.key,onCount:N?1:0,total:1})}const B=[...T.entries()].filter(([,C])=>C.total===M.length);if(B.length===0)return null;const H=async(C,R)=>{for(const U of M)await x(U.type,C,R)};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:B.map(([C,R])=>{const U=R.onCount===R.total,N=R.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:R.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",R.onCount,"/",R.total,")"]}),t.jsx("button",{onClick:()=>void H(C,!0),disabled:U,className:`machine-btn text-[9px] px-1.5 py-px ${U?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void H(C,!1),disabled:N,className:`machine-btn text-[9px] px-1.5 py-px ${N?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},C)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(M=>p==="all"||M.category===p).map(M=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:M.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:M.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:M.category==="acp"?"rgba(139,92,246,0.08)":M.category==="cli"?"rgba(59,130,246,0.08)":M.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:M.category==="acp"?"#a78bfa":M.category==="cli"?"#60a5fa":M.category==="ide"?"#86efac":"var(--status-warning)"},children:M.category}),M.category==="ide"&&t.jsx("button",{onClick:()=>g(s.find(T=>T.type===M.type)||{type:M.type,name:M.displayName,displayName:M.displayName,icon:M.icon,category:M.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),t.jsx("div",{className:"flex flex-col gap-2",children:M.schema.map(T=>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:[T.label||T.key,l===`${M.type}.${T.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),T.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:T.description})]}),t.jsx("div",{className:"shrink-0",children:T.type==="boolean"?t.jsx("button",{onClick:()=>x(M.type,T.key,!(M.values[T.key]??T.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:M.values[T.key]??T.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[T.key]??T.default?21:3}})}):T.type==="number"?t.jsx("input",{type:"number",value:Number(M.values[T.key]??T.default??0)||0,min:T.min,max:T.max,onChange:B=>{const H=parseInt(B.target.value)||0;T.min!==void 0&&H<T.min||T.max!==void 0&&H>T.max||x(M.type,T.key,H)},className:"machine-input w-20 text-center text-[11px]"}):T.type==="select"&&T.options?t.jsx("select",{value:String(M.values[T.key]??T.default??""),onChange:B=>x(M.type,T.key,B.target.value),className:"machine-input text-[11px]",children:T.options.map(B=>t.jsx("option",{value:B,children:B},B))}):t.jsx("input",{type:"text",value:String(M.values[T.key]??T.default??""),onBlur:B=>x(M.type,T.key,B.target.value),className:"machine-input w-[120px] text-[11px]"})})]},T.key))})]},M.type))}),f&&t.jsx(Ex,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>g(null)}),w&&t.jsx($x,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>A(!1),onCreated:()=>{A(!1),v()}})]})}const Bx=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Ox({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Wx(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Hx(e){return e.trim().toLowerCase()}function Mn(e,s){const r=Hx(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function bo(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function yr(e,s=220){const r=bo(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function Fx(e){const s=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(s))return{kind:s.length>0?"structured":"empty",entries:s.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof s=="string"){const r=s.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function Ll(e,s){return e.filter(r=>Mn([r.level,r.message],s))}function Ux(e,s){return e.split(`
|
|
66
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Mn([r],s))}function _l(e,s){return e.filter(r=>Mn([r.level,r.category,r.stage,r.interactionId,bo(r.payload)],s))}function Rl(e,s){return e.filter(r=>Mn([r.kind,r.topic,r.interactionId,bo(r.payload)],s))}function Ti(e){return e==="warn"||e==="error"}function zx({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){return{all:e.length+s.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>Ti(a.level)).length+r.filter(a=>Ti(a.level)).length}}function Vx({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
|
|
67
67
|
`)):s.length>0&&a.push(["[daemon logs]",...s].join(`
|
|
68
68
|
`)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${yr(i.payload,500)}`.trim())].join(`
|
|
69
69
|
`)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${yr(i.payload,500)}`.trim())].join(`
|
|
70
70
|
`)),a.join(`
|
|
71
71
|
|
|
72
|
-
`)}function Fx({daemonLogs:e,trace:s,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=Tl(e,c),u=Ll(s,c),p=_l(r,c),m=l.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"daemon",level:w.level,timestamp:w.timestamp,label:"daemon",detail:w.message})),f=u.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"trace",level:w.level,timestamp:w.ts,label:`${w.category}.${w.stage}`,detail:yr(w.payload,320)||`${w.category}.${w.stage}`})),g=[...m,...f].sort((w,A)=>A.timestamp-w.timestamp);return{daemonCount:l.length,traceCount:u.length,webCount:p.length,issueCount:g.length,latestIssue:g[0]||null,hasAnyData:n==="text"||l.length>0||u.length>0||p.length>0,hasBlockingError:!!(a||i)}}function Ti(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Li(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function ra(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function Ux({machineId:e,sendDaemonCommand:s}){var ve,K;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,p]=o.useState([]),[m,f]=o.useState([]),[g,w]=o.useState(0),[A,d]=o.useState(0),[b,y]=o.useState(null),[h,S]=o.useState(!0),[_,k]=o.useState("info"),[I,j]=o.useState("info"),[v,x]=o.useState("all"),[E,L]=o.useState(""),[M,T]=o.useState(!0),[B,H]=o.useState(!0),[C,R]=o.useState(""),[U,N]=o.useState(""),[D,Y]=o.useState(0),[q,W]=o.useState({daemon:!0,trace:!1,web:!1}),ae=o.useRef(null),ce=o.useRef(!1),Se=o.useMemo(()=>$x(u,v),[u,v]),X=o.useMemo(()=>Tl(r,E),[r,E]),he=o.useMemo(()=>Ox(c,E),[c,E]),J=o.useMemo(()=>Ll(Se,E),[Se,E]),Z=o.useMemo(()=>_l(m,E),[m,E]),ue=o.useMemo(()=>I==="issues"?X.filter(V=>V.level==="warn"||V.level==="error"):I==="info"?X.filter(V=>V.level!=="debug"):X,[X,I]),de=o.useMemo(()=>I==="all"?he:[],[he,I]),z=o.useMemo(()=>I==="issues"?J.filter(V=>V.level==="warn"||V.level==="error"):I==="info"?J.filter(V=>V.level!=="debug"):J,[J,I]),ye=o.useMemo(()=>I==="issues"?[]:Z,[Z,I]),ie=o.useMemo(()=>Wx({daemonLogs:X,daemonRawLines:he,trace:J,webEvents:Z}),[X,he,J,Z]),le=o.useMemo(()=>Fx({daemonLogs:r,trace:Se,webEvents:m,daemonLogKind:a,daemonFetchError:C,traceFetchError:U,searchQuery:E}),[C,a,r,Se,E,U,m]),se=o.useCallback(async()=>{if(!e)return;const[V,we]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:_,since:g}),s(e,"get_debug_trace",Ex({count:120,since:A,category:v}))]);if(V.status==="fulfilled"){const be=V.value,Q=(be==null?void 0:be.result)||be,Me=Bx(Q);if(T(!1),R((be==null?void 0:be.success)===!1?String((be==null?void 0:be.error)||"Could not load daemon logs"):""),i(Me.kind),l(Me.rawText),Me.entries.length>0){n(Pe=>(g>0?[...Pe,...Me.entries]:Me.entries).slice(-300));const Oe=Me.entries.reduce((Pe,Ke)=>Math.max(Pe,Number(Ke.timestamp||0)),g);Oe>g&&w(Oe)}else Me.kind!=="structured"&&g===0&&n([])}else T(!1),R(V.reason instanceof Error?V.reason.message:"Could not load daemon logs");if(we.status==="fulfilled"){const be=we.value,Q=(be==null?void 0:be.result)||be;if((be==null?void 0:be.success)===!1)N(String((be==null?void 0:be.error)||"Could not load daemon trace"));else if(Array.isArray(Q==null?void 0:Q.trace)){N(""),p(Q.trace.slice(-120));const Me=Q.trace.reduce((Oe,Pe)=>Math.max(Oe,Number(Pe.ts||0)),A);Me>A&&d(Me)}else N(""),p([]);H(!1)}else H(!1),N(we.reason instanceof Error?we.reason.message:"Could not load daemon trace");f(Ks.list({limit:120})),y(Date.now())},[g,A,_,e,s,v]);o.useEffect(()=>{if(!e||(se(),!h))return;const V=setInterval(()=>{se()},3e3);return()=>clearInterval(V)},[h,se,e,D]),o.useEffect(()=>{if(h&&(ue.length>0||de.length>0||z.length>0||ye.length>0)){const V=ce.current?"smooth":"instant";setTimeout(()=>{var we;(we=ae.current)==null||we.scrollIntoView({behavior:V}),ce.current=!0},50)}},[ue.length,de.length,z.length,ye.length,h]),o.useEffect(()=>{p([]),d(0),H(!0)},[v]);const pe=((ve=le.latestIssue)==null?void 0:ve.level)==="error"?"danger":((K=le.latestIssue)==null?void 0:K.level)==="warn"?"warning":"good",ne=C||U?"danger":h?"good":"neutral",ke=o.useCallback(async()=>{var we;const V=Hx({daemonLogs:ue,daemonRawLines:de,trace:z,webEvents:ye});if(!V.trim()){st.showToast("복사할 visible logs가 없습니다.","info");return}try{await((we=navigator.clipboard)==null?void 0:we.writeText(V)),st.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(be){st.showToast(be instanceof Error?be.message:"Could not copy visible logs","warning")}},[ue,de,z,ye]);return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"Level"}),["debug","info","warn","error"].map(V=>t.jsx("button",{onClick:()=>{k(V),n([]),l(""),i("empty"),w(0),T(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${_===V?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:V.toUpperCase()},V)),t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),Dx.map(V=>t.jsx("button",{onClick:()=>x(V.value),className:`machine-btn text-[10px] px-2 py-0.5 ${v===V.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:V.label},V.value))]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${ie.info})`},{id:"issues",label:`Issues (${ie.issues})`},{id:"all",label:`All (${ie.all})`}].map(V=>t.jsx("button",{type:"button",onClick:()=>j(V.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${I===V.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:V.label},V.id))}),t.jsx("input",{value:E,onChange:V=>L(V.target.value),placeholder:"Search visible logs, trace, events…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"}),t.jsx("button",{onClick:()=>{ke()},className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:()=>S(V=>!V),className:`machine-btn ${h?"text-green-500 border-green-500/30":""}`,children:h?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>Y(V=>V+1),className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),p([]),f([]),w(0),d(0),y(null),R(""),N(""),T(!0),H(!0),Ks.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${ra(le.issueCount>0?"warning":"good")}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Visible signals"}),t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:["daemon ",ue.length+de.length," · trace ",z.length," · web ",ye.length]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:E.trim()?`Filtered by “${E.trim()}”`:"Showing the latest buffered entries"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${ra(pe)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),le.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[le.latestIssue.source," · ",le.latestIssue.label]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:le.latestIssue.detail}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[le.issueCount," warn/error signal(s) · ",Ti(le.latestIssue.timestamp)]})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No recent warn/error signal"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use search or lower the log level if you need more context."})]})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${ra(ne)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Fetch status"}),t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:C||U?"Needs attention":h?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Ti(b)]}),(C||U)&&t.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[C&&t.jsxs("div",{children:["Daemon logs: ",C]}),U&&t.jsxs("div",{children:["Daemon trace: ",U]})]})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>W(V=>({...V,daemon:!V.daemon})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a==="text"?`${de.length} visible raw line(s) from file fallback`:`${ue.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:q.daemon?"Hide":"Show"})]}),q.daemon&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[M&&!le.hasAnyData&&!C&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!M&&C&&a==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:C}),!M&&a==="empty"&&!C&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&de.length===0&&c&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:I==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),a==="structured"&&ue.length===0&&r.length>0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),a==="text"&&de.map((V,we)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:V},`raw-${we}`)),a!=="text"&&ue.map((V,we)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Li(V.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(V.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:V.level==="error"?"ERR":V.level==="warn"?"WRN":V.level==="debug"?"DBG":"INF"}),t.jsx("span",{className:"break-words",children:V.message})]},`log-${we}`))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>W(V=>({...V,trace:!V.trace})),children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",v==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[z.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:q.trace?"Hide":"Show"})]}),q.trace&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[B&&z.length===0&&!U&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!B&&U&&z.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:U}),!B&&z.length===0&&!U&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No trace entries match the current search.":v==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),z.map(V=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Li(V.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(V.ts).toLocaleTimeString()}),t.jsx("span",{children:V.level.toUpperCase()}),t.jsxs("span",{children:[V.category,".",V.stage]}),V.interactionId&&t.jsxs("span",{children:["ix=",V.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:yr(V.payload,360)||"No payload"})]},V.id))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>W(V=>({...V,web:!V.web})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[ye.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:q.web?"Hide":"Show"})]}),q.web&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[ye.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),ye.map(V=>t.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(V.ts).toLocaleTimeString()}),t.jsx("span",{children:V.kind}),V.topic&&t.jsxs("span",{children:["topic=",V.topic]}),V.interactionId&&t.jsxs("span",{children:["ix=",V.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:yr(V.payload,360)||"No payload"})]},V.id))]})]})]}),t.jsx("div",{ref:ae})]})}function na(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function aa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function _i(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 zx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Vx(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 Gx(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 qx({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),p=Jc(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),m=p.diagnostics,f=p.loading,g=p.applyDiagnostics,w=o.useMemo(()=>sx({diagnostics:m,loading:f,refreshing:l,error:n}),[m,f,l,n]),A=o.useMemo(()=>new Map(s.map(L=>[L.sessionId||L.id,L])),[s]),d=o.useCallback(async()=>{if(e){u(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),M=na(L);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Could not load hosted runtime diagnostics");g(M.diagnostics||M.result||null),a("")}catch(L){const M=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(M)}finally{u(!1)}}},[g,e,r]);o.useEffect(()=>{!e||m||f||l||d()},[m,f,e,d,l]);const b=o.useCallback(async(L,M)=>{const T=`${L}:${M.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${M.displayName}?
|
|
72
|
+
`)}function Gx({daemonLogs:e,trace:s,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=Ll(e,c),u=_l(s,c),p=Rl(r,c),m=l.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"daemon",level:w.level,timestamp:w.timestamp,label:"daemon",detail:w.message})),f=u.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"trace",level:w.level,timestamp:w.ts,label:`${w.category}.${w.stage}`,detail:yr(w.payload,320)||`${w.category}.${w.stage}`})),g=[...m,...f].sort((w,A)=>A.timestamp-w.timestamp);return{daemonCount:l.length,traceCount:u.length,webCount:p.length,issueCount:g.length,latestIssue:g[0]||null,hasAnyData:n==="text"||l.length>0||u.length>0||p.length>0,hasBlockingError:!!(a||i)}}function Li(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function _i(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function ra(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function qx({machineId:e,sendDaemonCommand:s}){var ve,K;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,p]=o.useState([]),[m,f]=o.useState([]),[g,w]=o.useState(0),[A,d]=o.useState(0),[b,y]=o.useState(null),[h,S]=o.useState(!0),[_,k]=o.useState("info"),[I,j]=o.useState("info"),[v,x]=o.useState("all"),[E,L]=o.useState(""),[M,T]=o.useState(!0),[B,H]=o.useState(!0),[C,R]=o.useState(""),[U,N]=o.useState(""),[D,Y]=o.useState(0),[q,W]=o.useState({daemon:!0,trace:!1,web:!1}),ae=o.useRef(null),ce=o.useRef(!1),Se=o.useMemo(()=>Wx(u,v),[u,v]),X=o.useMemo(()=>Ll(r,E),[r,E]),he=o.useMemo(()=>Ux(c,E),[c,E]),J=o.useMemo(()=>_l(Se,E),[Se,E]),Z=o.useMemo(()=>Rl(m,E),[m,E]),ue=o.useMemo(()=>I==="issues"?X.filter(V=>V.level==="warn"||V.level==="error"):I==="info"?X.filter(V=>V.level!=="debug"):X,[X,I]),de=o.useMemo(()=>I==="all"?he:[],[he,I]),z=o.useMemo(()=>I==="issues"?J.filter(V=>V.level==="warn"||V.level==="error"):I==="info"?J.filter(V=>V.level!=="debug"):J,[J,I]),ye=o.useMemo(()=>I==="issues"?[]:Z,[Z,I]),ie=o.useMemo(()=>zx({daemonLogs:X,daemonRawLines:he,trace:J,webEvents:Z}),[X,he,J,Z]),le=o.useMemo(()=>Gx({daemonLogs:r,trace:Se,webEvents:m,daemonLogKind:a,daemonFetchError:C,traceFetchError:U,searchQuery:E}),[C,a,r,Se,E,U,m]),se=o.useCallback(async()=>{if(!e)return;const[V,we]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:_,since:g}),s(e,"get_debug_trace",Ox({count:120,since:A,category:v}))]);if(V.status==="fulfilled"){const be=V.value,Q=(be==null?void 0:be.result)||be,Me=Fx(Q);if(T(!1),R((be==null?void 0:be.success)===!1?String((be==null?void 0:be.error)||"Could not load daemon logs"):""),i(Me.kind),l(Me.rawText),Me.entries.length>0){n(Pe=>(g>0?[...Pe,...Me.entries]:Me.entries).slice(-300));const Oe=Me.entries.reduce((Pe,Ke)=>Math.max(Pe,Number(Ke.timestamp||0)),g);Oe>g&&w(Oe)}else Me.kind!=="structured"&&g===0&&n([])}else T(!1),R(V.reason instanceof Error?V.reason.message:"Could not load daemon logs");if(we.status==="fulfilled"){const be=we.value,Q=(be==null?void 0:be.result)||be;if((be==null?void 0:be.success)===!1)N(String((be==null?void 0:be.error)||"Could not load daemon trace"));else if(Array.isArray(Q==null?void 0:Q.trace)){N(""),p(Q.trace.slice(-120));const Me=Q.trace.reduce((Oe,Pe)=>Math.max(Oe,Number(Pe.ts||0)),A);Me>A&&d(Me)}else N(""),p([]);H(!1)}else H(!1),N(we.reason instanceof Error?we.reason.message:"Could not load daemon trace");f(Ks.list({limit:120})),y(Date.now())},[g,A,_,e,s,v]);o.useEffect(()=>{if(!e||(se(),!h))return;const V=setInterval(()=>{se()},3e3);return()=>clearInterval(V)},[h,se,e,D]),o.useEffect(()=>{if(h&&(ue.length>0||de.length>0||z.length>0||ye.length>0)){const V=ce.current?"smooth":"instant";setTimeout(()=>{var we;(we=ae.current)==null||we.scrollIntoView({behavior:V}),ce.current=!0},50)}},[ue.length,de.length,z.length,ye.length,h]),o.useEffect(()=>{p([]),d(0),H(!0)},[v]);const pe=((ve=le.latestIssue)==null?void 0:ve.level)==="error"?"danger":((K=le.latestIssue)==null?void 0:K.level)==="warn"?"warning":"good",ne=C||U?"danger":h?"good":"neutral",ke=o.useCallback(async()=>{var we;const V=Vx({daemonLogs:ue,daemonRawLines:de,trace:z,webEvents:ye});if(!V.trim()){st.showToast("복사할 visible logs가 없습니다.","info");return}try{await((we=navigator.clipboard)==null?void 0:we.writeText(V)),st.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(be){st.showToast(be instanceof Error?be.message:"Could not copy visible logs","warning")}},[ue,de,z,ye]);return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"Level"}),["debug","info","warn","error"].map(V=>t.jsx("button",{onClick:()=>{k(V),n([]),l(""),i("empty"),w(0),T(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${_===V?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:V.toUpperCase()},V)),t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),Bx.map(V=>t.jsx("button",{onClick:()=>x(V.value),className:`machine-btn text-[10px] px-2 py-0.5 ${v===V.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:V.label},V.value))]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${ie.info})`},{id:"issues",label:`Issues (${ie.issues})`},{id:"all",label:`All (${ie.all})`}].map(V=>t.jsx("button",{type:"button",onClick:()=>j(V.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${I===V.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:V.label},V.id))}),t.jsx("input",{value:E,onChange:V=>L(V.target.value),placeholder:"Search visible logs, trace, events…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"}),t.jsx("button",{onClick:()=>{ke()},className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:()=>S(V=>!V),className:`machine-btn ${h?"text-green-500 border-green-500/30":""}`,children:h?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>Y(V=>V+1),className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),p([]),f([]),w(0),d(0),y(null),R(""),N(""),T(!0),H(!0),Ks.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${ra(le.issueCount>0?"warning":"good")}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Visible signals"}),t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:["daemon ",ue.length+de.length," · trace ",z.length," · web ",ye.length]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:E.trim()?`Filtered by “${E.trim()}”`:"Showing the latest buffered entries"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${ra(pe)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),le.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[le.latestIssue.source," · ",le.latestIssue.label]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:le.latestIssue.detail}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[le.issueCount," warn/error signal(s) · ",Li(le.latestIssue.timestamp)]})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No recent warn/error signal"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use search or lower the log level if you need more context."})]})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${ra(ne)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Fetch status"}),t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:C||U?"Needs attention":h?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Li(b)]}),(C||U)&&t.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[C&&t.jsxs("div",{children:["Daemon logs: ",C]}),U&&t.jsxs("div",{children:["Daemon trace: ",U]})]})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>W(V=>({...V,daemon:!V.daemon})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a==="text"?`${de.length} visible raw line(s) from file fallback`:`${ue.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:q.daemon?"Hide":"Show"})]}),q.daemon&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[M&&!le.hasAnyData&&!C&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!M&&C&&a==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:C}),!M&&a==="empty"&&!C&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&de.length===0&&c&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:I==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),a==="structured"&&ue.length===0&&r.length>0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),a==="text"&&de.map((V,we)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:V},`raw-${we}`)),a!=="text"&&ue.map((V,we)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${_i(V.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(V.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:V.level==="error"?"ERR":V.level==="warn"?"WRN":V.level==="debug"?"DBG":"INF"}),t.jsx("span",{className:"break-words",children:V.message})]},`log-${we}`))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>W(V=>({...V,trace:!V.trace})),children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",v==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[z.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:q.trace?"Hide":"Show"})]}),q.trace&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[B&&z.length===0&&!U&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!B&&U&&z.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:U}),!B&&z.length===0&&!U&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No trace entries match the current search.":v==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),z.map(V=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${_i(V.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(V.ts).toLocaleTimeString()}),t.jsx("span",{children:V.level.toUpperCase()}),t.jsxs("span",{children:[V.category,".",V.stage]}),V.interactionId&&t.jsxs("span",{children:["ix=",V.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:yr(V.payload,360)||"No payload"})]},V.id))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>W(V=>({...V,web:!V.web})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[ye.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:q.web?"Hide":"Show"})]}),q.web&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[ye.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),ye.map(V=>t.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(V.ts).toLocaleTimeString()}),t.jsx("span",{children:V.kind}),V.topic&&t.jsxs("span",{children:["topic=",V.topic]}),V.interactionId&&t.jsxs("span",{children:["ix=",V.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:yr(V.payload,360)||"No payload"})]},V.id))]})]})]}),t.jsx("div",{ref:ae})]})}function na(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function aa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ri(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/1e3));if(r<60)return`${r}s ago`;const n=Math.round(r/60);if(n<60)return`${n}m ago`;const a=Math.round(n/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function Yx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Xx(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 Jx(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 Qx({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),p=Qc(e,{enabled:!!e,includeSessions:!0,limit:zo,intervalMs:Am}),m=p.diagnostics,f=p.loading,g=p.applyDiagnostics,w=o.useMemo(()=>ox({diagnostics:m,loading:f,refreshing:l,error:n}),[m,f,l,n]),A=o.useMemo(()=>new Map(s.map(L=>[L.sessionId||L.id,L])),[s]),d=o.useCallback(async()=>{if(e){u(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:zo}),M=na(L);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Could not load hosted runtime diagnostics");g(M.diagnostics||M.result||null),a("")}catch(L){const M=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(M)}finally{u(!1)}}},[g,e,r]);o.useEffect(()=>{!e||m||f||l||d()},[m,f,e,d,l]);const b=o.useCallback(async(L,M)=>{const T=`${L}:${M.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${M.displayName}?
|
|
73
73
|
This will terminate the hosted runtime.`))){c(T);try{const B=await r(e,L,{sessionId:M.sessionId}),H=na(B);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Session host action failed");const C=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";st.showToast(`Session host ${C}: ${M.displayName}`,"success"),await d()}catch(B){const H=B instanceof Error?B.message:"Session host action failed";st.showToast(H,"warning"),a(H)}finally{c(B=>B===T?null:B)}}},[e,d,r]),y=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
74
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const M=await r(e,"session_host_prune_duplicate_sessions",{}),T=na(M);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Duplicate prune failed");const B=T.result||{},H=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,C=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;st.showToast(`Pruned ${H} duplicate runtime(s) across ${C} group(s)`,"success"),await d()}catch(M){const T=M instanceof Error?M.message:"Duplicate prune failed";st.showToast(T,"warning"),a(T)}finally{c(M=>M==="session_host_prune_duplicate_sessions"?null:M)}}},[e,d,r]),h=o.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((L,M)=>(M.lastActivityAt||0)-(L.lastActivityAt||0)),[m==null?void 0:m.sessions]),S=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)||[]}:Cl(h),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,h]),_=S.liveRuntimes,k=S.recoverySnapshots,I=S.inactiveRecords,j=o.useMemo(()=>Gx(_),[_]),v=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(L=>L.level==="warn"||L.level==="error")||null,[m==null?void 0:m.recentLogs]),E=(L,M)=>{var Y;const T=i===`session_host_resume_session:${L.sessionId}`,B=i===`session_host_restart_session:${L.sessionId}`,H=i===`session_host_stop_session:${L.sessionId}`,C=xo(L.meta),R=A.get(L.sessionId),U=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,N=M==="recovery"?"Recover":"Resume",D=Il(M);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:L.displayName||(R==null?void 0:R.cliName)||L.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Vx(L.lifecycle)}`,children:L.lifecycle}),C&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:L.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((Y=L.writeOwner)==null?void 0:Y.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:zx(L.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(Pa,{size:11})," ",U]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",_i(L.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"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_resume_session",L)},children:T?`${N}ing…`:N}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",L)},children:B?"Restarting…":"Restart"}),M==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{b("session_host_stop_session",L)},children:H?"Stopping…":"Stop"})]})]})},L.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(Qt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:pp()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},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 ${w.toneClass}`,children:w.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:f||l,children:[t.jsx(Gs,{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(ks,{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:k.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:_i(m.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:aa(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(ks,{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:[aa(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(gn,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$s("live")}),_.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:_.map(L=>E(L,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Qt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$s("recovery")}),k.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:k.map(L=>E(L,"recovery"))})]}),I.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$s("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(L=>E(L,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),v.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:v.map(L=>{var T;const M=h.find(B=>B.sessionId===L.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(M==null?void 0:M.displayName)||((T=A.get(L.sessionId))==null?void 0:T.cliName)||L.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:aa(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:m.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Yx({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 oa({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 ia({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 Xx({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=dr(e,"0.8.86");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(oa,{icon:t.jsx(Zt,{size:13}),children:"Current Chats"}),t.jsx(ia,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const g=ba(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:lt(f)}),g>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:vn(g)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Cs(f)})]},f.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(oa,{icon:t.jsx(Yi,{size:13}),children:"Recent Launches"}),t.jsx(ia,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const{metaText:g,updatedLabel:w}=ul(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}),w&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(oa,{icon:t.jsx(ks,{size:13}),children:"Daemon Update"}),t.jsx(ia,{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(Gs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Jx(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const Qx={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 Yr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ca({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const m=Vs(),{handleLaunchIde:f,handleStopCli:g,handleRestartIde:w,handleStopIde:A,handleDetectIdes:d,launchingIde:b,launchingAgentType:y,addLog:h}=c,[S,_]=o.useState(null),k=o.useCallback($=>{$&&m(as($))},[m]),I=Qx[e],j=e==="ide",v=e==="acp",x=o.useMemo(()=>n.filter($=>$.category===e&&(e==="ide"||$.installed!==!1)),[e,n]),E=o.useMemo(()=>new Map(x.map($=>[$.type,$.displayName||$.type])),[x]),[L,M]=o.useState(""),[T,B]=o.useState(""),[H,C]=o.useState([]),[R,U]=o.useState(""),[N,D]=o.useState(""),[Y,q]=o.useState([]),[W,ae]=o.useState(!1),[ce,Se]=o.useState(!1),[X,he]=o.useState(""),[J,Z]=o.useState(!1),[ue,de]=o.useState(()=>jt()),[z,ye]=o.useState(null),[ie,le]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[se,pe]=o.useState(p||""),[ne,ke]=o.useState([]),[ve,K]=o.useState(!1),[V,we]=o.useState(""),[be,Q]=o.useState([]),[Me,Oe]=o.useState(!1),[Pe,Ke]=o.useState(""),Qe=o.useRef(null),[Ge,ut]=o.useState(null),it=o.useRef("__home__"),[ht,ze]=o.useState("__home__"),[xt,bt]=o.useState(!1),ct=o.useRef(0),Te=ne.filter($=>!a.some(te=>te.type===$&&Ct(te.status)!=="stopped")),Xe=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!ie&&le(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){le("__custom__"),pe(p);return}u&&(le(u),pe(""))},[u,p]),o.useEffect(()=>{j||L&&(x.some($=>$.type===L)||(M(""),D("")))},[x,j,L]);const Fe=(()=>{if(ie==="__custom__")return se.trim();if(!ie)return"";const $=(s.workspaces||[]).find(te=>te.id===ie);return($==null?void 0:$.path)||""})(),Ue=o.useCallback($=>{const te=Xe.current[$];te&&(clearTimeout(te),delete Xe.current[$]),ke(fe=>fe.includes($)?fe.filter(Ee=>Ee!==$):fe)},[]),kt=o.useRef(new Set),yt=o.useCallback(async $=>{if(l){Oe(!0),Ke("");try{const te=await Cn(l,r,$);we(te.path),pe(te.path),Q(te.directories)}catch(te){Ke(te instanceof Error?te.message:"Could not load folder")}finally{Oe(!1)}}},[r,l]),wt=o.useCallback(()=>{if(!l)return;le("__custom__"),K(!0);const $=a.map(fe=>fe.workspace),te=Nn(s.platform,Sn(se.trim(),Fe,p,$,s.defaultWorkspacePath,(s.workspaces||[]).map(fe=>fe.path)));yt(te)},[se,p,yt,s.defaultWorkspacePath,s.platform,s.workspaces,a,Fe,l]),St=o.useCallback($=>{const te=String($.workspace||"").trim();if(!te)return;const fe=(s.workspaces||[]).find(Ee=>Yr(Ee.path)===Yr(te));if(fe){le(fe.id),pe("");return}le("__custom__"),pe(te)},[s.workspaces]),Ht=o.useCallback($=>{const te=String($.workspace||"").trim();if(!te)return{workspaceId:null,workspacePath:"",useHome:!0};const fe=(s.workspaces||[]).find(Ee=>Yr(Ee.path)===Yr(te));return fe?{workspaceId:fe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:te,useHome:!1}},[s.workspaces]),Mt=o.useCallback(async $=>{if(!l||!$||e!=="cli"){q([]),ae(!1),Se(!1),he("");return}const te=ct.current+1;ct.current=te,ae(!0),he("");try{const fe=await l(r,"list_saved_sessions",{providerType:$,kind:"cli",limit:30});if(ct.current!==te)return;const Ee=(fe==null?void 0:fe.result)??fe;q(Array.isArray(Ee==null?void 0:Ee.sessions)?Ee.sessions:[])}catch(fe){if(ct.current!==te)return;q([]),he(fe instanceof Error?fe.message:"Could not load saved sessions")}finally{ct.current===te&&(ae(!1),Se(!0))}},[e,r,l]),Tt=o.useMemo(()=>{if(e!=="cli"||!L)return null;const $=E.get(L)||L;return{routeId:r,daemonId:r,providerSessionId:N||void 0,transport:"pty",mode:"chat",agentName:$,agentType:L,status:"idle",title:$,messages:[],ideType:L,workspaceName:Fe,displayPrimary:$,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${L}`}},[e,r,E,Fe,N,L]),ee=o.useCallback($=>{if(e==="ide"||!$){C([]);return}C(Sl(r,$))},[e,r]);o.useEffect(()=>{ct.current+=1,D(""),ee(L),Se(!1),q([]),he(""),ae(!1)},[e,ee,Mt,L]);const Re=o.useMemo(()=>Y.find($=>$.providerSessionId===N)||null,[Y,N]);o.useEffect(()=>{if(!N)return;const $=Y.find(te=>te.providerSessionId===N);$!=null&&$.canResume||D("")},[Y,N]);const P=o.useCallback(($,te)=>{Qe.current=te,it.current=$.selectedWorkspaceKey||"__home__",ze($.selectedWorkspaceKey||"__home__"),ut($)},[]),O=o.useCallback(()=>{Qe.current&&(bt(!0),Qe.current().finally(()=>{Qe.current=null,bt(!1),ut(null)}))},[]),F=o.useCallback($=>{if(!$)return;ke(fe=>fe.includes($)?fe:[...fe,$]);const te=Xe.current[$];te&&clearTimeout(te),Xe.current[$]=setTimeout(()=>{ke(fe=>fe.includes($)?fe.filter(Ee=>Ee!==$):fe),delete Xe.current[$]},2e4)},[]);o.useEffect(()=>{for(const te of a)Ct(te.status)!=="stopped"&&(ne.includes(te.type)&&!kt.current.has(te.type)&&(kt.current.add(te.type),h("info",`${E.get(te.type)||te.type} launched`,!0)),Ue(te.type));const $=new Set(a.filter(te=>Ct(te.status)!=="stopped").map(te=>te.type));kt.current.forEach(te=>{!ne.includes(te)&&!$.has(te)&&kt.current.delete(te)})},[h,Ue,a,ne,E]),o.useEffect(()=>()=>{Object.values(Xe.current).forEach(clearTimeout),Xe.current={}},[]);const[G,oe]=o.useState({}),[Ie,_e]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const te=await l(r,"get_ide_extensions",{}),fe=(te==null?void 0:te.result)||te;fe!=null&&fe.success&&(fe!=null&&fe.ideExtensions)&&oe(fe.ideExtensions)}catch{}})()},[j,r,l]);const Ae=$=>j?ot($.type):e==="cli"?$.cliName:$.acpName,We=j?s.detectedIdes||[]:[],De=o.useCallback(async $=>{const te=($==null?void 0:$.type)||L,fe=($==null?void 0:$.workspacePath)??Fe;if(j){await f(te,fe?{workspace:fe}:void 0)&&F(te);return}const Ee=await c.runLaunchCliCore({cliType:te,dir:$!=null&&$.workspaceId?void 0:fe||void 0,workspaceId:($==null?void 0:$.workspaceId)||void 0,useHome:($==null?void 0:$.useHome)||!($!=null&&$.workspaceId)&&!fe,argsStr:($==null?void 0:$.argsStr)??(T||void 0),model:($==null?void 0:$.model)??(v&&R||void 0),resumeSessionId:($==null?void 0:$.resumeSessionId)||!v&&e==="cli"&&te===L&&N||void 0});if(Ee.success||Ee.pending){const Le=($==null?void 0:$.argsStr)??T;!j&&(Le!=null&&Le.trim())&&(Nl(r,te,Le),ee(te)),F(te),Ee.success&&Ee.sessionId&&k(Ee.sessionId)}},[c,f,v,j,T,R,ee,F,r,k,Fe,N,L]),Je=Ec(j?"ide":v?"acp":"cli",!j&&!v&&!!N),Ve=$c(j?"ide":v?"acp":"cli",!j&&!v&&!!N),re=()=>{var Le;const $=j?ot(L):E.get(L)||L,te=!j&&!v&&!!N,{options:fe,selectedKey:Ee}=vs({machine:s,currentWorkspaceId:ie&&ie!=="__custom__"?ie:null,currentWorkspacePath:Fe});P({title:te?Qa($):xs("start-fresh",$),description:te?Za():bs("start-fresh"),confirmLabel:Je,busyLabel:Ve,workspaceOptions:fe,selectedWorkspaceKey:Ee,details:[{label:"Mode",value:I.label},{label:"Provider",value:$},...!j&&e==="cli"&&N?[{label:"Resume",value:((Le=Y.find(Ne=>Ne.providerSessionId===N))==null?void 0:Le.title)||N}]:[],...!j&&T.trim()?[{label:"Arguments",value:T.trim()}]:[],...v&&R.trim()?[{label:"Model",value:R.trim()}]:[]]},async()=>{const Ne=fe.find(et=>et.key===it.current);Ne!=null&&Ne.workspaceId?(le(Ne.workspaceId),pe("")):Ne!=null&&Ne.workspacePath?(le("__custom__"),pe(Ne.workspacePath)):(le(""),pe("")),await De({workspaceId:(Ne==null?void 0:Ne.workspaceId)??null,workspacePath:(Ne==null?void 0:Ne.workspacePath)??"",useHome:!(Ne!=null&&Ne.workspaceId)&&!(Ne!=null&&Ne.workspacePath)})})},je=$=>{j?A($):g($.type,$.workspace,$.id)},Be=o.useCallback(async($,te,fe=!1)=>{if($.mode===te){fe&&$.sessionId&&k($.sessionId);return}if(!l||!$.sessionId){fe&&$.sessionId&&k($.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:$.sessionId,cliType:$.type,mode:te}),fe&&k($.sessionId)}catch(Ee){const Le=co(Ee);io(Ee)?console.warn(Le?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ee instanceof Error?Ee.message:String(Ee)):console.error("Failed to switch CLI view mode:",Ee)}},[r,k,l]),rt=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ie,onChange:$=>{const te=$.target.value;if(le(te),te==="__custom__"&&l){wt();return}te!=="__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?"⭐ ":"",jn($.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…"})]})}),ie==="__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:wt,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:ie==="__custom__"?Fe?t.jsx("span",{className:"font-mono truncate block",title:Fe,children:Fe}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Fe?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ie===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:Fe,children:Fe})]}):"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 ${I.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 ",I.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?We.length>0?We.map($=>{const te=a.find(et=>(et.type||"").toLowerCase()===($.type||"").toLowerCase()&&Ct(et.status)!=="stopped"),fe=$.running||!!te,Ee=!!te&&te.cdpConnected,Le=ne.includes($.type||$.id||""),Ne=L===($.type||"");return t.jsxs("button",{onClick:()=>{if(Ee&&te){const et=te.sessionId;et?m(as(et),{state:{openRemoteForTabKey:et}}):m("/dashboard",{state:{openRemoteForTabKey:te.id}});return}Le||M(et=>et===($.type||"")?"":$.type||"")},disabled:!!b||Le,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ee?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ne?"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)}),fe&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ee?"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 ${Ee?"text-green-400":Le?"text-orange-400":Ne?"text-accent-primary":"text-text-muted"}`,children:Ee?"Open Session":Le?"Starting...":Ne?"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($d,{size:14})," Scan System"]})]}):x.length>0?x.map($=>{const te=L===$.type,fe=ne.includes($.type),Le=!!a.find(Ne=>Ne.type===$.type&&Ct(Ne.status)!=="stopped");return t.jsxs("button",{onClick:()=>M(Ne=>Ne===$.type?"":$.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${te?"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}),Le&&t.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:$.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${fe?"text-orange-400":te?"text-accent-primary":"text-text-muted"}`,children:fe?"Starting...":te?"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."})]})}),L&&(j?We.find($=>$.type===L):x.find($=>$.type===L))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?ot(L):E.get(L)||L})]}),rt,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&t.jsx(Ml,{busy:!!y||!!b||ne.includes(L),savedSessionsLoading:W,savedSessionsError:X,selectedSession:Re,onRefresh:()=>void Mt(L),onOpenHistory:()=>{L&&(Z(!0),Al({hasLoadedInitialResults:ce,isLoading:W})&&Mt(L))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:R,onChange:$=>U($.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:T,onChange:$=>B($.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),H.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:H.map($=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>B($),title:$,children:$},$))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:re,disabled:!!y||!!b||ne.includes(L),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:y===L||b===L?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ne.filter($=>!a.some(te=>te.type===$&&Ct(te.status)!=="stopped")).length,")"]}),a.length===0&&Te.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 ",I.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Te.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($):E.get($)||$}),t.jsx("div",{className:"text-[11px] text-text-muted",children:y===$?"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 te=j?$:null,fe=!j&&!v?$:null,Ee=Ct($.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:[Ae($),(te==null?void 0:te.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",te.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:$.workspace||"—"}),(fe==null?void 0:fe.mode)&&t.jsx("span",{className:fe.mode==="chat"?"text-violet-400":"text-text-secondary",children:fe.mode==="chat"?"Chat view":"Terminal view"})]}),fe&&(fe.runtimeKey||fe.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[fe.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 ",fe.runtimeKey]}),t.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Le;(Le=navigator.clipboard)==null||Le.writeText(`adhdev attach ${fe.runtimeKey}`),_(fe.runtimeKey||null),window.setTimeout(()=>{_(Ne=>Ne===fe.runtimeKey?null:Ne)},1200)},children:S===fe.runtimeKey?"Copied":"Copy"})]}),fe.runtimeWriteOwner&&t.jsx("span",{style:{color:fe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:fe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Jx(fe.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 ${Ee==="stopped"?"bg-red-500/[0.08] text-red-500":Ee==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ee}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Le=$.sessionId;if(Le){m(as(Le),{state:{openRemoteForTabKey:Le}});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(Rt,{size:13})}),t.jsx("button",{onClick:()=>{const Le=$.workspace||"",{options:Ne,selectedKey:et}=vs({machine:s,currentWorkspacePath:Le});P({title:xs("restart-ide",ot($.type)),description:bs("restart-ide"),confirmLabel:Us("restart-ide"),busyLabel:zs("restart-ide"),workspaceOptions:Ne,selectedWorkspaceKey:et,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ot($.type)}]},async()=>{const $e=Ne.find(es=>es.key===it.current),mt=($e==null?void 0:$e.workspacePath)??"";if(mt&&mt!==Le){await De({type:$.type,workspacePath:mt});return}await w($)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:t.jsx(Gs,{size:14})})]}),v&&t.jsx("button",{onClick:()=>{const Le=$.sessionId;Le&&k(Le)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!$.sessionId,children:t.jsx(Zt,{size:14})}),fe&&Ee!=="stopped"&&t.jsxs(t.Fragment,{children:[fe.mode&&t.jsx(Ya,{mode:fe.mode,onChange:Le=>void Be(fe,Le,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Le=$.sessionId;Le&&k(Le)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!$.sessionId,children:fe.mode==="chat"?t.jsx(Zt,{size:14}):t.jsx(Rt,{size:13})})]}),Ee==="stopped"?t.jsx("button",{onClick:()=>{const Le=$.workspace||"",Ne=j?ot($.type):Ae($),{options:et,selectedKey:$e}=vs({machine:s,currentWorkspacePath:Le});P({title:xs("restart-stopped",Ne),description:bs("restart-stopped"),confirmLabel:Us("restart-stopped"),busyLabel:zs("restart-stopped"),workspaceOptions:et,selectedWorkspaceKey:$e,details:[{label:"Mode",value:I.label},{label:"Provider",value:Ne}]},async()=>{const mt=et.find(es=>es.key===it.current);await De({type:$.type,workspaceId:(mt==null?void 0:mt.workspaceId)??null,workspacePath:(mt==null?void 0:mt.workspacePath)??"",useHome:!(mt!=null&&mt.workspaceId)&&!(mt!=null&&mt.workspacePath)})})},disabled:ne.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:ne.includes($.type)?"⏳":t.jsx(Ea,{size:14})}):t.jsx("button",{onClick:()=>je($),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(At,{size:14})})]})]}),te&&te.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:te.aiAgents.map(Le=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${ac(Le.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Le.name," · ",Ct(Le.status)]},Le.id))}),te&&(G[te.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:(G[te.type]||[]).map(Le=>t.jsxs("button",{disabled:Ie===`${te.type}.${Le.type}`,onClick:async()=>{const Ne=`${te.type}.${Le.type}`;_e(Ne);try{await l(r,"set_ide_extension",{ideType:te.type,extensionType:Le.type,enabled:!Le.enabled}),oe(et=>({...et,[te.type]:(et[te.type]||[]).map($e=>$e.type===Le.type?{...$e,enabled:!$e.enabled}:$e)}))}catch(et){console.error("Extension toggle failed:",et)}finally{_e(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Le.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Le.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Le.name,t.jsx("span",{className:"text-[9px] font-normal",children:Le.enabled?"ON":"OFF"})]},Le.type))})]})]},$.id)})]}),ve&&l&&t.jsx(In,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:V,directories:be,busy:Me,error:Pe,confirmLabel:"Use this folder",onClose:()=>K(!1),onNavigate:$=>{yt($)},onConfirm:$=>{pe($),le("__custom__"),K(!1)}}),Ge&&t.jsx(fo,{title:Ge.title,description:Ge.description,details:Ge.details,workspaceOptions:Ge.workspaceOptions,selectedWorkspaceKey:ht,onWorkspaceChange:$=>{it.current=$,ze($)},confirmLabel:Ge.confirmLabel,busyLabel:Ge.busyLabel,busy:xt,onConfirm:O,onCancel:()=>{Qe.current=null,ut(null)}}),J&&Tt&&t.jsx(eo,{activeConv:Tt,ides:[],isCreatingChat:!1,isRefreshingHistory:W,savedSessions:Y,isSavedSessionsLoading:W,isResumingSavedSessionId:z,savedHistoryFilters:ue,onSavedHistoryFiltersChange:de,onClose:()=>Z(!1),onNewChat:()=>{D(""),Z(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Mt(L)},onResumeSavedSession:$=>{if(!$.canResume||z)return;const te=Ht($);D($.providerSessionId),St($),ye($.providerSessionId),Z(!1),De({type:$.providerType,workspaceId:te.workspaceId,workspacePath:te.workspacePath,useHome:te.useHome,resumeSessionId:$.providerSessionId}).finally(()=>{ye(fe=>fe===$.providerSessionId?null:fe)})}})]})}const Ri=[{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 Zx({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[g,w]=o.useState(u);o.useEffect(()=>{w(u)},[u]);const A=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Ri.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 ${g===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>w(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${g===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=Ri.find(b=>b.id===g))==null?void 0:d.helper})]}),g==="ide"&&t.jsx(ca,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),g==="cli"&&t.jsx(ca,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),g==="acp"&&t.jsx(ca,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m})]})}function eb({onNicknameSynced:e}={}){var z,ye,ie,le,se,pe,ne,ke,ve;const{id:s}=hd(),r=Vs(),n=_a(),{sendCommand:a}=Pt(),i=Sr(),c=Ac(),l=c.ides||[],u=c.initialLoaded??!0,p=l.find(K=>K.id===s&&K.type==="adhdev-daemon"),m=l.some(K=>K.type==="adhdev-daemon"),[f,g]=o.useState("workspace"),[w,A]=o.useState("ide"),d=o.useRef(null),[b,y]=o.useState(null),h=o.useRef("__home__"),[S,_]=o.useState("__home__"),[k,I]=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]),nf(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:15e3});const v=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=Cx({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>st.onToast(V=>{c.setToasts(be=>{if(be.some(Oe=>Oe.message===V.message&&V.timestamp-Oe.timestamp<3e3))return be;const Me={id:V.id,message:V.message,type:V.type,timestamp:V.timestamp,targetKey:V.targetKey,actions:V.actions};return[...be.slice(-4),Me]});const we=V.duration||5e3;setTimeout(()=>c.setToasts(be=>be.filter(Q=>Q.id!==V.id)),we)}),[c]);const E=(p==null?void 0:p.availableProviders)||[],L={};for(const K of E)L[K.type]=K.icon;const M=K=>L[K]||"",T=p?{id:p.id,hostname:oc(p,{fallbackId:p.id}),platform:((z=p.machine)==null?void 0:z.platform)||"unknown",arch:((ye=p.machine)==null?void 0:ye.arch)||"",cpus:((ie=p.machine)==null?void 0:ie.cpus)||0,totalMem:((le=p.machine)==null?void 0:le.totalMem)||0,freeMem:(se=p.machine)==null?void 0:se.freeMem,availableMem:(pe=p.machine)==null?void 0:pe.availableMem,loadavg:(ne=p.machine)==null?void 0:ne.loadavg,uptime:(ke=p.machine)==null?void 0:ke.uptime,release:((ve=p.machine)==null?void 0:ve.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,B=l.filter(K=>K.daemonId===s&&K.type!=="adhdev-daemon").filter(K=>!xr(K)&&!Ps(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,version:K.version||"",instanceId:K.instanceId||"",status:K.status,workspace:K.workspace||null,terminals:K.terminals||0,aiAgents:Lu(K.aiAgents||(K.agents||[]).map(V=>({id:V.name,name:V.name,status:V.status,version:V.version}))),activeChat:K.activeChat||null,chats:K.chats||[],childSessions:K.childSessions||[],cdpConnected:K.cdpConnected||!1,daemonId:s})),H=l.filter(K=>K.daemonId===s&&xr(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,cliName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,mode:K.mode,runtimeKey:K.runtimeKey,runtimeDisplayName:K.runtimeDisplayName,runtimeWorkspaceLabel:K.runtimeWorkspaceLabel,runtimeWriteOwner:K.runtimeWriteOwner||null,runtimeAttachedClients:K.runtimeAttachedClients||[],daemonId:s})),C=l.filter(K=>K.daemonId===s&&Ps(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,acpName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,daemonId:s})),R=p?_t(p,{fallbackId:s}):"",U="workspace",N=n.state,D=N==null?void 0:N.initialMachineTab,Y=N==null?void 0:N.initialWorkspaceCategory,q=N==null?void 0:N.initialWorkspaceId,W=N==null?void 0:N.initialWorkspacePath,ae=D==="ides"||D==="clis"||D==="acps"?"workspace":D||U,ce=D==="ides"?"ide":D==="clis"?"cli":D==="acps"?"acp":Y,Se=[...B.map(K=>{var V,we,be,Q,Me;return{id:`ide:${K.type}:${K.workspace||""}`,label:((V=K.activeChat)==null?void 0:V.title)||K.type,kind:"ide",providerType:K.type,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:((Me=(Q=(be=(we=K.activeChat)==null?void 0:we.messages)==null?void 0:be.at)==null?void 0:Q.call(be,-1))==null?void 0:Me.timestamp)||0}}),...H.map(K=>{var V,we,be,Q,Me;return{id:`cli:${K.type}:${K.workspace||""}`,label:((V=K.activeChat)==null?void 0:V.title)||K.cliName,kind:"cli",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:((Me=(Q=(be=(we=K.activeChat)==null?void 0:we.messages)==null?void 0:be.at)==null?void 0:Q.call(be,-1))==null?void 0:Me.timestamp)||0}}),...C.map(K=>{var V,we,be,Q,Me;return{id:`acp:${K.type}:${K.workspace||""}`,label:((V=K.activeChat)==null?void 0:V.title)||K.acpName,kind:"acp",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:Ss(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:((Me=(Q=(be=(we=K.activeChat)==null?void 0:we.messages)==null?void 0:be.at)==null?void 0:Q.call(be,-1))==null?void 0:Me.timestamp)||0}})].sort((K,V)=>(V.lastLaunchedAt||0)-(K.lastLaunchedAt||0)),X=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(K=>({id:K.id,label:K.title||K.providerName||K.providerType,kind:K.kind,providerType:K.providerType,providerSessionId:K.providerSessionId,subtitle:Ss(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace,summaryMetadata:K.summaryMetadata,lastLaunchedAt:K.lastLaunchedAt})):Se,he=o.useMemo(()=>{var V;const K=((V=c.connectionStates)==null?void 0:V[s||""])||void 0;return l.filter(we=>we.daemonId===s&&we.type!=="adhdev-daemon").flatMap(we=>to(we,{},{connectionStates:s&&K?{[s]:K}:void 0,defaultConnectionState:K})).filter(we=>!(we.transport==="pty"&&we.mode==="terminal")).sort((we,be)=>ba(be)-ba(we))},[l,c.connectionStates,s]),J=o.useCallback(K=>{const V=za(K);V&&r(as(V))},[r]),Z=o.useCallback(()=>{d.current&&(I(!0),d.current().finally(()=>{d.current=null,I(!1),y(null)}))},[]),ue=o.useCallback(K=>{if(!T)return;const{options:V,selectedKey:we}=vs({machine:T,currentWorkspacePath:K.workspace}),be=async()=>{A(K.kind),g("workspace")};d.current=async()=>{const Q=V.find(Pe=>Pe.key===h.current),Me=(Q==null?void 0:Q.workspacePath)??null,Oe=(Q==null?void 0:Q.workspaceId)??null;if(K.kind==="ide"&&K.providerType){await x.handleLaunchIde(K.providerType,Me?{workspace:Me}:void 0);return}if((K.kind==="cli"||K.kind==="acp")&&K.providerType){await x.runLaunchCliCore({cliType:K.providerType,dir:Oe?void 0:Me||"",workspaceId:Oe||void 0,model:K.kind==="acp"&&cc(K.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:K.providerSessionId});return}await be()},h.current=we,_(we),y({title:K.kind==="ide"?xs("restart-ide",K.label):K.providerSessionId?Qa(K.label):xs("start-fresh",K.label),description:K.kind==="ide"?bs("restart-ide"):K.providerSessionId?Za():bs("start-fresh"),confirmLabel:K.kind==="ide"?Us("restart-ide"):K.providerSessionId?mn(!0):Us("start-fresh"),busyLabel:K.kind==="ide"?zs("restart-ide"):K.providerSessionId?Xa(!0):zs("start-fresh"),workspaceOptions:V,details:[{label:"Mode",value:K.kind.toUpperCase()},...K.providerType?[{label:"Provider",value:K.providerType}]:[]]})},[x,T]);if(o.useEffect(()=>{g(ae)},[U,ae,s]),o.useEffect(()=>{ce&&A(ce)},[ce,s]),!T)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:v,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const de=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rt,{size:14})," Workspace"]}),count:B.length+H.length+C.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Qt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(bn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Kd,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Dd,{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:v,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:K=>x.setNicknameInput(K.target.value),onKeyDown:K=>{K.key==="Enter"&&x.handleSaveNickname(),K.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(T.machineNickname||"")},title:"Click to set nickname",children:R}),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:[T.platform," · ",T.arch]}),t.jsxs("span",{children:[T.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),T.p2p.available&&t.jsxs("span",{children:["P2P ",T.p2p.state==="connected"?"connected":T.p2p.state]}),T.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:T.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:de.map(K=>t.jsxs("button",{onClick:()=>g(K.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===K.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[K.label,K.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===K.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:K.count})]},K.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(Xx,{machineEntry:p,providers:E,recentLaunches:X,currentConversations:he,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:J}),t.jsx(Zx,{machine:T,machineId:s,providers:E,ideSessions:B,cliSessions:H,acpSessions:C,actions:x,getIcon:M,initialCategory:w,initialWorkspaceId:q,initialWorkspacePath:W,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(Px,{machineId:s,providers:E,sendDaemonCommand:a}),f==="overview"&&t.jsx(Ix,{machineId:s,machine:T,ideSessions:B,cliSessions:H,acpSessions:C,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(qx,{machineId:s,cliSessions:H,sendDaemonCommand:a}),f==="logs"&&t.jsx(Ux,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&T&&t.jsx(Yx,{machine:T,launchPick:x.launchPick,actions:x}),b&&t.jsx(fo,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:S,onWorkspaceChange:K=>{h.current=K,_(K)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:k,onConfirm:Z,onCancel:()=>{d.current=null,y(null)}}),t.jsx(Kc,{toasts:c.toasts||[],onDismiss:K=>c.setToasts(V=>V.filter(we=>we.id!==K)),onClickToast:K=>{K.targetKey&&r(as(K.targetKey))}}),t.jsx("style",{children:`
|
|
74
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const M=await r(e,"session_host_prune_duplicate_sessions",{}),T=na(M);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Duplicate prune failed");const B=T.result||{},H=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,C=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;st.showToast(`Pruned ${H} duplicate runtime(s) across ${C} group(s)`,"success"),await d()}catch(M){const T=M instanceof Error?M.message:"Duplicate prune failed";st.showToast(T,"warning"),a(T)}finally{c(M=>M==="session_host_prune_duplicate_sessions"?null:M)}}},[e,d,r]),h=o.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((L,M)=>(M.lastActivityAt||0)-(L.lastActivityAt||0)),[m==null?void 0:m.sessions]),S=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)||[]}:Il(h),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,h]),_=S.liveRuntimes,k=S.recoverySnapshots,I=S.inactiveRecords,j=o.useMemo(()=>Jx(_),[_]),v=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(L=>L.level==="warn"||L.level==="error")||null,[m==null?void 0:m.recentLogs]),E=(L,M)=>{var Y;const T=i===`session_host_resume_session:${L.sessionId}`,B=i===`session_host_restart_session:${L.sessionId}`,H=i===`session_host_stop_session:${L.sessionId}`,C=xo(L.meta),R=A.get(L.sessionId),U=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,N=M==="recovery"?"Recover":"Resume",D=Al(M);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:L.displayName||(R==null?void 0:R.cliName)||L.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Xx(L.lifecycle)}`,children:L.lifecycle}),C&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:L.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((Y=L.writeOwner)==null?void 0:Y.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Yx(L.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(Pa,{size:11})," ",U]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Ri(L.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"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_resume_session",L)},children:T?`${N}ing…`:N}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",L)},children:B?"Restarting…":"Restart"}),M==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{b("session_host_stop_session",L)},children:H?"Stopping…":"Stop"})]})]})},L.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(Qt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:gp()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},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 ${w.toneClass}`,children:w.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:f||l,children:[t.jsx(Gs,{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(ks,{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:k.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:Ri(m.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:aa(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(ks,{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:[aa(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(gn,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$s("live")}),_.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:_.map(L=>E(L,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Qt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$s("recovery")}),k.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:k.map(L=>E(L,"recovery"))})]}),I.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$s("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(L=>E(L,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),v.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:v.map(L=>{var T;const M=h.find(B=>B.sessionId===L.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(M==null?void 0:M.displayName)||((T=A.get(L.sessionId))==null?void 0:T.cliName)||L.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:aa(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:m.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Zx({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 oa({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 ia({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 eb({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=dr(e,"0.8.88");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(oa,{icon:t.jsx(Zt,{size:13}),children:"Current Chats"}),t.jsx(ia,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const g=ba(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:lt(f)}),g>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:vn(g)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Cs(f)})]},f.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(oa,{icon:t.jsx(Xi,{size:13}),children:"Recent Launches"}),t.jsx(ia,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const{metaText:g,updatedLabel:w}=ml(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}),w&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(oa,{icon:t.jsx(ks,{size:13}),children:"Daemon Update"}),t.jsx(ia,{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(Gs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function tb(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const sb={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 Yr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ca({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const m=Vs(),{handleLaunchIde:f,handleStopCli:g,handleRestartIde:w,handleStopIde:A,handleDetectIdes:d,launchingIde:b,launchingAgentType:y,addLog:h}=c,[S,_]=o.useState(null),k=o.useCallback($=>{$&&m(as($))},[m]),I=sb[e],j=e==="ide",v=e==="acp",x=o.useMemo(()=>n.filter($=>$.category===e&&(e==="ide"||$.installed!==!1)),[e,n]),E=o.useMemo(()=>new Map(x.map($=>[$.type,$.displayName||$.type])),[x]),[L,M]=o.useState(""),[T,B]=o.useState(""),[H,C]=o.useState([]),[R,U]=o.useState(""),[N,D]=o.useState(""),[Y,q]=o.useState([]),[W,ae]=o.useState(!1),[ce,Se]=o.useState(!1),[X,he]=o.useState(""),[J,Z]=o.useState(!1),[ue,de]=o.useState(()=>jt()),[z,ye]=o.useState(null),[ie,le]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[se,pe]=o.useState(p||""),[ne,ke]=o.useState([]),[ve,K]=o.useState(!1),[V,we]=o.useState(""),[be,Q]=o.useState([]),[Me,Oe]=o.useState(!1),[Pe,Ke]=o.useState(""),Qe=o.useRef(null),[Ge,ut]=o.useState(null),it=o.useRef("__home__"),[ht,ze]=o.useState("__home__"),[xt,bt]=o.useState(!1),ct=o.useRef(0),Te=ne.filter($=>!a.some(te=>te.type===$&&Ct(te.status)!=="stopped")),Xe=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!ie&&le(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){le("__custom__"),pe(p);return}u&&(le(u),pe(""))},[u,p]),o.useEffect(()=>{j||L&&(x.some($=>$.type===L)||(M(""),D("")))},[x,j,L]);const Fe=(()=>{if(ie==="__custom__")return se.trim();if(!ie)return"";const $=(s.workspaces||[]).find(te=>te.id===ie);return($==null?void 0:$.path)||""})(),Ue=o.useCallback($=>{const te=Xe.current[$];te&&(clearTimeout(te),delete Xe.current[$]),ke(fe=>fe.includes($)?fe.filter(Ee=>Ee!==$):fe)},[]),kt=o.useRef(new Set),yt=o.useCallback(async $=>{if(l){Oe(!0),Ke("");try{const te=await Cn(l,r,$);we(te.path),pe(te.path),Q(te.directories)}catch(te){Ke(te instanceof Error?te.message:"Could not load folder")}finally{Oe(!1)}}},[r,l]),wt=o.useCallback(()=>{if(!l)return;le("__custom__"),K(!0);const $=a.map(fe=>fe.workspace),te=Nn(s.platform,Sn(se.trim(),Fe,p,$,s.defaultWorkspacePath,(s.workspaces||[]).map(fe=>fe.path)));yt(te)},[se,p,yt,s.defaultWorkspacePath,s.platform,s.workspaces,a,Fe,l]),St=o.useCallback($=>{const te=String($.workspace||"").trim();if(!te)return;const fe=(s.workspaces||[]).find(Ee=>Yr(Ee.path)===Yr(te));if(fe){le(fe.id),pe("");return}le("__custom__"),pe(te)},[s.workspaces]),Ht=o.useCallback($=>{const te=String($.workspace||"").trim();if(!te)return{workspaceId:null,workspacePath:"",useHome:!0};const fe=(s.workspaces||[]).find(Ee=>Yr(Ee.path)===Yr(te));return fe?{workspaceId:fe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:te,useHome:!1}},[s.workspaces]),Mt=o.useCallback(async $=>{if(!l||!$||e!=="cli"){q([]),ae(!1),Se(!1),he("");return}const te=ct.current+1;ct.current=te,ae(!0),he("");try{const fe=await l(r,"list_saved_sessions",{providerType:$,kind:"cli",limit:30});if(ct.current!==te)return;const Ee=(fe==null?void 0:fe.result)??fe;q(Array.isArray(Ee==null?void 0:Ee.sessions)?Ee.sessions:[])}catch(fe){if(ct.current!==te)return;q([]),he(fe instanceof Error?fe.message:"Could not load saved sessions")}finally{ct.current===te&&(ae(!1),Se(!0))}},[e,r,l]),Tt=o.useMemo(()=>{if(e!=="cli"||!L)return null;const $=E.get(L)||L;return{routeId:r,daemonId:r,providerSessionId:N||void 0,transport:"pty",mode:"chat",agentName:$,agentType:L,status:"idle",title:$,messages:[],ideType:L,workspaceName:Fe,displayPrimary:$,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${L}`}},[e,r,E,Fe,N,L]),ee=o.useCallback($=>{if(e==="ide"||!$){C([]);return}C(Nl(r,$))},[e,r]);o.useEffect(()=>{ct.current+=1,D(""),ee(L),Se(!1),q([]),he(""),ae(!1)},[e,ee,Mt,L]);const Re=o.useMemo(()=>Y.find($=>$.providerSessionId===N)||null,[Y,N]);o.useEffect(()=>{if(!N)return;const $=Y.find(te=>te.providerSessionId===N);$!=null&&$.canResume||D("")},[Y,N]);const P=o.useCallback(($,te)=>{Qe.current=te,it.current=$.selectedWorkspaceKey||"__home__",ze($.selectedWorkspaceKey||"__home__"),ut($)},[]),O=o.useCallback(()=>{Qe.current&&(bt(!0),Qe.current().finally(()=>{Qe.current=null,bt(!1),ut(null)}))},[]),F=o.useCallback($=>{if(!$)return;ke(fe=>fe.includes($)?fe:[...fe,$]);const te=Xe.current[$];te&&clearTimeout(te),Xe.current[$]=setTimeout(()=>{ke(fe=>fe.includes($)?fe.filter(Ee=>Ee!==$):fe),delete Xe.current[$]},2e4)},[]);o.useEffect(()=>{for(const te of a)Ct(te.status)!=="stopped"&&(ne.includes(te.type)&&!kt.current.has(te.type)&&(kt.current.add(te.type),h("info",`${E.get(te.type)||te.type} launched`,!0)),Ue(te.type));const $=new Set(a.filter(te=>Ct(te.status)!=="stopped").map(te=>te.type));kt.current.forEach(te=>{!ne.includes(te)&&!$.has(te)&&kt.current.delete(te)})},[h,Ue,a,ne,E]),o.useEffect(()=>()=>{Object.values(Xe.current).forEach(clearTimeout),Xe.current={}},[]);const[G,oe]=o.useState({}),[Ie,_e]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const te=await l(r,"get_ide_extensions",{}),fe=(te==null?void 0:te.result)||te;fe!=null&&fe.success&&(fe!=null&&fe.ideExtensions)&&oe(fe.ideExtensions)}catch{}})()},[j,r,l]);const Ae=$=>j?ot($.type):e==="cli"?$.cliName:$.acpName,We=j?s.detectedIdes||[]:[],De=o.useCallback(async $=>{const te=($==null?void 0:$.type)||L,fe=($==null?void 0:$.workspacePath)??Fe;if(j){await f(te,fe?{workspace:fe}:void 0)&&F(te);return}const Ee=await c.runLaunchCliCore({cliType:te,dir:$!=null&&$.workspaceId?void 0:fe||void 0,workspaceId:($==null?void 0:$.workspaceId)||void 0,useHome:($==null?void 0:$.useHome)||!($!=null&&$.workspaceId)&&!fe,argsStr:($==null?void 0:$.argsStr)??(T||void 0),model:($==null?void 0:$.model)??(v&&R||void 0),resumeSessionId:($==null?void 0:$.resumeSessionId)||!v&&e==="cli"&&te===L&&N||void 0});if(Ee.success||Ee.pending){const Le=($==null?void 0:$.argsStr)??T;!j&&(Le!=null&&Le.trim())&&(Cl(r,te,Le),ee(te)),F(te),Ee.success&&Ee.sessionId&&k(Ee.sessionId)}},[c,f,v,j,T,R,ee,F,r,k,Fe,N,L]),Je=$c(j?"ide":v?"acp":"cli",!j&&!v&&!!N),Ve=Kc(j?"ide":v?"acp":"cli",!j&&!v&&!!N),re=()=>{var Le;const $=j?ot(L):E.get(L)||L,te=!j&&!v&&!!N,{options:fe,selectedKey:Ee}=vs({machine:s,currentWorkspaceId:ie&&ie!=="__custom__"?ie:null,currentWorkspacePath:Fe});P({title:te?Qa($):xs("start-fresh",$),description:te?Za():bs("start-fresh"),confirmLabel:Je,busyLabel:Ve,workspaceOptions:fe,selectedWorkspaceKey:Ee,details:[{label:"Mode",value:I.label},{label:"Provider",value:$},...!j&&e==="cli"&&N?[{label:"Resume",value:((Le=Y.find(Ne=>Ne.providerSessionId===N))==null?void 0:Le.title)||N}]:[],...!j&&T.trim()?[{label:"Arguments",value:T.trim()}]:[],...v&&R.trim()?[{label:"Model",value:R.trim()}]:[]]},async()=>{const Ne=fe.find(et=>et.key===it.current);Ne!=null&&Ne.workspaceId?(le(Ne.workspaceId),pe("")):Ne!=null&&Ne.workspacePath?(le("__custom__"),pe(Ne.workspacePath)):(le(""),pe("")),await De({workspaceId:(Ne==null?void 0:Ne.workspaceId)??null,workspacePath:(Ne==null?void 0:Ne.workspacePath)??"",useHome:!(Ne!=null&&Ne.workspaceId)&&!(Ne!=null&&Ne.workspacePath)})})},je=$=>{j?A($):g($.type,$.workspace,$.id)},Be=o.useCallback(async($,te,fe=!1)=>{if($.mode===te){fe&&$.sessionId&&k($.sessionId);return}if(!l||!$.sessionId){fe&&$.sessionId&&k($.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:$.sessionId,cliType:$.type,mode:te}),fe&&k($.sessionId)}catch(Ee){const Le=co(Ee);io(Ee)?console.warn(Le?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ee instanceof Error?Ee.message:String(Ee)):console.error("Failed to switch CLI view mode:",Ee)}},[r,k,l]),rt=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ie,onChange:$=>{const te=$.target.value;if(le(te),te==="__custom__"&&l){wt();return}te!=="__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?"⭐ ":"",jn($.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…"})]})}),ie==="__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:wt,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:ie==="__custom__"?Fe?t.jsx("span",{className:"font-mono truncate block",title:Fe,children:Fe}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Fe?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ie===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:Fe,children:Fe})]}):"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 ${I.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 ",I.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?We.length>0?We.map($=>{const te=a.find(et=>(et.type||"").toLowerCase()===($.type||"").toLowerCase()&&Ct(et.status)!=="stopped"),fe=$.running||!!te,Ee=!!te&&te.cdpConnected,Le=ne.includes($.type||$.id||""),Ne=L===($.type||"");return t.jsxs("button",{onClick:()=>{if(Ee&&te){const et=te.sessionId;et?m(as(et),{state:{openRemoteForTabKey:et}}):m("/dashboard",{state:{openRemoteForTabKey:te.id}});return}Le||M(et=>et===($.type||"")?"":$.type||"")},disabled:!!b||Le,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ee?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ne?"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)}),fe&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ee?"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 ${Ee?"text-green-400":Le?"text-orange-400":Ne?"text-accent-primary":"text-text-muted"}`,children:Ee?"Open Session":Le?"Starting...":Ne?"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(Kd,{size:14})," Scan System"]})]}):x.length>0?x.map($=>{const te=L===$.type,fe=ne.includes($.type),Le=!!a.find(Ne=>Ne.type===$.type&&Ct(Ne.status)!=="stopped");return t.jsxs("button",{onClick:()=>M(Ne=>Ne===$.type?"":$.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${te?"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}),Le&&t.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:$.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${fe?"text-orange-400":te?"text-accent-primary":"text-text-muted"}`,children:fe?"Starting...":te?"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."})]})}),L&&(j?We.find($=>$.type===L):x.find($=>$.type===L))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?ot(L):E.get(L)||L})]}),rt,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&t.jsx(Tl,{busy:!!y||!!b||ne.includes(L),savedSessionsLoading:W,savedSessionsError:X,selectedSession:Re,onRefresh:()=>void Mt(L),onOpenHistory:()=>{L&&(Z(!0),Ml({hasLoadedInitialResults:ce,isLoading:W})&&Mt(L))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:R,onChange:$=>U($.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:T,onChange:$=>B($.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),H.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:H.map($=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>B($),title:$,children:$},$))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:re,disabled:!!y||!!b||ne.includes(L),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:y===L||b===L?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ne.filter($=>!a.some(te=>te.type===$&&Ct(te.status)!=="stopped")).length,")"]}),a.length===0&&Te.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 ",I.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Te.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($):E.get($)||$}),t.jsx("div",{className:"text-[11px] text-text-muted",children:y===$?"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 te=j?$:null,fe=!j&&!v?$:null,Ee=Ct($.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:[Ae($),(te==null?void 0:te.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",te.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:$.workspace||"—"}),(fe==null?void 0:fe.mode)&&t.jsx("span",{className:fe.mode==="chat"?"text-violet-400":"text-text-secondary",children:fe.mode==="chat"?"Chat view":"Terminal view"})]}),fe&&(fe.runtimeKey||fe.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[fe.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 ",fe.runtimeKey]}),t.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Le;(Le=navigator.clipboard)==null||Le.writeText(`adhdev attach ${fe.runtimeKey}`),_(fe.runtimeKey||null),window.setTimeout(()=>{_(Ne=>Ne===fe.runtimeKey?null:Ne)},1200)},children:S===fe.runtimeKey?"Copied":"Copy"})]}),fe.runtimeWriteOwner&&t.jsx("span",{style:{color:fe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:fe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:tb(fe.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 ${Ee==="stopped"?"bg-red-500/[0.08] text-red-500":Ee==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ee}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Le=$.sessionId;if(Le){m(as(Le),{state:{openRemoteForTabKey:Le}});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(Rt,{size:13})}),t.jsx("button",{onClick:()=>{const Le=$.workspace||"",{options:Ne,selectedKey:et}=vs({machine:s,currentWorkspacePath:Le});P({title:xs("restart-ide",ot($.type)),description:bs("restart-ide"),confirmLabel:Us("restart-ide"),busyLabel:zs("restart-ide"),workspaceOptions:Ne,selectedWorkspaceKey:et,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ot($.type)}]},async()=>{const $e=Ne.find(es=>es.key===it.current),mt=($e==null?void 0:$e.workspacePath)??"";if(mt&&mt!==Le){await De({type:$.type,workspacePath:mt});return}await w($)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:t.jsx(Gs,{size:14})})]}),v&&t.jsx("button",{onClick:()=>{const Le=$.sessionId;Le&&k(Le)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!$.sessionId,children:t.jsx(Zt,{size:14})}),fe&&Ee!=="stopped"&&t.jsxs(t.Fragment,{children:[fe.mode&&t.jsx(Ya,{mode:fe.mode,onChange:Le=>void Be(fe,Le,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Le=$.sessionId;Le&&k(Le)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!$.sessionId,children:fe.mode==="chat"?t.jsx(Zt,{size:14}):t.jsx(Rt,{size:13})})]}),Ee==="stopped"?t.jsx("button",{onClick:()=>{const Le=$.workspace||"",Ne=j?ot($.type):Ae($),{options:et,selectedKey:$e}=vs({machine:s,currentWorkspacePath:Le});P({title:xs("restart-stopped",Ne),description:bs("restart-stopped"),confirmLabel:Us("restart-stopped"),busyLabel:zs("restart-stopped"),workspaceOptions:et,selectedWorkspaceKey:$e,details:[{label:"Mode",value:I.label},{label:"Provider",value:Ne}]},async()=>{const mt=et.find(es=>es.key===it.current);await De({type:$.type,workspaceId:(mt==null?void 0:mt.workspaceId)??null,workspacePath:(mt==null?void 0:mt.workspacePath)??"",useHome:!(mt!=null&&mt.workspaceId)&&!(mt!=null&&mt.workspacePath)})})},disabled:ne.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:ne.includes($.type)?"⏳":t.jsx(Ea,{size:14})}):t.jsx("button",{onClick:()=>je($),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(At,{size:14})})]})]}),te&&te.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:te.aiAgents.map(Le=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${oc(Le.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Le.name," · ",Ct(Le.status)]},Le.id))}),te&&(G[te.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:(G[te.type]||[]).map(Le=>t.jsxs("button",{disabled:Ie===`${te.type}.${Le.type}`,onClick:async()=>{const Ne=`${te.type}.${Le.type}`;_e(Ne);try{await l(r,"set_ide_extension",{ideType:te.type,extensionType:Le.type,enabled:!Le.enabled}),oe(et=>({...et,[te.type]:(et[te.type]||[]).map($e=>$e.type===Le.type?{...$e,enabled:!$e.enabled}:$e)}))}catch(et){console.error("Extension toggle failed:",et)}finally{_e(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Le.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Le.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Le.name,t.jsx("span",{className:"text-[9px] font-normal",children:Le.enabled?"ON":"OFF"})]},Le.type))})]})]},$.id)})]}),ve&&l&&t.jsx(In,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:V,directories:be,busy:Me,error:Pe,confirmLabel:"Use this folder",onClose:()=>K(!1),onNavigate:$=>{yt($)},onConfirm:$=>{pe($),le("__custom__"),K(!1)}}),Ge&&t.jsx(fo,{title:Ge.title,description:Ge.description,details:Ge.details,workspaceOptions:Ge.workspaceOptions,selectedWorkspaceKey:ht,onWorkspaceChange:$=>{it.current=$,ze($)},confirmLabel:Ge.confirmLabel,busyLabel:Ge.busyLabel,busy:xt,onConfirm:O,onCancel:()=>{Qe.current=null,ut(null)}}),J&&Tt&&t.jsx(eo,{activeConv:Tt,ides:[],isCreatingChat:!1,isRefreshingHistory:W,savedSessions:Y,isSavedSessionsLoading:W,isResumingSavedSessionId:z,savedHistoryFilters:ue,onSavedHistoryFiltersChange:de,onClose:()=>Z(!1),onNewChat:()=>{D(""),Z(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Mt(L)},onResumeSavedSession:$=>{if(!$.canResume||z)return;const te=Ht($);D($.providerSessionId),St($),ye($.providerSessionId),Z(!1),De({type:$.providerType,workspaceId:te.workspaceId,workspacePath:te.workspacePath,useHome:te.useHome,resumeSessionId:$.providerSessionId}).finally(()=>{ye(fe=>fe===$.providerSessionId?null:fe)})}})]})}const Pi=[{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 rb({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[g,w]=o.useState(u);o.useEffect(()=>{w(u)},[u]);const A=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Pi.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 ${g===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>w(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${g===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:A[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=Pi.find(b=>b.id===g))==null?void 0:d.helper})]}),g==="ide"&&t.jsx(ca,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),g==="cli"&&t.jsx(ca,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),g==="acp"&&t.jsx(ca,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m})]})}function nb({onNicknameSynced:e}={}){var z,ye,ie,le,se,pe,ne,ke,ve;const{id:s}=xd(),r=Vs(),n=_a(),{sendCommand:a}=Pt(),i=Sr(),c=Mc(),l=c.ides||[],u=c.initialLoaded??!0,p=l.find(K=>K.id===s&&K.type==="adhdev-daemon"),m=l.some(K=>K.type==="adhdev-daemon"),[f,g]=o.useState("workspace"),[w,A]=o.useState("ide"),d=o.useRef(null),[b,y]=o.useState(null),h=o.useRef("__home__"),[S,_]=o.useState("__home__"),[k,I]=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]),df(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:Nm});const v=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=Tx({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:j});o.useEffect(()=>st.onToast(V=>{c.setToasts(be=>{if(be.some(Oe=>Oe.message===V.message&&V.timestamp-Oe.timestamp<3e3))return be;const Me={id:V.id,message:V.message,type:V.type,timestamp:V.timestamp,targetKey:V.targetKey,actions:V.actions};return[...be.slice(-4),Me]});const we=V.duration||5e3;setTimeout(()=>c.setToasts(be=>be.filter(Q=>Q.id!==V.id)),we)}),[c]);const E=(p==null?void 0:p.availableProviders)||[],L={};for(const K of E)L[K.type]=K.icon;const M=K=>L[K]||"",T=p?{id:p.id,hostname:ic(p,{fallbackId:p.id}),platform:((z=p.machine)==null?void 0:z.platform)||"unknown",arch:((ye=p.machine)==null?void 0:ye.arch)||"",cpus:((ie=p.machine)==null?void 0:ie.cpus)||0,totalMem:((le=p.machine)==null?void 0:le.totalMem)||0,freeMem:(se=p.machine)==null?void 0:se.freeMem,availableMem:(pe=p.machine)==null?void 0:pe.availableMem,loadavg:(ne=p.machine)==null?void 0:ne.loadavg,uptime:(ke=p.machine)==null?void 0:ke.uptime,release:((ve=p.machine)==null?void 0:ve.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,B=l.filter(K=>K.daemonId===s&&K.type!=="adhdev-daemon").filter(K=>!xr(K)&&!Ps(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,version:K.version||"",instanceId:K.instanceId||"",status:K.status,workspace:K.workspace||null,terminals:K.terminals||0,aiAgents:_u(K.aiAgents||(K.agents||[]).map(V=>({id:V.name,name:V.name,status:V.status,version:V.version}))),activeChat:K.activeChat||null,chats:K.chats||[],childSessions:K.childSessions||[],cdpConnected:K.cdpConnected||!1,daemonId:s})),H=l.filter(K=>K.daemonId===s&&xr(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,cliName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,mode:K.mode,runtimeKey:K.runtimeKey,runtimeDisplayName:K.runtimeDisplayName,runtimeWorkspaceLabel:K.runtimeWorkspaceLabel,runtimeWriteOwner:K.runtimeWriteOwner||null,runtimeAttachedClients:K.runtimeAttachedClients||[],daemonId:s})),C=l.filter(K=>K.daemonId===s&&Ps(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,acpName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,daemonId:s})),R=p?_t(p,{fallbackId:s}):"",U="workspace",N=n.state,D=N==null?void 0:N.initialMachineTab,Y=N==null?void 0:N.initialWorkspaceCategory,q=N==null?void 0:N.initialWorkspaceId,W=N==null?void 0:N.initialWorkspacePath,ae=D==="ides"||D==="clis"||D==="acps"?"workspace":D||U,ce=D==="ides"?"ide":D==="clis"?"cli":D==="acps"?"acp":Y,Se=[...B.map(K=>{var V,we,be,Q,Me;return{id:`ide:${K.type}:${K.workspace||""}`,label:((V=K.activeChat)==null?void 0:V.title)||K.type,kind:"ide",providerType:K.type,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:((Me=(Q=(be=(we=K.activeChat)==null?void 0:we.messages)==null?void 0:be.at)==null?void 0:Q.call(be,-1))==null?void 0:Me.timestamp)||0}}),...H.map(K=>{var V,we,be,Q,Me;return{id:`cli:${K.type}:${K.workspace||""}`,label:((V=K.activeChat)==null?void 0:V.title)||K.cliName,kind:"cli",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:((Me=(Q=(be=(we=K.activeChat)==null?void 0:we.messages)==null?void 0:be.at)==null?void 0:Q.call(be,-1))==null?void 0:Me.timestamp)||0}}),...C.map(K=>{var V,we,be,Q,Me;return{id:`acp:${K.type}:${K.workspace||""}`,label:((V=K.activeChat)==null?void 0:V.title)||K.acpName,kind:"acp",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:Ss(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:((Me=(Q=(be=(we=K.activeChat)==null?void 0:we.messages)==null?void 0:be.at)==null?void 0:Q.call(be,-1))==null?void 0:Me.timestamp)||0}})].sort((K,V)=>(V.lastLaunchedAt||0)-(K.lastLaunchedAt||0)),X=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(K=>({id:K.id,label:K.title||K.providerName||K.providerType,kind:K.kind,providerType:K.providerType,providerSessionId:K.providerSessionId,subtitle:Ss(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace,summaryMetadata:K.summaryMetadata,lastLaunchedAt:K.lastLaunchedAt})):Se,he=o.useMemo(()=>{var V;const K=((V=c.connectionStates)==null?void 0:V[s||""])||void 0;return l.filter(we=>we.daemonId===s&&we.type!=="adhdev-daemon").flatMap(we=>to(we,{},{connectionStates:s&&K?{[s]:K}:void 0,defaultConnectionState:K})).filter(we=>!(we.transport==="pty"&&we.mode==="terminal")).sort((we,be)=>ba(be)-ba(we))},[l,c.connectionStates,s]),J=o.useCallback(K=>{const V=za(K);V&&r(as(V))},[r]),Z=o.useCallback(()=>{d.current&&(I(!0),d.current().finally(()=>{d.current=null,I(!1),y(null)}))},[]),ue=o.useCallback(K=>{if(!T)return;const{options:V,selectedKey:we}=vs({machine:T,currentWorkspacePath:K.workspace}),be=async()=>{A(K.kind),g("workspace")};d.current=async()=>{const Q=V.find(Pe=>Pe.key===h.current),Me=(Q==null?void 0:Q.workspacePath)??null,Oe=(Q==null?void 0:Q.workspaceId)??null;if(K.kind==="ide"&&K.providerType){await x.handleLaunchIde(K.providerType,Me?{workspace:Me}:void 0);return}if((K.kind==="cli"||K.kind==="acp")&&K.providerType){await x.runLaunchCliCore({cliType:K.providerType,dir:Oe?void 0:Me||"",workspaceId:Oe||void 0,model:K.kind==="acp"&&lc(K.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:K.providerSessionId});return}await be()},h.current=we,_(we),y({title:K.kind==="ide"?xs("restart-ide",K.label):K.providerSessionId?Qa(K.label):xs("start-fresh",K.label),description:K.kind==="ide"?bs("restart-ide"):K.providerSessionId?Za():bs("start-fresh"),confirmLabel:K.kind==="ide"?Us("restart-ide"):K.providerSessionId?mn(!0):Us("start-fresh"),busyLabel:K.kind==="ide"?zs("restart-ide"):K.providerSessionId?Xa(!0):zs("start-fresh"),workspaceOptions:V,details:[{label:"Mode",value:K.kind.toUpperCase()},...K.providerType?[{label:"Provider",value:K.providerType}]:[]]})},[x,T]);if(o.useEffect(()=>{g(ae)},[U,ae,s]),o.useEffect(()=>{ce&&A(ce)},[ce,s]),!T)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:v,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const de=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rt,{size:14})," Workspace"]}),count:B.length+H.length+C.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Qt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(bn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bd,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ed,{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:v,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:K=>x.setNicknameInput(K.target.value),onKeyDown:K=>{K.key==="Enter"&&x.handleSaveNickname(),K.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(T.machineNickname||"")},title:"Click to set nickname",children:R}),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:[T.platform," · ",T.arch]}),t.jsxs("span",{children:[T.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),T.p2p.available&&t.jsxs("span",{children:["P2P ",T.p2p.state==="connected"?"connected":T.p2p.state]}),T.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:T.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:de.map(K=>t.jsxs("button",{onClick:()=>g(K.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===K.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[K.label,K.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===K.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:K.count})]},K.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(eb,{machineEntry:p,providers:E,recentLaunches:X,currentConversations:he,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ue,onOpenConversation:J}),t.jsx(rb,{machine:T,machineId:s,providers:E,ideSessions:B,cliSessions:H,acpSessions:C,actions:x,getIcon:M,initialCategory:w,initialWorkspaceId:q,initialWorkspacePath:W,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(Kx,{machineId:s,providers:E,sendDaemonCommand:a}),f==="overview"&&t.jsx(Lx,{machineId:s,machine:T,ideSessions:B,cliSessions:H,acpSessions:C,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(Qx,{machineId:s,cliSessions:H,sendDaemonCommand:a}),f==="logs"&&t.jsx(qx,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&T&&t.jsx(Zx,{machine:T,launchPick:x.launchPick,actions:x}),b&&t.jsx(fo,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:S,onWorkspaceChange:K=>{h.current=K,_(K)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:k,onConfirm:Z,onCancel:()=>{d.current=null,y(null)}}),t.jsx(Bc,{toasts:c.toasts||[],onDismiss:K=>c.setToasts(V=>V.filter(we=>we.id!==K)),onClickToast:K=>{K.targetKey&&r(as(K.targetKey))}}),t.jsx("style",{children:`
|
|
75
75
|
@keyframes toast-in {
|
|
76
76
|
from { opacity: 0; transform: translateX(40px); }
|
|
77
77
|
to { opacity: 1; transform: translateX(0); }
|
|
78
78
|
}
|
|
79
|
-
`})]})}function go(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function tb(e){if(typeof window>"u")return e;const s=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=go();return r&&!s.searchParams.has("token")&&s.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?s.toString():`${s.pathname}${s.search}${s.hash}`}async function Ut(e,s){return await fetch(tb(e),{credentials:"same-origin",...s})}function Rl(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class sb{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1){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 Ut(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const a=await n.json();this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof a.seq=="number"?a.seq:0,text:typeof a.text=="string"?a.text:"",truncated:!!a.truncated,cols:typeof a.cols=="number"?a.cols:void 0,rows:typeof a.rows=="number"?a.rows:void 0})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Yt=new sb;function rb(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=go();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Xr=rb(),Pi=3e3,nb=3e4;let zt=null,ab=0;const xn=new Map;let ds=null,mr=null;function Di(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function rr(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function ob(e){return e==="connected"?"connected":e}async function rn(e,s,r){const n=Np(e,r||{}),a=zt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++ab}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{xn.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);xn.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 Aa(e,s){const r=zt;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class ib{constructor(s){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(zt==null?void 0:zt.readyState)===WebSocket.OPEN}get connectionState(){return(zt==null?void 0:zt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return rn(this.daemonId,s,r)}async sendInput(s,r){return rn(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,ds&&(clearInterval(ds),ds=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await rn(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Yt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ds=setInterval(r,2e3)}stopScreenshots(s){ds&&(clearInterval(ds),ds=null)}}let Kt=null;function cb(e){return(!Kt||Kt.daemonId!==e)&&(Kt=new ib(e)),Kt}function lb({children:e}){const s=o.useRef(cn()),r=cn();s.current=r;const{setUserName:n}=js(),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),mr==null||mr(d,b)},[]),p=o.useRef(null),m=o.useRef(),f=o.useRef(Pi),g=o.useRef(!0),w=o.useRef(!1),A=o.useRef("initial_connect");return o.useEffect(()=>{g.current=!0,w.current=!1;function d(){var h,S;if(!g.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((S=p.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Xr}...`),rr("connect_attempt",{url:Xr,reason:A.current,delayMs:f.current});let y;try{y=new WebSocket(Xr)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),b();return}p.current=y,y.onopen=()=>{if(!g.current){y.close();return}u("connected"),f.current=Pi,rr("open",{url:Xr,reason:A.current}),os.resubscribeAll({sendData:Aa}),console.log("[Standalone WS] Connected")},zt=y,y.onmessage=_=>{var k,I;try{const j=JSON.parse(_.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const v=xn.get(j.requestId);v&&(xn.delete(j.requestId),j.type==="error"?v.reject(new Error(((k=j.data)==null?void 0:k.message)||"Command failed")):v.resolve(j.data));return}if(j.type==="session_output"){const v=j.sessionId||j.cliId||j.cliType;v&&Yt.emitSessionOutput(v,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Yt.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 v=j.update;v&&os.publish(v);return}if(j.type==="status"||j.type==="initial_state"){const v=j.data;if(!v)return;const{injectEntries:x,markLoaded:E,getIdes:L}=s.current,M=v.instanceId||"standalone",T=L().find(C=>C.id===M),B=cb(M);Yt.register(M,B),Yt.setState(M,"connected"),u("connected",M),Yt.emitStatus(M,v);const H=un(v,{daemonId:M,existingDaemon:T,existingEntries:L()});Di("ws_status",{type:j.type,daemonId:M,sessions:(v.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(v.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Di("entries",{daemonId:M,entries:H.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),H.length>0&&x(H,{authoritativeDaemonIds:[M]}),E(),c.current!==M&&((I=i.current)==null||I.call(i),c.current=M,i.current=os.subscribe({sendData:Aa},M,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${M}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const R=s.current.getIdes(),U=R.find(D=>D.id===M),N=un(C.status,{daemonId:M,existingDaemon:U,existingEntries:R,timestamp:C.timestamp});N.length>0&&s.current.injectEntries(N),C.userName&&a.current&&a.current(C.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},y.onclose=_=>{g.current&&(Kt==null||Kt.stopScreenshots(),Kt&&Yt.setState(Kt.daemonId,"disconnected"),u("disconnected"),p.current=null,A.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,rr("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),b())},y.onerror=_=>{w.current||!g.current||(A.current="error",rr("error",{message:_ instanceof Event?"event":String(_),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function b(){if(!g.current)return;clearTimeout(m.current);const y=f.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),rr("schedule_reconnect",{reason:A.current,delayMs:y}),m.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,nb),d()},y)}return d(),()=>{var y;g.current=!1,w.current=!0,(y=i.current)==null||y.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,zt=null),Kt&&(Kt.stopScreenshots(),Yt.unregister(Kt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function db({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(mr=(c,l)=>{r(c),l&&a(l)},()=>{mr=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=ob(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(Nd,{connectionOverrides:i,children:t.jsx(lb,{children:e})})}const Pl="adhdev_standalone_font_preferences",ws={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Tn=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],vr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],ub=new Set(Tn.map(e=>e.id)),mb=new Set(vr.map(e=>e.id));function Vt(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:nn("chat",s.chat),code:nn("code",s.code),terminal:nn("terminal",s.terminal)}}function nn(e,s){const r=ws[e],n=s&&typeof s=="object"&&!Array.isArray(s)?s:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?ub:mb).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function an(e,s){var a;const r=nn(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Tn:vr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function pb(e){const s=Vt(e),r=an("chat",s.chat),n=an("code",s.code),a=an("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ms(e,s=document.documentElement){const r=Vt(e),n=pb(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))s.style.setProperty(a,i);return r}function Ma(e){const s=Vt(e);try{localStorage.setItem(Pl,JSON.stringify(s))}catch{}return s}function fb(){try{const e=localStorage.getItem(Pl);if(e)return Vt(JSON.parse(e))}catch{}return ws}function hb(){return ms(fb())}function nr(e,s){var n;const r=e==="chat"?Tn:vr;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const xb=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Ui,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Qt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(bn,{}),label:"Settings"}];function bb({children:e}){const s=Vs(),r=_a(),[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(At,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:xb.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(zi,{})}),!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(Vi,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.86"]}),t.jsx($p,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:u,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const gb=[{icon:t.jsx(Qt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Zt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Gi,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Rt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(fr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(zi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],yb=[{icon:t.jsx(Wd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Ui,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(yn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Pd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(Pa,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Ed,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],vb=[{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 wb(){return t.jsxs(Uc,{icon:t.jsx(Vi,{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.86"]}),children:[t.jsx(Lt,{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(Lt,{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:gb.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(Lt,{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:Wc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Fc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Hc.map(e=>`${e.icon} ${e.name}`)}].map(e=>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(Lt,{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:yb.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(Lt,{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:vb.map((e,s)=>t.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[t.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?t.jsx("span",{className:"text-emerald-500",children:"✓"}):t.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:t.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),t.jsx(zc,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:"Cloud is optional, not required",description:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",action:t.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),t.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[t.jsx(Jd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function la(e,s,r){return{...e,[s]:r}}function da({surface:e,title:s,description:r,value:n,options:a,onChange:i}){return t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:s}),t.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>t.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",t.jsx("span",{className:"font-mono break-all",children:an(e,n)})]})]})]})}function jb({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const p=JSON.stringify(e)!==JSON.stringify(s);return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&t.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&t.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),t.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[t.jsx(da,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Tn,onChange:m=>i(la(e,"chat",m))}),t.jsx(da,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:vr,onChange:m=>i(la(e,"code",m))}),t.jsx(da,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:vr,onChange:m=>i(la(e,"terminal",m))})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),t.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",nr("chat",e.chat.preset)," · Code: ",nr("code",e.code.preset)," · Terminal: ",nr("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",nr("chat",ws.chat.preset)," / ",nr("code",ws.code.preset)]})]}),t.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:t.jsxs("div",{className:"chat-container-content",children:[t.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:t.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[t.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[t.jsx("span",{className:"chat-sender",children:"Hermes"}),t.jsx("span",{className:"chat-time",children:"now"})]}),t.jsxs("div",{className:"chat-markdown",children:[t.jsxs("p",{children:["Readable prose, ",t.jsx("strong",{children:"bold text"}),", and ",t.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),t.jsx("pre",{children:t.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),t.jsxs("div",{className:"chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"▸"}),t.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),t.jsxs("div",{className:"chat-msg-terminal",children:[t.jsx("div",{className:"chat-msg-header",children:"Terminal"}),t.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:c,disabled:r||!p,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),t.jsx("button",{type:"button",onClick:l,disabled:r||!p,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),t.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function kb(){const{ides:e}=js(),s=e.find(J=>J.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Pt(),{userName:a}=js(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[p,m]=o.useState(null),[f,g]=o.useState(ws),[w,A]=o.useState(!1),[d,b]=o.useState(""),[y,h]=o.useState(""),[S,_]=o.useState("127.0.0.1"),[k,I]=o.useState(""),[j,v]=o.useState(""),[x,E]=o.useState(""),[L,M]=o.useState(""),[T,B]=o.useState(""),[H,C]=o.useState(!1),R=async()=>{const Z=await(await Ut("/auth/session")).json();u(Z)},U=async()=>{const Z=await(await Ut("/api/v1/standalone/preferences")).json();m(Z),_(Z.standaloneBindHost);const ue=Vt(Z.standaloneFontPreferences);g(ue),ms(ue),Ma(ue)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([R(),U()]).catch(J=>{M(J instanceof Error?J.message:String(J))})},[]),o.useEffect(()=>{ms(f)},[f]);const N=J=>{const Z=J.target.value.trim();s!=null&&s.id&&Z!==a&&n(s.id,"set_user_name",{userName:Z}).catch(console.error)},[D,Y]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),q=J=>{Y(J);try{localStorage.setItem("adhdev_sound",J?"1":"0")}catch{}},W=async()=>{b(""),h(""),A(!0);try{const J=Vt(f),Z=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:J})}),ue=await Z.json();if(!Z.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to save standalone font preferences");const de=Vt(ue.standaloneFontPreferences);m(ue),g(de),ms(de),Ma(de),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(J){b(J instanceof Error?J.message:String(J))}finally{A(!1)}},ae=()=>{const J=Vt(p==null?void 0:p.standaloneFontPreferences);b(""),h(""),g(J),ms(J)},ce=()=>{b(""),h(""),g(ws),ms(ws)},Se=async()=>{M(""),B(""),C(!0);try{const J=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:S})}),Z=await J.json();if(!J.ok)throw new Error((Z==null?void 0:Z.error)||"Failed to save standalone network preference");m(Z),_(Z.standaloneBindHost),B(Z.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(J){M(J instanceof Error?J.message:String(J))}finally{C(!1)}},X=async()=>{if(M(""),B(""),j.trim().length<4){M("Password must be at least 4 characters.");return}if(j!==x){M("New password and confirmation do not match.");return}C(!0);try{const J=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:j})}),Z=await J.json();if(!J.ok)throw new Error((Z==null?void 0:Z.error)||"Failed to save password");u(Z),await U(),I(""),v(""),E(""),B(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Rl()}catch(J){M(J instanceof Error?J.message:String(J))}finally{C(!1)}},he=async()=>{M(""),B(""),C(!0);try{const J=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),Z=await J.json();if(!J.ok)throw new Error((Z==null?void 0:Z.error)||"Failed to clear password");u(Z),await U(),I(""),v(""),E(""),B("Standalone password disabled.")}catch(J){M(J instanceof Error?J.message:String(J))}finally{C(!1)}};return t.jsxs(Uc,{icon:t.jsx(bn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Br,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&t.jsx(Br,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),t.jsx(Lt,{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.86"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(Lt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="127.0.0.1",onChange:()=>_("127.0.0.1")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="0.0.0.0",onChange:()=>_("0.0.0.0")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:()=>{Se()},disabled:H,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:H?"Saving…":"Save default network mode"}),t.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Lt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),L&&t.jsx(Br,{variant:"error",children:L}),T&&t.jsx(Br,{variant:"success",children:T}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:k,onChange:J=>I(J.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:j,onChange:J=>v(J.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:x,onChange:J=>E(J.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{X()},disabled:H,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:H?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{he()},disabled:H,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),t.jsx(Lt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(J=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${J.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:J.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:J.type})]},J.type))})}),t.jsx(Lt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Wp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Lt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(zp,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),t.jsx(Zp,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),t.jsx(jb,{value:f,savedValue:Vt(p==null?void 0:p.standaloneFontPreferences),saving:w,error:d,notice:y,onChange:g,onSave:()=>{W()},onResetToSaved:ae,onResetToDefaults:ce})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout."}),t.jsx(sf,{})]})]})}),t.jsx(Lt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Kp,{}),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Xd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:D,onChange:q})]})}),t.jsx(Lt,{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(Rd,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:J=>c(J.target.value),onBlur:N,onKeyDown:J=>{J.key==="Enter"&&J.currentTarget.blur()}})]})})})]})}Ep();Jp();hb();const Sb=Wi({baseUrl:"",getToken:go});function Nb({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[p,m]=o.useState(!1),f=async()=>{a(!0),u("");try{const A=await(await Ut("/auth/session")).json();r(A)}catch(w){u(w instanceof Error?w.message:String(w))}finally{a(!1)}};o.useEffect(()=>{f()},[]),o.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let w=!1;return(async()=>{try{const A=await Ut("/api/v1/standalone/preferences");if(!A.ok)return;const d=await A.json();if(w)return;const b=Vt(d.standaloneFontPreferences);ms(b),Ma(b)}catch{}})(),()=>{w=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const g=async w=>{w.preventDefault(),m(!0),u("");try{const A=await Ut("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),d=await A.json();if(!A.ok)throw new Error((d==null?void 0:d.error)||"Login failed");r(d),c(""),Rl()}catch(A){u(A instanceof Error?A.message:String(A))}finally{m(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[t.jsx("input",{type:"password",value:i,onChange:w=>c(w.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),t.jsx("button",{type:"submit",disabled:p||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:p?"Signing in…":"Unlock dashboard"})]}):t.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&t.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):t.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function Ei(){const{ides:e,initialLoaded:s}=js();if(!s)return t.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?t.jsx(pa,{to:`/machines/${r.id}`,replace:!0}):t.jsx(pa,{to:"/dashboard",replace:!0})}function Cb(){const e=o.useMemo(()=>({sendCommand:rn,sendData:Aa}),[]);return t.jsx(xd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Ad,{client:Sb,children:t.jsx(Nb,{children:t.jsx(db,{children:t.jsx(Td,{value:e,children:t.jsx(bb,{children:t.jsxs(bd,{children:[t.jsx(cs,{path:"/dashboard",element:t.jsx(Nx,{})}),t.jsx(cs,{path:"/machine",element:t.jsx(Ei,{})}),t.jsx(cs,{path:"/machines/:id",element:t.jsx(eb,{})}),t.jsx(cs,{path:"/machines",element:t.jsx(Ei,{})}),t.jsx(cs,{path:"/about",element:t.jsx(wb,{})}),t.jsx(cs,{path:"/settings",element:t.jsx(kb,{})}),t.jsx(cs,{path:"*",element:t.jsx(pa,{to:"/dashboard",replace:!0})})]})})})})})})})}Jm({connectionManager:Yt});gd(document.getElementById("root")).render(t.jsx(Cb,{}));
|
|
79
|
+
`})]})}function go(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function ab(e){if(typeof window>"u")return e;const s=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=go();return r&&!s.searchParams.has("token")&&s.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?s.toString():`${s.pathname}${s.search}${s.hash}`}async function Ut(e,s){return await fetch(ab(e),{credentials:"same-origin",...s})}function Pl(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class ob{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1){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 Ut(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const a=await n.json();this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof a.seq=="number"?a.seq:0,text:typeof a.text=="string"?a.text:"",truncated:!!a.truncated,cols:typeof a.cols=="number"?a.cols:void 0,rows:typeof a.rows=="number"?a.rows:void 0})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Yt=new ob;function ib(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=go();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Xr=ib(),Di=3e3,cb=3e4;let zt=null,lb=0;const xn=new Map;let ds=null,mr=null;function Ei(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function rr(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function db(e){return e==="connected"?"connected":e}async function rn(e,s,r){const n=Tp(e,r||{}),a=zt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++lb}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{xn.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);xn.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 Aa(e,s){const r=zt;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class ub{constructor(s){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(zt==null?void 0:zt.readyState)===WebSocket.OPEN}get connectionState(){return(zt==null?void 0:zt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return rn(this.daemonId,s,r)}async sendInput(s,r){return rn(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,ds&&(clearInterval(ds),ds=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await rn(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Yt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ds=setInterval(r,2e3)}stopScreenshots(s){ds&&(clearInterval(ds),ds=null)}}let Kt=null;function mb(e){return(!Kt||Kt.daemonId!==e)&&(Kt=new ub(e)),Kt}function pb({children:e}){const s=o.useRef(cn()),r=cn();s.current=r;const{setUserName:n}=js(),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),mr==null||mr(d,b)},[]),p=o.useRef(null),m=o.useRef(),f=o.useRef(Di),g=o.useRef(!0),w=o.useRef(!1),A=o.useRef("initial_connect");return o.useEffect(()=>{g.current=!0,w.current=!1;function d(){var h,S;if(!g.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((S=p.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Xr}...`),rr("connect_attempt",{url:Xr,reason:A.current,delayMs:f.current});let y;try{y=new WebSocket(Xr)}catch(_){console.error("[Standalone WS] Failed to create WebSocket:",_),b();return}p.current=y,y.onopen=()=>{if(!g.current){y.close();return}u("connected"),f.current=Di,rr("open",{url:Xr,reason:A.current}),os.resubscribeAll({sendData:Aa}),console.log("[Standalone WS] Connected")},zt=y,y.onmessage=_=>{var k,I;try{const j=JSON.parse(_.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const v=xn.get(j.requestId);v&&(xn.delete(j.requestId),j.type==="error"?v.reject(new Error(((k=j.data)==null?void 0:k.message)||"Command failed")):v.resolve(j.data));return}if(j.type==="session_output"){const v=j.sessionId||j.cliId||j.cliType;v&&Yt.emitSessionOutput(v,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Yt.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 v=j.update;v&&os.publish(v);return}if(j.type==="status"||j.type==="initial_state"){const v=j.data;if(!v)return;const{injectEntries:x,markLoaded:E,getIdes:L}=s.current,M=v.instanceId||"standalone",T=L().find(C=>C.id===M),B=mb(M);Yt.register(M,B),Yt.setState(M,"connected"),u("connected",M),Yt.emitStatus(M,v);const H=un(v,{daemonId:M,existingDaemon:T,existingEntries:L()});Ei("ws_status",{type:j.type,daemonId:M,sessions:(v.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(v.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Ei("entries",{daemonId:M,entries:H.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),H.length>0&&x(H,{authoritativeDaemonIds:[M]}),E(),c.current!==M&&((I=i.current)==null||I.call(i),c.current=M,i.current=os.subscribe({sendData:Aa},M,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${M}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const R=s.current.getIdes(),U=R.find(D=>D.id===M),N=un(C.status,{daemonId:M,existingDaemon:U,existingEntries:R,timestamp:C.timestamp});N.length>0&&s.current.injectEntries(N),C.userName&&a.current&&a.current(C.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},y.onclose=_=>{g.current&&(Kt==null||Kt.stopScreenshots(),Kt&&Yt.setState(Kt.daemonId,"disconnected"),u("disconnected"),p.current=null,A.current=`close:${_.code}${_.wasClean?":clean":":unclean"}`,rr("close",{code:_.code,reason:_.reason||"",wasClean:_.wasClean}),b())},y.onerror=_=>{w.current||!g.current||(A.current="error",rr("error",{message:_ instanceof Event?"event":String(_),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",_))}}function b(){if(!g.current)return;clearTimeout(m.current);const y=f.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),rr("schedule_reconnect",{reason:A.current,delayMs:y}),m.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,cb),d()},y)}return d(),()=>{var y;g.current=!1,w.current=!0,(y=i.current)==null||y.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,zt=null),Kt&&(Kt.stopScreenshots(),Yt.unregister(Kt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function fb({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(mr=(c,l)=>{r(c),l&&a(l)},()=>{mr=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=db(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(Cd,{connectionOverrides:i,children:t.jsx(pb,{children:e})})}const Dl="adhdev_standalone_font_preferences",ws={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Tn=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],vr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],hb=new Set(Tn.map(e=>e.id)),xb=new Set(vr.map(e=>e.id));function Vt(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:nn("chat",s.chat),code:nn("code",s.code),terminal:nn("terminal",s.terminal)}}function nn(e,s){const r=ws[e],n=s&&typeof s=="object"&&!Array.isArray(s)?s:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?hb:xb).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function an(e,s){var a;const r=nn(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Tn:vr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function bb(e){const s=Vt(e),r=an("chat",s.chat),n=an("code",s.code),a=an("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ms(e,s=document.documentElement){const r=Vt(e),n=bb(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))s.style.setProperty(a,i);return r}function Ma(e){const s=Vt(e);try{localStorage.setItem(Dl,JSON.stringify(s))}catch{}return s}function gb(){try{const e=localStorage.getItem(Dl);if(e)return Vt(JSON.parse(e))}catch{}return ws}function yb(){return ms(gb())}function nr(e,s){var n;const r=e==="chat"?Tn:vr;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const vb=[{id:"dashboard",path:"/dashboard",icon:t.jsx(zi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Qt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(bn,{}),label:"Settings"}];function wb({children:e}){const s=Vs(),r=_a(),[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(At,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:vb.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(Vi,{})}),!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(Gi,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.88"]}),t.jsx(Hp,{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 jb=[{icon:t.jsx(Qt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Zt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(qi,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Rt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(fr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Vi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],kb=[{icon:t.jsx(Hd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(zi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(yn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Dd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(Pa,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx($d,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Sb=[{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 Nb(){return t.jsxs(zc,{icon:t.jsx(Gi,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.8.88"]}),children:[t.jsx(Lt,{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(Lt,{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:jb.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(Lt,{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:Hc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Uc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Fc.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(Lt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:kb.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:e.icon}),e.title]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(Lt,{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:Sb.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(Vc,{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(Qd,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function la(e,s,r){return{...e,[s]:r}}function da({surface:e,title:s,description:r,value:n,options:a,onChange:i}){return t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:s}),t.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>t.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",t.jsx("span",{className:"font-mono break-all",children:an(e,n)})]})]})]})}function Cb({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const p=JSON.stringify(e)!==JSON.stringify(s);return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&t.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&t.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),t.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[t.jsx(da,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Tn,onChange:m=>i(la(e,"chat",m))}),t.jsx(da,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:vr,onChange:m=>i(la(e,"code",m))}),t.jsx(da,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:vr,onChange:m=>i(la(e,"terminal",m))})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),t.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",nr("chat",e.chat.preset)," · Code: ",nr("code",e.code.preset)," · Terminal: ",nr("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",nr("chat",ws.chat.preset)," / ",nr("code",ws.code.preset)]})]}),t.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:t.jsxs("div",{className:"chat-container-content",children:[t.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:t.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[t.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[t.jsx("span",{className:"chat-sender",children:"Hermes"}),t.jsx("span",{className:"chat-time",children:"now"})]}),t.jsxs("div",{className:"chat-markdown",children:[t.jsxs("p",{children:["Readable prose, ",t.jsx("strong",{children:"bold text"}),", and ",t.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),t.jsx("pre",{children:t.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),t.jsxs("div",{className:"chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"▸"}),t.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),t.jsxs("div",{className:"chat-msg-terminal",children:[t.jsx("div",{className:"chat-msg-header",children:"Terminal"}),t.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:c,disabled:r||!p,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),t.jsx("button",{type:"button",onClick:l,disabled:r||!p,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),t.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function Ib(){const{ides:e}=js(),s=e.find(J=>J.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Pt(),{userName:a}=js(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[p,m]=o.useState(null),[f,g]=o.useState(ws),[w,A]=o.useState(!1),[d,b]=o.useState(""),[y,h]=o.useState(""),[S,_]=o.useState("127.0.0.1"),[k,I]=o.useState(""),[j,v]=o.useState(""),[x,E]=o.useState(""),[L,M]=o.useState(""),[T,B]=o.useState(""),[H,C]=o.useState(!1),R=async()=>{const Z=await(await Ut("/auth/session")).json();u(Z)},U=async()=>{const Z=await(await Ut("/api/v1/standalone/preferences")).json();m(Z),_(Z.standaloneBindHost);const ue=Vt(Z.standaloneFontPreferences);g(ue),ms(ue),Ma(ue)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([R(),U()]).catch(J=>{M(J instanceof Error?J.message:String(J))})},[]),o.useEffect(()=>{ms(f)},[f]);const N=J=>{const Z=J.target.value.trim();s!=null&&s.id&&Z!==a&&n(s.id,"set_user_name",{userName:Z}).catch(console.error)},[D,Y]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),q=J=>{Y(J);try{localStorage.setItem("adhdev_sound",J?"1":"0")}catch{}},W=async()=>{b(""),h(""),A(!0);try{const J=Vt(f),Z=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:J})}),ue=await Z.json();if(!Z.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to save standalone font preferences");const de=Vt(ue.standaloneFontPreferences);m(ue),g(de),ms(de),Ma(de),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(J){b(J instanceof Error?J.message:String(J))}finally{A(!1)}},ae=()=>{const J=Vt(p==null?void 0:p.standaloneFontPreferences);b(""),h(""),g(J),ms(J)},ce=()=>{b(""),h(""),g(ws),ms(ws)},Se=async()=>{M(""),B(""),C(!0);try{const J=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:S})}),Z=await J.json();if(!J.ok)throw new Error((Z==null?void 0:Z.error)||"Failed to save standalone network preference");m(Z),_(Z.standaloneBindHost),B(Z.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(J){M(J instanceof Error?J.message:String(J))}finally{C(!1)}},X=async()=>{if(M(""),B(""),j.trim().length<4){M("Password must be at least 4 characters.");return}if(j!==x){M("New password and confirmation do not match.");return}C(!0);try{const J=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:j})}),Z=await J.json();if(!J.ok)throw new Error((Z==null?void 0:Z.error)||"Failed to save password");u(Z),await U(),I(""),v(""),E(""),B(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Pl()}catch(J){M(J instanceof Error?J.message:String(J))}finally{C(!1)}},he=async()=>{M(""),B(""),C(!0);try{const J=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),Z=await J.json();if(!J.ok)throw new Error((Z==null?void 0:Z.error)||"Failed to clear password");u(Z),await U(),I(""),v(""),E(""),B("Standalone password disabled.")}catch(J){M(J instanceof Error?J.message:String(J))}finally{C(!1)}};return t.jsxs(zc,{icon:t.jsx(bn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Br,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&t.jsx(Br,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),t.jsx(Lt,{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.88"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(p==null?void 0:p.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(Lt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="127.0.0.1",onChange:()=>_("127.0.0.1")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="0.0.0.0",onChange:()=>_("0.0.0.0")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:()=>{Se()},disabled:H,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:H?"Saving…":"Save default network mode"}),t.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(p==null?void 0:p.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Lt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),L&&t.jsx(Br,{variant:"error",children:L}),T&&t.jsx(Br,{variant:"success",children:T}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:k,onChange:J=>I(J.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:j,onChange:J=>v(J.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:x,onChange:J=>E(J.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{X()},disabled:H,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:H?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{he()},disabled:H,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),t.jsx(Lt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(J=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${J.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:J.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:J.type})]},J.type))})}),t.jsx(Lt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Vp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Lt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(Xp,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"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(nf,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),t.jsx(Cb,{value:f,savedValue:Vt(p==null?void 0:p.standaloneFontPreferences),saving:w,error:d,notice:y,onChange:g,onSave:()=>{W()},onResetToSaved:ae,onResetToDefaults:ce})]}),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(cf,{})]})]})}),t.jsx(Lt,{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(Fp,{}),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Jd,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:D,onChange:q})]})}),t.jsx(Lt,{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(Pd,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:J=>c(J.target.value),onBlur:N,onKeyDown:J=>{J.key==="Enter"&&J.currentTarget.blur()}})]})})})]})}Wp();sf();yb();const Ab=Hi({baseUrl:"",getToken:go});function Mb({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[p,m]=o.useState(!1),f=async()=>{a(!0),u("");try{const A=await(await Ut("/auth/session")).json();r(A)}catch(w){u(w instanceof Error?w.message:String(w))}finally{a(!1)}};o.useEffect(()=>{f()},[]),o.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let w=!1;return(async()=>{try{const A=await Ut("/api/v1/standalone/preferences");if(!A.ok)return;const d=await A.json();if(w)return;const b=Vt(d.standaloneFontPreferences);ms(b),Ma(b)}catch{}})(),()=>{w=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const g=async w=>{w.preventDefault(),m(!0),u("");try{const A=await Ut("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),d=await A.json();if(!A.ok)throw new Error((d==null?void 0:d.error)||"Login failed");r(d),c(""),Pl()}catch(A){u(A instanceof Error?A.message:String(A))}finally{m(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[t.jsx("input",{type:"password",value:i,onChange:w=>c(w.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),t.jsx("button",{type:"submit",disabled:p||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:p?"Signing in…":"Unlock dashboard"})]}):t.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&t.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):t.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function $i(){const{ides:e,initialLoaded:s}=js();if(!s)return t.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?t.jsx(pa,{to:`/machines/${r.id}`,replace:!0}):t.jsx(pa,{to:"/dashboard",replace:!0})}function Tb(){const e=o.useMemo(()=>({sendCommand:rn,sendData:Aa}),[]);return t.jsx(bd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Md,{client:Ab,children:t.jsx(Mb,{children:t.jsx(fb,{children:t.jsx(Ld,{value:e,children:t.jsx(wb,{children:t.jsxs(gd,{children:[t.jsx(cs,{path:"/dashboard",element:t.jsx(Mx,{})}),t.jsx(cs,{path:"/machine",element:t.jsx($i,{})}),t.jsx(cs,{path:"/machines/:id",element:t.jsx(nb,{})}),t.jsx(cs,{path:"/machines",element:t.jsx($i,{})}),t.jsx(cs,{path:"/about",element:t.jsx(Nb,{})}),t.jsx(cs,{path:"/settings",element:t.jsx(Ib,{})}),t.jsx(cs,{path:"*",element:t.jsx(pa,{to:"/dashboard",replace:!0})})]})})})})})})})}sp({connectionManager:Yt});yd(document.getElementById("root")).render(t.jsx(Tb,{}));
|