@adhdev/daemon-standalone 0.8.69 → 0.8.70

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.
@@ -0,0 +1,72 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-fZXg9GuG.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var $c=Object.defineProperty;var Bc=(e,s,r)=>s in e?$c(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Ye=(e,s,r)=>Bc(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as zn,a as Vn,b as Po,c as Do,u as Ls,R as nt,d as qs,t as Kc,e as Wc,D as Oc,f as Tn,g as Mn,h as Gn,i as Hc,k as Uc,B as Fc,l as zc,m as Qt,N as Ln,n as Vc}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 Gc(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=Gc();function La(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}}const Eo=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}),$o=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function _a(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 Ra(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);if(!a)return n;const i=n.providerName&&n.providerName!==n.providerType?n.providerName:void 0;return{...a,...n,providerName:i??a.providerName??n.providerName??n.providerType,title:n.title??a.title??n.providerName??a.providerName??n.providerType,workspace:n.workspace??a.workspace??null,activeChat:n.activeChat??a.activeChat??null,capabilities:n.capabilities??a.capabilities??[],cdpConnected:n.cdpConnected??a.cdpConnected,summaryMetadata:n.summaryMetadata??a.summaryMetadata,controlValues:n.controlValues??a.controlValues,providerControls:n.providerControls??a.providerControls,unread:n.unread??a.unread,lastSeenAt:n.lastSeenAt??a.lastSeenAt,inboxBucket:n.inboxBucket??a.inboxBucket,surfaceHidden:n.surfaceHidden??a.surfaceHidden,lastUpdated:n.lastUpdated??a.lastUpdated,lastMessagePreview:n.lastMessagePreview??a.lastMessagePreview,lastMessageRole:n.lastMessageRole??a.lastMessageRole,lastMessageAt:n.lastMessageAt??a.lastMessageAt,lastMessageHash:n.lastMessageHash??a.lastMessageHash}})}function tn(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 Mr(e){return Array.isArray(e)?e.map(Mr):!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,Mr(r)]))}function qc(e,s){try{return JSON.stringify(Mr(e))===JSON.stringify(Mr(s))}catch{return!1}}function ar(e,s,r){return qc(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function Yc(e,s,r){var u,p,m,f,w,S,T;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(d=>({...d,_lastUpdate:n}));const i=new Map;for(const d of s)i.set(d.id,d);for(const d of e){const b=i.get(d.id);if(!b){i.set(d.id,{...d,_lastUpdate:n});continue}const y=_a(d),h=_a(b);if(y>h){const C=(u=d.chats)!=null&&u.length?d.chats:b.chats,P=Ra(b.childSessions,d.childSessions),v=tn(b,d,{...b,...d,chats:C,childSessions:P,_lastUpdate:n});i.set(d.id,ar(b,v,n))}else if(y<h){const C={};if(d.status&&d.status!==b.status&&(C.status=d.status),d.cdpConnected!==void 0&&(C.cdpConnected=d.cdpConnected),(p=d.chats)!=null&&p.length&&!((m=b.chats)!=null&&m.length)&&(C.chats=d.chats),d.machineNickname!==void 0&&d.machineNickname!==b.machineNickname&&(C.machineNickname=d.machineNickname),d.version!==void 0&&(C.version=d.version),d.serverVersion!==void 0&&(C.serverVersion=d.serverVersion),d.versionMismatch===!0&&(C.versionMismatch=!0),Object.keys(C).length>0){const P=tn(b,d,{...b,...C,_lastUpdate:b._lastUpdate});i.set(d.id,ar(b,P,n))}else ar(b,{...b,_lastUpdate:b._lastUpdate},n)}else{const C=d.timestamp||n,P=b._lastUpdate||b.timestamp||0;if(C>=P){const v=(f=d.chats)!=null&&f.length?d.chats:b.chats,j=Ra(b.childSessions,d.childSessions),k=tn(b,d,{...b,...d,chats:v,childSessions:j,_lastUpdate:n});i.set(d.id,ar(b,k,n))}else(w=d.chats)!=null&&w.length&&!((S=b.chats)!=null&&S.length)&&i.set(d.id,{...b,chats:d.chats})}}const c=new Set(e.map(d=>d.id)),l=new Set;for(const d of e){const b=d.daemonId||((T=d.id)==null?void 0:T.split(":")[0]);b&&l.add(b)}for(const[d,b]of i){const 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 Xc(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 Qc({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(C=>{let P=!1;const v=C.map(j=>j.id!==y||j.chats===h?j:(P=!0,{...j,chats:h}));return P?v:C})},[]),w=o.useCallback((y,h)=>{n(C=>{const P=C.length===0?y:Yc(y,C,h),v=!Xc(C,P);return v&&ks.record({kind:"dashboard.entries_applied",payload:{incoming:La(y),next:La(P)}}),v?P:C})},[]),S=o.useCallback(()=>i(!0),[]),T=o.useMemo(()=>({injectEntries:w,markLoaded:S,getIdes:()=>m.current}),[w,S]),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($o.Provider,{value:T,children:t.jsx(Eo.Provider,{value:b,children:e})})}function cs(){return o.useContext(Eo)}function Lr(){return o.useContext($o)}function Bo(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${s}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),p=a(l),m=l.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return u&&m.searchParams.set("token",u),!l.startsWith("http")&&!s?`${m.pathname}${m.search}${m.hash}`:m.toString()}async function c(l,u={}){const p={"Content-Type":"application/json",...u.headers||{}},m=r==null?void 0:r();m&&(p.Authorization=`Bearer ${m}`);const f=a(l),w=new AbortController,S=setTimeout(()=>w.abort(),15e3);try{const T=await fetch(f,{...u,headers:p,signal:w.signal});if(T.status===401)throw n==null||n(),new Error("Unauthorized");if(!T.ok){const d=await T.json().catch(()=>({error:T.statusText}));throw new Error(d.error||`API Error: ${T.status}`)}return T.json()}finally{clearTimeout(S)}}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 Jc=Bo({baseUrl:"http://localhost:3847"}),Zc=o.createContext(Jc);function el({client:e,children:s}){return t.jsx(Zc.Provider,{value:e,children:s})}const tl={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Ko=o.createContext(tl);function sl({value:e,children:s}){return t.jsx(Ko.Provider,{value:e,children:s})}function Tt(){return o.useContext(Ko)}const He={size:18};function Wo({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 qn({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 Ot({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 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:"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 rl({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 nl({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 Oo({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 al({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 Or({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 Ho({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 ol({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 Ht({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 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.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 Xn({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 il({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 Ss({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 _s({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 ls({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 Ys({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 Uo({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 Fo({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 zo({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 cl({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 Hr({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 ll({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 Qn({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 dl({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 St({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 ul({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 ml({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 pl({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 fl({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 Ur({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 hl({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 xl({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 bl({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 gl({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 yl({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 vl({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 wl({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 jl({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 kl({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 Sl({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 Nl({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 Cl({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 Pa(e){return!!e&&typeof e=="object"&&"text"in e}function Jn(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:Pa(i)?String(i.text||""):"").join(r):Pa(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Ns(e){return Jn(e,{normalizeWhitespace:!0})}const sn=new Map;function Vo(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Il(e,s,r){return Number(e.receivedAt||r[ys(e,s)]||0)||0}function Go(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Al(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function or(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 rn(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 Da(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):Go(e)?t.jsx(zn,{remarkPlugins:[Vn,Po,Do],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function ir({parts:e,renderAsPreformatted:s}){return t.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return t.jsx("div",{children:Da(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=rn(r);return a?t.jsx("img",{src:a,alt:or(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=rn(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=rn(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:or(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||or(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=or(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}),Da(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 ys(e,s){const r=e,n=Jn(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 Tl=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(zn,{remarkPlugins:[Vn],children:s.text}),t.jsx("span",{className:"action-time",children:Vo(s.timestamp)})]})},(e,s)=>e.log===s.log),Ml=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var j,k,g;const u=(s.role||"").toLowerCase(),p=u==="user"||u==="human",m=s.kind||(u==="tool"?"tool":"standard"),f=Al(s.content)?s.content:null,w=!!(f!=null&&f.some(x=>x.type!=="text")),S=Jn(s.content,{joiner:`
4
+ `});if(m==="thought"){const x=typeof((j=s.meta)==null?void 0:j.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(pl,{size:13}),t.jsx("span",{children:x})]}),t.jsx("div",{className:"chat-msg-body",children:S})]})}if(m==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),w&&f?t.jsx("div",{className:"tool-text w-full",children:t.jsx(ir,{parts:f,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:S})]});if(m==="terminal"){const x=(k=s.meta)!=null&&k.isRunning?"⏳":"✅",$=typeof((g=s.meta)==null?void 0:g.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:x}),t.jsx("span",{children:$})]}),w&&f?t.jsx("div",{className:"chat-msg-body",children:t.jsx(ir,{parts:f,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:S})]})}if(m==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:w&&f?t.jsx(ir,{parts:f,renderAsPreformatted:!1}):S.slice(0,100)});const T=s.meta,b=(typeof(T==null?void 0:T.renderMode)=="string"?T.renderMode.trim():"")==="preformatted",y=S,h=!1,C=y,P=b,v=!P&&Go(C);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${p?"self-end":"self-start"}`,children:(y||w||p)&&t.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${y||w?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:p?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:Vo(r)})]}),(y||w)&&t.jsx("div",{className:"chat-markdown",children:w&&f?t.jsx(ir,{parts:f,renderAsPreformatted:P}):P?t.jsx("pre",{className:"chat-preformatted",children:C}):v?t.jsx(zn,{remarkPlugins:[Vn,Po,Do],children:C}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:C})}),h]})})},(e,s)=>e.message===s.message&&e.receivedAt===s.receivedAt&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isTextExpanded===s.isTextExpanded),Ll=o.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},emptyState:p,onLoadMore:m,isLoadingMore:f,hasMoreHistory:w,hiddenLiveCount:S=0,loadError:T,scrollToBottomRequestNonce:d},b){var Ie;const y=o.useRef(null),h=o.useRef(null),C=o.useRef(null),P=o.useRef(0),v=o.useRef(""),j=o.useRef(!1),k=o.useRef(null),g=o.useRef(!1),x=o.useRef(null),$=o.useRef(!1),[A,M]=o.useState(new Set),L=o.useRef(!1),O=o.useRef(!1),R=()=>{const te=y.current;return te?te.scrollHeight-te.scrollTop-te.clientHeight<200:!0},N=o.useCallback((te="auto")=>{const de=y.current;de&&de.scrollTo({top:de.scrollHeight,behavior:te})},[]),U=o.useCallback(()=>{const te=y.current;!te||!l||sn.set(l,{top:te.scrollTop,fromBottom:Math.max(0,te.scrollHeight-te.scrollTop-te.clientHeight)})},[l]),G=o.useCallback(()=>{var oe;const te=y.current,de=(oe=window.getSelection)==null?void 0:oe.call(window);if(!te||!de||de.rangeCount===0||de.isCollapsed){$.current=!1;return}const ae=de.anchorNode,ge=de.focusNode;$.current=!!(ae&&ge&&te.contains(ae)&&te.contains(ge))},[]),I=o.useCallback((te="auto")=>{k.current!=null&&cancelAnimationFrame(k.current),k.current=requestAnimationFrame(()=>{k.current=null,N(te)})},[N]),B=s.length>0?`${s.length}:${(((Ie=s[s.length-1])==null?void 0:Ie.content)||"").length}`:"0:0";o.useEffect(()=>{const te=!j.current,de=v.current!==l;if(v.current=l,te||de){if(j.current=!0,L.current=!1,g.current=!0,!$.current){const ge=l?sn.get(l):null;ge?requestAnimationFrame(()=>{const oe=y.current;if(!oe)return;const F=Math.max(0,oe.scrollHeight-oe.clientHeight-ge.fromBottom);oe.scrollTop=Number.isFinite(F)?F:ge.top,O.current=!0}):I("auto")}P.current=s.length;return}s.length>P.current?!L.current&&!$.current&&I("auto"):R()&&!L.current&&!$.current&&I("auto"),P.current=s.length},[B,l,c,s.length,I]),o.useEffect(()=>{d&&(L.current=!1,g.current=!0,O.current=!0,x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{g.current=!1,x.current=null},180),$.current||I("auto"))},[I,d]),o.useEffect(()=>()=>{U(),k.current!=null&&cancelAnimationFrame(k.current),x.current!=null&&window.clearTimeout(x.current)},[U]),o.useEffect(()=>{const te=h.current;if(!te)return;const de=()=>{x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{g.current=!1,x.current=null},180)},ae=new ResizeObserver(()=>{g.current&&($.current||(I("auto"),de()))});return ae.observe(te),()=>{ae.disconnect(),x.current!=null&&(window.clearTimeout(x.current),x.current=null)}},[I,l]),o.useImperativeHandle(b,()=>({scrollToBottom:(te="smooth")=>{N(te)}}),[N]),o.useEffect(()=>{const te=y.current;if(!te)return;let de;const ae=()=>{clearTimeout(de),de=setTimeout(()=>{L.current=!R(),U()},50)};return te.addEventListener("scroll",ae,{passive:!0}),()=>{te.removeEventListener("scroll",ae),clearTimeout(de)}},[U]),o.useEffect(()=>(document.addEventListener("selectionchange",G),()=>document.removeEventListener("selectionchange",G)),[G]);const D=o.useRef(0),W=o.useRef(!1);o.useEffect(()=>{const te=y.current;if(!te||!W.current||D.current===0)return;const de=te.scrollHeight-D.current;de>0&&(te.scrollTop=de),U(),D.current=0,W.current=!1},[s.length,U]),o.useEffect(()=>{if(O.current||!l)return;const te=sn.get(l),de=y.current;if(!te||!de)return;const ae=Math.max(0,de.scrollHeight-de.clientHeight-te.fromBottom);de.scrollTop=Number.isFinite(ae)?ae:te.top,O.current=!0},[l,s.length]);const X=()=>{const te=y.current;te&&(D.current=te.scrollHeight),W.current=!0,m==null||m()},we=o.useMemo(()=>{const te=s.map((oe,F)=>({type:"message",data:oe,index:F,ts:Il(oe,F,u)}));if(!r||r.length===0)return te;const de=[...r].sort((oe,F)=>oe.timestamp-F.timestamp).map((oe,F)=>({type:"action",data:oe,index:F,ts:oe.timestamp})),ae=[];let ge=0;for(const oe of te){for(;ge<de.length&&oe.ts>0&&de[ge].ts<oe.ts;)ae.push(de[ge++]);ae.push(oe)}for(;ge<de.length;)ae.push(de[ge++]);return ae},[s,r,u]),Le=S>0||!!w,ie=S>0?`↑ Show ${Math.min(S,80)} earlier messages${S>80?` (${S} hidden)`:""}`:T?`↻ ${T}`:"↑ 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..."}),Le&&!f&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:X,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${T&&S===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:ie})}),we.length===0&&!Le&&(p||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),we.map(te=>{if(te.type==="action"){const se=te.data;return t.jsx(Tl,{log:se},`action-${te.index}`)}const de=te.data,ae=te.index,ge=ys(de,ae),oe=de.receivedAt||u[ge],F=`${l}-${ge}`,xe=A.has(F);return t.jsx(Ml,{message:de,receivedAt:oe,agentName:n,userName:a,isCliMode:i,isTextExpanded:xe,onToggleTextExpanded:()=>M(se=>{const pe=new Set(se);return xe?pe.delete(F):pe.add(F),pe})},`msg-${ge}`)}),c&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:C})]})})}),_l=o.memo(Ll,(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),Rl="modulepreload",Pl=function(e){return"/"+e},Ea={},Dl=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=Pl(u),u in Ea)return;Ea[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":Rl,p||(f.as="script"),f.crossOrigin="",f.href=u,l&&f.setAttribute("nonce",l),document.head.appendChild(f),p)return new Promise((w,S)=>{f.addEventListener("load",w),f.addEventListener("error",()=>S(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 $a=!1;const qo=o.forwardRef(({onInput:e,onResize:s,fontSize:r=13,readOnly:n=!1},a)=>{const i=o.useRef(null),[c,l]=o.useState(null),u=o.useRef([]),p=o.useRef(!1),m=o.useRef(!1),f=o.useRef(!1),w=()=>{const S=i.current;if(S){p.current&&(S.clear(),p.current=!1);for(const T of u.current)S.write(T);u.current=[],m.current&&(S.fit(),m.current=!1),f.current&&(S.bumpResize(),f.current=!1)}};return o.useImperativeHandle(a,()=>({write:S=>{i.current?i.current.write(S):u.current.push(S)},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:(S,T)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(S,T)},fit:()=>{i.current?i.current.fit():m.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():f.current=!0}}),[]),o.useEffect(()=>{if(!c)return;const S=requestAnimationFrame(()=>{w()});return()=>cancelAnimationFrame(S)},[c]),o.useEffect(()=>{let S=!1;return Dl(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(T=>{$a||($a=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),S||l(()=>T.GhosttyTerminalView)}).catch(T=>{console.error("[CliTerminal] failed to load terminal renderer",T)}),()=>{S=!0}},[]),c?t.jsx(c,{ref:i,onInput:e,onResize:s,fontSize:r,readOnly:n,className:"w-full h-full rounded-lg overflow-hidden"}):t.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});qo.displayName="CliTerminal";function cr({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 Ba({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 El({cursorPos:e,viewportRef:s,imgRef:r}){var h;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(h=s.current)==null?void 0:h.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,u=c/l,p=a.width/a.height;let m,f,w,S;u>p?(m=a.width,f=a.width/u,w=0,S=(a.height-f)/2):(f=a.height,m=a.height*u,w=(a.width-m)/2,S=0);const T=a.left-i.left+w+m*e.nx,d=a.top-i.top+S+f*e.ny,b=Math.max(8,Math.min(i.width-8,T)),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 $l({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:p,zoom:m,isMobile:f,mobileFillZoom:w,onZoomOut:S,onZoomReset:T,onZoomIn:d,transportType:b,screenshotUsage:y,lastActionStatus:h}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:C=>C.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[t.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[t.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),t.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("div",{onClick:()=>{n(C=>!C),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&t.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:t.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:C=>C.stopPropagation(),onChange:C=>l(C.target.value),onKeyDown:C=>{u(C)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),t.jsx("div",{className:"relative",children:t.jsx("div",{onClick:()=>{i(C=>!C),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⚙️"})})}),t.jsx("div",{className:"w-px h-[18px] bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:p?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:p?"Connected":"WS"})]}),m>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(m*100),"%"]}),b==="direct"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),b==="relay"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),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:C=>C.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",m<=(f?w:1)+.01?f?"FILL":"FIT":`${Math.round(m*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:C=>{C.stopPropagation(),S()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),t.jsx("button",{onClick:C=>{C.stopPropagation(),T()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:f?"FILL":"FIT"}),t.jsx("button",{onClick:C=>{C.stopPropagation(),d()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Bl({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 Kl(){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 Ka(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 Zs(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!Kl())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,Ka(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,Ka(s[c])]))}),r.current=s})}function Wl({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:p,setPanY:m,setZoom:f,lastWheelTimeRef:w,onAction:S,setLastActionStatus:T,spawnRippleFromNormalized:d,clampPan:b,isMobile:y,mobileFillZoom:h}){const[C,P]=o.useState(null),v=o.useRef(null),j=o.useRef(null),k=o.useRef(null),g=o.useRef(!1),x=o.useRef(null),$=o.useRef(0),A=o.useRef(null),M=o.useRef(1),L=o.useRef({x:0,y:0}),O=o.useRef(!1),R=o.useRef(n),N=o.useRef(S),U=30,G=550,I=18,B=60,D=400,W=12,X=()=>{if(v.current)return;const ie={nx:.5,ny:.5};v.current=ie,P(ie)};return o.useEffect(()=>{R.current=n,n==="mouse"&&X()},[n]),o.useEffect(()=>{N.current=S},[S]),o.useEffect(()=>{const ie=e.current;if(!ie)return;const Ie=F=>{if(!r.current)return null;const xe=r.current.getBoundingClientRect();return!xe.width||!xe.height?null:{nx:Math.max(0,Math.min(1,(F.clientX-xe.left)/xe.width)),ny:Math.max(0,Math.min(1,(F.clientY-xe.top)/xe.height))}},te=(F,xe)=>{if(!r.current)return{dnx:0,dny:0};const se=r.current,pe=se.getBoundingClientRect(),Z=se.naturalWidth||pe.width,le=se.naturalHeight||pe.height,ne=Z/le,be=pe.width/pe.height;let me,E;return ne>be?(me=pe.width,E=pe.width/ne):(E=pe.height,me=pe.height*ne),{dnx:F/me,dny:xe/E}},de=(F,xe,se)=>{if(se<=1.05)return;const pe=-(F-.5)*100,Z=-(xe-.5)*100,le=b(pe,Z,se);(Math.abs(le.x-l.current)>.1||Math.abs(le.y-u.current)>.1)&&(p(le.x),m(le.y),l.current=le.x,u.current=le.y)},ae=F=>{const xe=s.current;if(xe&&F.target instanceof Node&&xe.contains(F.target))F.preventDefault();else return;if(F.touches.length===1){const se=F.touches[0];j.current={x:se.clientX,y:se.clientY,time:Date.now()},k.current={x:se.clientX,y:se.clientY},O.current||(g.current=!1),x.current=setTimeout(()=>{if(!g.current&&!O.current)if(g.current=!0,R.current==="mouse"){const pe=v.current||{nx:.5,ny:.5};T("Right Click"),d(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{})}else{const pe=Ie(se);pe&&(T("Right Click"),d(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{}))}},500);return}if(F.touches.length===2){x.current&&clearTimeout(x.current),g.current=!0,O.current=!0;const se=F.touches[1].clientX-F.touches[0].clientX,pe=F.touches[1].clientY-F.touches[0].clientY;A.current=Math.sqrt(se*se+pe*pe),M.current=c.current,L.current={x:(F.touches[0].clientX+F.touches[1].clientX)/2,y:(F.touches[0].clientY+F.touches[1].clientY)/2}}},ge=F=>{const xe=s.current;if(xe&&F.target instanceof Node&&xe.contains(F.target)&&F.preventDefault(),F.touches.length===1&&k.current){const se=F.touches[0],pe=se.clientX-k.current.x,Z=se.clientY-k.current.y;if(!g.current&&j.current){const le=se.clientX-j.current.x,ne=se.clientY-j.current.y;Math.sqrt(le*le+ne*ne)>8&&(g.current=!0,x.current&&clearTimeout(x.current))}if(g.current)if(R.current==="mouse"){const le=te(pe,Z),ne=v.current||{nx:.5,ny:.5},be=Math.max(0,Math.min(1,ne.nx+le.dnx)),me=Math.max(0,Math.min(1,ne.ny+le.dny));v.current={nx:be,ny:me},P({nx:be,ny:me}),T(`Cursor: ${Math.round(be*100)}%, ${Math.round(me*100)}%`),de(be,me,c.current);const E=Date.now();E-w.current>=30&&(w.current=E,N.current("input_mouseMoved",{nx:be,ny:me}).catch(()=>{}))}else if(c.current>1){const le=s.current;if(le){const ne=le.clientWidth,be=le.clientHeight,me=l.current+pe/ne*100,E=u.current+Z/be*100,ye=b(me,E,c.current);p(ye.x),m(ye.y),l.current=ye.x,u.current=ye.y}}else{const le=Ie(se);if(le){const ne=Date.now();ne-w.current>=40&&(w.current=ne,T("Scroll"),N.current("input_wheel",{nx:le.nx,ny:le.ny,deltaX:Math.round(-pe*2.5),deltaY:Math.round(-Z*2.5)}).catch(()=>{}))}}k.current={x:se.clientX,y:se.clientY};return}if(F.touches.length===2&&A.current!==null){const se=F.touches[1].clientX-F.touches[0].clientX,pe=F.touches[1].clientY-F.touches[0].clientY,le=Math.sqrt(se*se+pe*pe)/A.current,ne=(F.touches[0].clientX+F.touches[1].clientX)/2,be=(F.touches[0].clientY+F.touches[1].clientY)/2,me=ne-L.current.x,E=be-L.current.y,ye=Math.abs(le-1)>.03;if(R.current==="mouse"){if(ye){const he=Math.max(i,Math.min(5,M.current*le));f(he),c.current=he}else if(Math.abs(me)>2||Math.abs(E)>2){const he=v.current||{nx:.5,ny:.5},ke=Date.now();ke-w.current>=30&&(w.current=ke,T("Scroll"),N.current("input_wheel",{nx:he.nx,ny:he.ny,deltaX:Math.round(-me*3),deltaY:Math.round(-E*3)}).catch(()=>{}))}}else{const he=Math.max(i,Math.min(5,M.current*le));f(he),c.current=he;const ke=s.current;if(ke&&he>1){const J=ke.clientWidth,Se=ke.clientHeight,Ue=l.current+me/J*100,De=u.current+E/Se*100,Ge=b(Ue,De,he);p(Ge.x),m(Ge.y),l.current=Ge.x,u.current=Ge.y}}L.current={x:ne,y:be}}},oe=F=>{var xe;if(x.current&&clearTimeout(x.current),A.current=null,F.touches.length===1&&O.current){const se=F.touches[0];j.current={x:se.clientX,y:se.clientY,time:Date.now()},k.current={x:se.clientX,y:se.clientY},g.current=!0;return}if(F.touches.length===0){if(O.current){O.current=!1,g.current=!1;return}if(F.changedTouches.length===1){const se=F.changedTouches[0],pe=Date.now(),Z=pe-(((xe=j.current)==null?void 0:xe.time)||0),le=j.current?se.clientX-j.current.x:0,ne=j.current?se.clientY-j.current.y:0,be=Math.sqrt(le*le+ne*ne);if(R.current==="mouse"){if(Z<U||Z>G||be>I){g.current=!1;return}const me=v.current||Ie(se);me&&(T(`Click: ${Math.round(me.nx*100)}%, ${Math.round(me.ny*100)}%`),d(me.nx,me.ny,"left"),N.current("input_click",{...me}).catch(()=>{}))}else{if(g.current){g.current=!1;return}if(Z<B||Z>D||be>W){g.current=!1;return}const me=Ie(se);if(!me)return;pe-$.current<300?(T("Double tap"),d(me.nx,me.ny,"double"),N.current("input_click",{...me,clickCount:2}).catch(()=>{}),$.current=0):(T(`Tap: ${Math.round(me.nx*100)}%, ${Math.round(me.ny*100)}%`),d(me.nx,me.ny,"left"),N.current("input_click",{...me}).catch(()=>{}),$.current=pe)}}g.current=!1}};return ie.addEventListener("touchstart",ae,{passive:!1}),ie.addEventListener("touchmove",ge,{passive:!1}),ie.addEventListener("touchend",oe,{passive:!1}),()=>{ie.removeEventListener("touchstart",ae),ie.removeEventListener("touchmove",ge),ie.removeEventListener("touchend",oe),x.current&&clearTimeout(x.current)}},[e,s,r,i,c,l,u,p,m,f,w,T,d,b]),{cursorPos:C,cursorPosRef:v,handleToggleInputMode:()=>{a(ie=>{const Ie=ie==="touch"?"mouse":"touch";return Ie==="mouse"&&X(),Ie})},handleZoomReset:()=>{const ie=y?h:1;f(ie),c.current=ie,p(0),m(0),l.current=0,u.current=0}}}function Yo({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[p,m]=o.useState(null),[f,w]=o.useState(""),[,S]=o.useState(!1),[T,d]=o.useState([]),b=o.useRef(0),[y,h]=o.useState(!1),[C,P]=o.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[j,k]=o.useState(v?"mouse":"touch"),[g,x]=o.useState(1),$=o.useRef(!1),[A,M]=o.useState(1),[L,O]=o.useState(0),[R,N]=o.useState(0);Zs("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:j,zoom:A,panX:L,panY:R,isMenuOpen:y,isImeOpen:C});const U=o.useRef(0),G=o.useRef(A),I=o.useRef(L),B=o.useRef(R);o.useEffect(()=>{G.current=A},[A]),o.useEffect(()=>{I.current=L},[L]),o.useEffect(()=>{B.current=R},[R]),o.useEffect(()=>{var Z;(Z=c.current)==null||Z.focus()},[]);const D=r==="connected",W=n,X=D?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",we=D?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!v||$.current||!W)return;const Z=u.current,le=l.current;if(!Z||!le)return;const ne=()=>{const be=le.clientWidth,me=le.clientHeight,E=Z.naturalWidth,ye=Z.naturalHeight;if(!E||!ye||!be||!me)return;const he=Math.min(be/E,me/ye),J=Math.max(be/E,me/ye)/he;J>1.01&&(x(J),M(J),G.current=J),$.current=!0};Z.complete&&Z.naturalWidth?ne():Z.addEventListener("load",ne,{once:!0})},[W,v]);const Le=.5;o.useEffect(()=>{A<=Le&&(O(0),N(0))},[A,Le]);const ie=(Z,le,ne)=>{if(ne<=Le)return{x:0,y:0};const be=(ne-1)/(2*ne)*100,me=(ne-1)/(2*ne)*100;return{x:Math.max(-be,Math.min(be,Z)),y:Math.max(-me,Math.min(me,le))}},Ie=(Z,le)=>{if(!u.current)return null;const ne=u.current.getBoundingClientRect();return!ne.width||!ne.height?null:{nx:Math.max(0,Math.min(1,(Z-ne.left)/ne.width)),ny:Math.max(0,Math.min(1,(le-ne.top)/ne.height))}},te=(Z,le,ne)=>{const be=l.current;if(!be)return;const me=be.getBoundingClientRect(),E=++b.current;d(ye=>[...ye,{id:E,x:Z-me.left,y:le-me.top,type:ne}]),setTimeout(()=>d(ye=>ye.filter(he=>he.id!==E)),600)},de=(Z,le,ne)=>{const be=u.current,me=l.current;if(!be||!me)return;const E=be.getBoundingClientRect(),ye=me.getBoundingClientRect(),he=be.naturalWidth||E.width,ke=be.naturalHeight||E.height,J=he/ke,Se=E.width/E.height;let Ue,De,Ge,Qe;J>Se?(Ue=E.width,De=E.width/J,Ge=0,Qe=(E.height-De)/2):(De=E.height,Ue=E.height*J,Ge=(E.width-Ue)/2,Qe=0);const Ze=E.left-ye.left+Ge+Ue*Z,ut=E.top-ye.top+Qe+De*le,qe=++b.current;d(ht=>[...ht,{id:qe,x:Ze,y:ut,type:ne}]),setTimeout(()=>d(ht=>ht.filter(mt=>mt.id!==qe)),600)},ae=async Z=>{var ne;const le=Ie(Z.clientX,Z.clientY);if(le){m(`Click: ${Math.round(le.nx*100)}%, ${Math.round(le.ny*100)}%`),te(Z.clientX,Z.clientY,"left"),(ne=c.current)==null||ne.focus();try{const be=await e("input_click",{nx:le.nx,ny:le.ny});be!=null&&be.success||s(`❌ Click failed: ${be==null?void 0:be.error}`)}catch(be){s(`❌ Click error: ${be.message||be}`)}}},ge=async(Z,le,ne,be=0)=>{try{await e("input_key",{type:ne?"char":"keyDown",key:Z,code:le,text:ne?Z:void 0,unmodifiedText:ne?Z:void 0,modifiers:be})}catch(me){s(`❌ Key error: ${me.message||me}`)}},oe=async Z=>{if(Z.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(Z.key)&&Z.preventDefault();let ne=0;Z.altKey&&(ne|=1),Z.ctrlKey&&(ne|=2),Z.metaKey&&(ne|=4),Z.shiftKey&&(ne|=8),m(`Key: ${Z.key}`),await ge(Z.key,Z.code,Z.key.length===1,ne)},F=async Z=>{if(Z.key==="Enter"){if(Z.nativeEvent.isComposing)return;if(f){const le=f;w(""),m(`IME Sent: ${le}`);try{const ne=await e("input_type",{text:le});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 ge("Enter","Enter",!1)}};o.useEffect(()=>{const Z=c.current;if(!Z)return;const le=ne=>{var be;if((be=u.current)!=null&&be.contains(ne.target)){ne.preventDefault();const me=Date.now();if(me-U.current<40)return;U.current=me;const E=Ie(ne.clientX,ne.clientY);if(!E)return;m(`Scroll: ${Math.round(ne.deltaY)}`),e("input_wheel",{nx:E.nx,ny:E.ny,deltaX:Math.round(ne.deltaX),deltaY:Math.round(ne.deltaY)}).catch(()=>{})}};return Z.addEventListener("wheel",le,{passive:!1}),()=>Z.removeEventListener("wheel",le)},[e]);const{cursorPos:xe,handleToggleInputMode:se,handleZoomReset:pe}=Wl({containerRef:c,viewportRef:l,imgRef:u,inputMode:j,setInputMode:k,minZoom:Le,zoomRef:G,panXRef:I,panYRef:B,setPanX:O,setPanY:N,setZoom:M,lastWheelTimeRef:U,onAction:e,setLastActionStatus:m,spawnRippleFromNormalized:de,clampPan:ie,isMobile:v,mobileFillZoom:g});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:oe,onContextMenu:Z=>Z.preventDefault(),onFocus:()=>S(!0),onBlur:()=>S(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[W?t.jsx("img",{ref:u,src:W,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${A}) translate(${L}%, ${R}%)`,transformOrigin:"center center",cursor:j==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ae,onContextMenu:Z=>Z.preventDefault(),onDragStart:Z=>Z.preventDefault()}):t.jsx(Bl,{waitingLabel:X,waitingHint:we,transportType:i}),j==="mouse"&&W&&t.jsx(El,{cursorPos:xe,viewportRef:l,imgRef:u}),T.map(Z=>{const ne={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[Z.type];return t.jsxs("div",{style:{position:"absolute",left:Z.x,top:Z.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}})]},Z.id)})]}),t.jsx($l,{inputMode:j,onToggleInputMode:se,isImeOpen:C,setIsImeOpen:P,isMenuOpen:y,setIsMenuOpen:h,imeText:f,setImeText:w,handleImeSubmit:F,isConnActive:D,zoom:A,isMobile:v,mobileFillZoom:g,onZoomOut:()=>M(Z=>Math.max(.5,Z-.25)),onZoomReset:pe,onZoomIn:()=>M(Z=>Math.min(5,Z+.25)),transportType:i,screenshotUsage:a,lastActionStatus:p}),t.jsx("style",{children:`
5
+ @keyframes slideUp {
6
+ from { opacity: 0; transform: translateY(6px); }
7
+ to { opacity: 1; transform: translateY(0); }
8
+ }
9
+ @keyframes slideUpSidebar {
10
+ from { opacity: 0; transform: translateY(6px); }
11
+ to { opacity: 1; transform: translateY(0); }
12
+ }
13
+ @keyframes click-ripple-ring {
14
+ 0% { transform: scale(0.3); opacity: 1; }
15
+ 100% { transform: scale(2.2); opacity: 0; }
16
+ }
17
+ @keyframes click-ripple-dot {
18
+ 0% { transform: scale(1); opacity: 0.9; }
19
+ 50% { transform: scale(1.8); opacity: 0.6; }
20
+ 100% { transform: scale(0.5); opacity: 0; }
21
+ }
22
+ @keyframes remote-float {
23
+ 0% { transform: translateY(0px); }
24
+ 50% { transform: translateY(-7px); }
25
+ 100% { transform: translateY(0px); }
26
+ }
27
+ `})]})}function Fr(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 Xo=e=>Fr(e);function Ol(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden}}function Rs(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 zr(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...Ol(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 _r(e,s){if(e.sessionId){const r=s.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1}}function Zn(e,s,r){var T,d,b;const n=_r(e,s),a=Rs(e),i=e.sessionId&&((T=r==null?void 0:r.notificationStateBySessionId)==null?void 0:T.get(e.sessionId))||e.providerSessionId&&((d=r==null?void 0:r.notificationStateBySessionId)==null?void 0:d.get(e.providerSessionId))||((b=r==null?void 0:r.notificationStateBySessionId)==null?void 0:b.get(e.tabKey)),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,S=n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:S,requiresAction:m,isWorking:f,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:p,inboxBucket:m?"needs_attention":f?"working":S?"task_complete":"idle"}}function Hl(e,s,r){return Zn(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Qo({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Rs(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(ls,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const p=c(l).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(p),f=/^(reject|deny|delete|remove|abort)/.test(p),w=r===l,S=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:S,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"font-extrabold":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${S&&!w?"opacity-40":"opacity-100"} ${S?"cursor-not-allowed":"cursor-pointer"}`,style:m?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:f?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:w?"⏳ ...":c(l)},u)})})]})]})}var Ul=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Fl(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function wt(e,s){if(Fl(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Ul.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 Jo(e){return wt(e)==="generating"}function at(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function zl(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 nn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Vr(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 Vl(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 Gl(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function ql(e){return Vl(e.trim().replace(/\.local$/i,""))}function Yl(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function Zo(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&&!Gl(c));if(r&&r!=="Unknown")return ql(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function It(e,s={}){return Yl(e)||Zo(e,s)}function ei(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 ti(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 ds(e,s){return ei(e).join(" · ")}function Xs(e){return e.transport==="pty"}function vs(e){return e.transport==="acp"}function Xl(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:at(e)}function Wa(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=at(r||"").trim().toLowerCase();return n===a||n===i||n===c}function Ql(e){return wt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Jl(e){if(!Array.isArray(e)||e.length<=1)return e;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),i=s.get(a),c=wt(n.status);if(!i){s.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&s.set(a,{...n,status:c})}return Array.from(s.values())}function Zl(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 ed(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&&Zl(s.receivedAt)||0}function td(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function _n(e){return Math.max(td(e),ed(e.activeChat))}function sd(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 ea(e,s){return sd(_n(e),_n(s),It(e,{fallbackId:e.id}),It(s,{fallbackId:s.id}),e.id,s.id)}const si="adhdev_notification_prefs",Oa={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function rd(){try{const e=localStorage.getItem(si);if(e){const s=JSON.parse(e);return{...Oa,...s}}}catch{}return{...Oa}}function nd(e){try{localStorage.setItem(si,JSON.stringify(e))}catch{}}let Wt=rd(),kr=[];function ad(){kr.forEach(e=>e())}function od(e){Wt={...Wt,...e},nd(Wt),ad()}function id(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return kr.push(r),()=>{kr=kr.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{od(r)},[]);return[{...Wt},s]}function Us(e){if(!Wt.globalEnabled)return!1;switch(e){case"disconnect":return Wt.disconnectAlert;case"completion":return Wt.completionAlert;case"approval":return Wt.approvalAlert;case"browser":return Wt.browserNotifications;default:return!0}}const cd={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function ld(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function ri(){return"Notification"in window&&Notification.permission==="granted"}let Jt=null;async function dd(){if(Jt!==null)return Jt;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Jt=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Jt=!!await e.pushManager.getSubscription(),Jt):(Jt=!1,!1)}catch{return Jt=!1,!1}}function Rn(e,s,r){if(ri())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 ud(e,s={}){const r={...cd,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{dd().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,p)=>{const m=Date.now();m-a.current<r.throttleMs||(a.current=m,Rn(l,u,p))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!ri())&&Us("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,wt(u.status,{activeModal:u.activeModal}));return}for(const u of e){const p=n.current.get(u.id),m=wt(u.status,{activeModal:u.activeModal}),f=u.name||u.id;if(r.onApproval&&Us("approval")&&m==="waiting_approval"&&p!=="waiting_approval"){const w=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,w.slice(0,120),`approval-${u.id}`)}r.onComplete&&Us("completion")&&Jo(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 md=/^(run|approve|accept|yes|allow|always)/,pd=/^(run|approve|accept|yes|allow|always|proceed|save)/,fd=/^(reject|deny|delete|remove|abort|cancel|no)/;function ta(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function hd(e){const s=ta(e).toLowerCase();return md.test(s)?"primary":fd.test(s)?"danger":"default"}function xd(e){return pd.test(ta(e).toLowerCase())?"approve":"reject"}function bd(e){return e.map((s,r)=>({label:ta(s),variant:hd(s),action:xd(s),button:s,buttonIndex:r}))}function gd(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 yd(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function vd(e,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,s,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,s,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class wd{constructor(){Ye(this,"dedupMap",new Map);Ye(this,"DEDUP_WINDOW_MS",5e3);Ye(this,"DEDUP_MAX_SIZE",50);Ye(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ye(this,"toastCallbacks",[]);Ye(this,"systemMessageCallbacks",[]);Ye(this,"clearSystemMessageCallbacks",[]);Ye(this,"resolveActionFn",null);Ye(this,"viewRequestRespondFn",null);Ye(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onSystemMessage(s){return this.systemMessageCallbacks.push(s),()=>{this.systemMessageCallbacks=this.systemMessageCallbacks.filter(r=>r!==s)}}onClearSystemMessage(s){return this.clearSystemMessageCallbacks.push(s),()=>{this.clearSystemMessageCallbacks=this.clearSystemMessageCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:s,type:r,timestamp:a,duration:5e3,...n})}emitSystemMessage(s,r){for(const n of this.systemMessageCallbacks)n(s,r)}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,i]of this.dedupMap)r-i>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(s){if(s.daemonId){const a=this.ides.find(i=>i.id===s.daemonId&&i.type==="adhdev-daemon");if(a)return a}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const i=this.ides.find(c=>c.id===a&&c.type==="adhdev-daemon");if(i)return i}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var T,d;const n=this.resolveConversationKey(s),a=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(a),l=`${i}:${s.event}:${c}`;if(this.isDuplicate(l))return;const u=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,p=(u==null?void 0:u.type)||"";let m=at(p);const f=this.resolveOwningDaemon(s);if(f){const b=It(f,{fallbackId:f.id});b&&(m=!p||p==="adhdev-daemon"?b:`${b}/${m}`)}let w="",S="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";w=`✅ ${m} agent task completed${b}`,S="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(w=`⚡ ${m} approval needed`,S="warning",n&&!((T=s.modalButtons)!=null&&T.length)&&this.emitSystemMessage(n,{role:"system",timestamp:a,content:gd(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=bd(s.modalButtons).map(v=>({label:v.label,variant:v.variant,onClick:()=>{y(b,"resolve_action",{action:v.action,button:v.button,buttonIndex:v.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),C=yd(m,s.modalMessage,w),P=Date.now();this.emitToast({id:P,message:C,type:S,timestamp:P,targetKey:n||b,actions:h,duration:15e3}),w=""}}else if(s.event==="monitor:long_generating"){const b=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";w=`⚠️ ${m} agent is taking a long time${b}`,S="warning",Us("browser")&&!document.hasFocus()&&Rn(`⚠️ ${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(w=`👁️ ${b} wants to view your session`,S="warning",y&&h&&this.viewRequestRespondFn){const C=Date.now(),P=vd(h,y,this.viewRequestRespondFn,(v,j)=>console.error(`[EventManager] ${v} view request failed:`,j));this.emitToast({id:C,message:w,type:S,timestamp:C,actions:P,duration:3e4}),w=""}Us("browser")&&!document.hasFocus()&&Rn("👁️ View Request",`${b} wants to view your session`,`view-request-${y}`)}else s.event==="team:view_request_approved"?(w="✅ View request approved",S="success"):s.event==="team:view_request_rejected"&&(w=`❌ ${s.targetName||"Team member"} declined your view request`,S="warning");if(w){const b=Date.now();this.emitToast({id:b,message:w,type:S,timestamp:b,targetKey:n||s.daemonId,duration:5e3})}}}const ot=new wd,Ha=new Map;function Cs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ni(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function jd(e){return!Cs(e)||!Cs(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function lr(e){return!Cs(e)||!Cs(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function Es(e){if(!(!Cs(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function dr(e){return Cs(e)&&e.success===!1}function kd(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";ot.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";ot.showToast(n.notification.body,a)}}}function Sd(e,s){return e&&ni(e.currentValue)?e.currentValue:s}function Sr(e,s){return e.options||s[e.id]||[]}function an(e,s){return{value:s}}function Nd(e,s,r){var a;return r?((a=Sr(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const Cd={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Id({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=Tt(),u=`${e}:${s||n}`,p=Cd[n]||"#94a3b8",[m,f]=o.useState({}),w=o.useRef(0),S={};for(const R of i||[])R.defaultValue!==void 0&&(S[R.id]=R.defaultValue);const T={...S,...c||{},...Date.now()<w.current?m:{}};o.useEffect(()=>{c&&Date.now()>w.current&&f({})},[c]);const[d,b]=o.useState(Ha.get(u)||{}),[y,h]=o.useState(null),[C,P]=o.useState(null),v=o.useCallback(async(R,N={})=>{const U={...N,...s&&{targetSessionId:s}};return await l(e,R,U)},[e,s,l]),j=o.useCallback(async(R,N={})=>{const U=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await v("invoke_provider_script",{...U,scriptName:R,...N})},[v,n,r,s]),k=o.useCallback((R,N,U)=>{const G=Sd(U,N);f(I=>({...I,[R.id]:G})),kd(U==null?void 0:U.effects)},[]),g=o.useCallback((R,N)=>{f(U=>{const G={...U};return N===void 0?delete G[R.id]:G[R.id]=N,G}),w.current=0},[]);if(!i||i.length===0)return null;const x=i.filter(R=>R.placement==="bar"&&R.hidden!==!0).sort((R,N)=>(R.order??50)-(N.order??50));if(x.length===0)return null;const $=async R=>{if(y===R.id){h(null);return}if(Sr(R,d).length>0){h(R.id);return}if(R.dynamic&&R.listScript){P(R.id);try{const U=await j(R.listScript,{}),G=jd(U);if(!G){const B=Es(U);B&&ot.showToast(B,"warning");return}const I=G.options;if(b(B=>{const D={...B,[R.id]:I};return Ha.set(u,D),D}),ni(G.currentValue)){const B=G.currentValue;f(D=>({...D,[R.id]:B}))}h(R.id)}catch(U){const G=U instanceof Error?U.message:`Could not load ${R.label}`;ot.showToast(G,"warning")}finally{P(null)}}},A=async(R,N)=>{h(null);const U=(c==null?void 0:c[R.id])??S[R.id];f(G=>({...G,[R.id]:N})),w.current=Date.now()+5e3;try{if(!R.setScript)return;const G=await j(R.setScript,an(R,N)),I=lr(G);if(I&&!I.ok||dr(G))throw new Error((I==null?void 0:I.error)||Es(G)||`Could not update ${R.label}`);k(R,N,I)}catch(G){g(R,U);const I=G instanceof Error?G.message:`Could not update ${R.label}`;ot.showToast(I,"warning")}},M=async R=>{const N=Sr(R,d).map(W=>W.value);if(N.length===0)return;const U=String(T[R.id]||""),I=(N.indexOf(U)+1)%N.length,B=N[I];if(typeof B!="string")return;const D=(c==null?void 0:c[R.id])??S[R.id];f(W=>({...W,[R.id]:B})),w.current=Date.now()+5e3;try{if(!R.setScript)return;const W=await j(R.setScript,an(R,B)),X=lr(W);if(X&&!X.ok||dr(W))throw new Error((X==null?void 0:X.error)||Es(W)||`Could not update ${R.label}`);k(R,B,X)}catch(W){g(R,D);const X=W instanceof Error?W.message:`Could not update ${R.label}`;ot.showToast(X,"warning")}},L=async R=>{const U=!T[R.id],G=(c==null?void 0:c[R.id])??S[R.id];f(I=>({...I,[R.id]:U})),w.current=Date.now()+5e3;try{if(!R.setScript)return;const I=await j(R.setScript,an(R,U)),B=lr(I);if(B&&!B.ok||dr(I))throw new Error((B==null?void 0:B.error)||Es(I)||`Could not update ${R.label}`);k(R,U,B)}catch(I){g(R,G);const B=I instanceof Error?I.message:`Could not update ${R.label}`;ot.showToast(B,"warning")}},O=async R=>{if(!R.invokeScript)return;if(R.confirmMessage){const U=[R.confirmTitle,R.confirmMessage,R.confirmLabel].filter(I=>typeof I=="string"&&I.trim().length>0);if(!window.confirm(U.join(`
29
+
30
+ `)))return}const N=(c==null?void 0:c[R.id])??S[R.id];try{const U=await j(R.invokeScript),G=lr(U);if(G&&!G.ok||dr(U))throw new Error((G==null?void 0:G.error)||Es(U)||`Could not run ${R.label}`);G&&k(R,N??!0,G)}catch(U){g(R,N);const G=U instanceof Error?U.message:`Could not run ${R.label}`;ot.showToast(G,"warning")}};return t.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1 flex-wrap text-[10px] border-t border-border-subtle bg-surface-primary font-[var(--font)]",children:[t.jsx("span",{className:"text-[9px] font-bold tracking-wide opacity-70",style:{color:p},children:a}),t.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),x.map(R=>{const N=String(T[R.id]||""),U=Nd(R,d,N),G=y===R.id,I=C===R.id,B=Sr(R,d);switch(R.type){case"select":return t.jsxs("div",{className:"relative",children:[t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap max-w-40 overflow-hidden text-ellipsis",style:{borderColor:G?`${p}55`:"transparent",border:"1px solid",color:N?"var(--text-primary)":"var(--text-muted)"},onClick:()=>$(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),I?"...":U||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),G&&B.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>h(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] bg-[var(--surface-primary)] border border-border-subtle rounded-lg mb-1 max-h-[220px] overflow-y-auto min-w-40 shadow-[0_-4px_16px_rgba(0,0,0,0.3)]",children:[t.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:R.label.toUpperCase()}),B.map(D=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:D.value===N?`${p}18`:"transparent",color:D.value===N?p:"var(--text-secondary)",fontWeight:D.value===N?600:400,borderLeft:D.value===N?`2px solid ${p}`:"2px solid transparent"},title:D.description||D.label,onMouseEnter:W=>{W.currentTarget.style.background=`${p}12`},onMouseLeave:W=>{W.currentTarget.style.background=D.value===N?`${p}18`:"transparent"},onClick:()=>A(R,D.value),children:D.label},D.value))]})]})]},R.id);case"cycle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap",style:{border:"1px solid transparent",color:N?"var(--text-primary)":"var(--text-muted)"},onClick:()=>M(R),title:`Click to cycle: ${B.map(D=>D.label).join(" → ")}`,children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),U||R.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},R.id);case"toggle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all whitespace-nowrap",style:{border:"1px solid",borderColor:N?`${p}44`:"transparent",background:N?`${p}14`:"var(--surface-tertiary)",color:N?p:"var(--text-muted)"},onClick:()=>L(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.label]},R.id);case"action":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all hover:bg-[var(--surface-tertiary-hover)] whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>O(R),children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),R.resultDisplay==="inline"&&N?`${R.label}: ${N}`:R.label]},R.id);case"display":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:N?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:R.icon}),N?`${R.label}: ${N}`:R.label]},R.id);default:return null}})]})}const Ad=o.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:a,isActive:i=!0}){const c=o.useRef(null),[l,u]=o.useState("");o.useEffect(()=>{u("")},[s]),o.useEffect(()=>{var m;i&&((m=c.current)==null||m.focus())},[s,i]);const p=()=>{const m=l.trim();!m||n||(u(""),a(m))};return t.jsx("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:i?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:i?72:0,opacity:i?1:0,transform:i?"translateY(0)":"translateY(10px)",padding:i?"10px 12px":"0 12px",pointerEvents:i?"auto":"none"},"aria-hidden":!i,children:t.jsxs("div",{className:"flex gap-2.5 items-center",title:i?`Send message to ${r}`:void 0,children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:c,type:"text",placeholder:`Send message to ${r}...`,value:l,onChange:m=>u(m.target.value),onPaste:m=>{const f=m.clipboardData.getData("text");f&&u(w=>w+f),m.preventDefault()},onKeyDown:m=>{if(m.key==="Enter"){if(m.nativeEvent.isComposing){m.preventDefault();return}m.preventDefault(),p()}},onBlur:m=>{if(window.innerWidth<768){const f=m.relatedTarget;if((f==null?void 0:f.tagName)==="BUTTON")return;setTimeout(()=>{document.documentElement.scrollTop=0},300)}},className:"w-full h-10 rounded-[20px] px-4 bg-bg-secondary text-sm text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:p,disabled:!l.trim()||n,className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${l.trim()&&!n?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:l.trim()&&!n?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:l.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})}),et=e=>e.transport==="pty",Is=(e,s)=>et(e)?e.mode||"terminal":"chat",ai=(e,s)=>et(e)&&Is(e)==="terminal",Xe=e=>e.transport==="acp";function Vt(e){return e.streamSource!=="agent-stream"}function qt(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function oi(e){return e.machineName||""}function er(e){return qt(e)}function Dt(e){return e.agentType||""}function Rr(e){return e.hostIdeType||""}function sa(e){return e.displayPrimary||e.agentName||"Agent"}function ii(e){return[e.displaySecondary,oi(e)].filter(Boolean)}function us(e){return e.agentName||at(Dt(e))}function Td(e){var s,r;if(!Vt(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return at(Rr(e)||Dt(e))}function ra(e){return Vt(e)?e.sessionId:e.nativeSessionId}function Ua(e){return Vt(e)?"native":e.tabKey}function Md(e){return e.sessionId}function Ld(e,s){if(s)return Vt(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function _d(e,s){const r=Dt(e),n=Vt(e),a=et(e)||Xe(e),i=n?a?us(e)||(s==null?void 0:s.cliName)||at(Rr(e)||r):s!=null&&s.type?at(s.type):at(Rr(e)||r):us(e);return{isNativeConversation:n,isCli:et(e),isAcp:Xe(e),isCliTerminal:ai(e),providerType:r,displayLabel:i,targetEntry:Ld(e,s)}}function ci({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Ls(),c=qt(e),l=oi(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=us(e),w=Td(e),S=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),T=o.useCallback(()=>{if(r){r();return}const d=ra(e);d&&i(`/dashboard?activeTab=${encodeURIComponent(d)}`)},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[u&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:T,title:w,children:[t.jsx(At,{size:12}),t.jsx("span",{children:w})]}):t.jsxs("span",{className:"conversation-meta-chip",title:w,children:[t.jsx(At,{size:12}),t.jsx("span",{children:w})]})),p&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(Ys,{size:12}),t.jsx("span",{children:f})]}),m&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(Ys,{size:12}),t.jsx("span",{children:f})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:l,children:[t.jsx(Ot,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(Ot,{size:12}),t.jsx("span",{children:l})]}))]})}function on(e,s){return`${e}:${s}`}function Rd(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function ur(e,s){Rd()&&console.debug(`[subscription-manager] ${e}`,s)}class Pd{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),ur("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((p=s.sendData)==null?void 0:p.call(s,r,n))??!1}const u=()=>{var w;const m=this.active.get(i);if(!m||(m.handlers.delete(a),m.handlers.size>0))return;this.active.delete(i);const f={type:"unsubscribe",topic:n.topic,key:n.key};ur("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(w=s.sendData)==null||w.call(s,r,f)};return u.initialSendAccepted=l,u}publish(s){const r=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;ur("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);ur("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 Gt=new Pd;function Dd(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 Ed(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function mr(e,s){return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerName:e.providerName??(s==null?void 0:s.providerName)??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??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)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),activeChat:Dd(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)}}function $d(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 Pr(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}=$d(u),f=Ed(i,n),w=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,S=p.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),T=p.filter(b=>b.kind==="agent"&&b.transport==="pty"),d=p.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...w&&{machine:w,platform:w.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},cdpConnected:S.some(b=>!!b.cdpConnected)});for(const b of S){const y=f.get(b.id),h=mr(b,y),C=(m.get(b.id)||[]).map(P=>mr(P,f.get(P.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:C,agents:C.map(P=>({id:P.id,name:P.providerName||P.providerType,type:P.providerType,status:P.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l})}for(const b of T){const y=f.get(b.id),h=mr(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,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=mr(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,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 cn=new Map,ln=new Map,dn=new Set,Fs=new Map,Bd=1200;function Kd(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 Fa(e,s){const r=Fs.get(e);!r||r.size===0||(Fs.delete(e),r.forEach(n=>n(s)))}function Wd(e,s){return new Promise(r=>{const n=Fs.get(e)||new Set;Fs.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&Fs.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function tr(){const{sendCommand:e,sendData:s}=Tt(),{injectEntries:r,getIdes:n}=Lr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=ln.get(a)||0;if(!(i!=null&&i.force)&&dn.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=cn.get(a);if(u)return u;const p=(async()=>{if(s&&!dn.has(a)&&(dn.add(a),Gt.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},d=>{const b=n(),y=b.find(C=>C.id===a),h=Pr(d.status,{daemonId:a,existingDaemon:y,existingEntries:b,timestamp:d.timestamp});h.length>0&&r(h),ln.set(a,Date.now()),Fa(a,!0)}),!(i!=null&&i.force)&&await Wd(a,Bd)))return;const m=await e(a,"get_status_metadata"),f=Kd(m);if(!f)return;const w=n(),S=w.find(d=>d.id===a),T=Pr(f,{daemonId:a,existingDaemon:S,existingEntries:w,timestamp:f.timestamp||Date.now()});T.length>0&&r(T,{authoritativeDaemonIds:[a]}),ln.set(a,Date.now()),Fa(a,!0)})().finally(()=>{cn.delete(a)});return cn.set(a,p),p},[n,r,e,s])}function Ut(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function na(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=Ns(e.content),i=Ns(s.content);if(!a||a!==i)return!1;const c=Ut(e),l=Ut(s);return c&&l?Math.abs(c-l)<=15e3:!!e._localId!=!!s._localId}function za(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),Ut(e)&&(s+=1),s}function As(e){return Ns(e==null?void 0:e.content)}function Pn(e,s){return!e||!s||e.length<=s.length||s.length<80?!1:e.startsWith(s)||e.includes(s)}function Od(e,s){const r=As(e),n=As(s);return!r||!n||r===n?null:Pn(r,n)?e:Pn(n,r)?s:null}function Hd(e,s){const r=Od(e,s);if(r)return r;const n=za(e),a=za(s);return a!==n?a>n?s:e:As(s).length>=As(e).length?s:e}function Qs(e){const s=[];for(const r of e){const n=s.findIndex(a=>na(a,r));if(n>=0){s.splice(n,1,Hd(s[n],r));continue}s.push(r)}return s}function Ud(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:Qs([...r,...n])}function Va(e){return[...e].sort((s,r)=>{const n=Ut(s),a=Ut(r);return n&&a&&n!==a?n-a:0})}function Ga(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=>na(i,n));return a>=0?(r.splice(a,1),!1):!0})}function Fd(e,s){return e.filter(r=>{const n=As(r),a=String((r==null?void 0:r.role)||"").toLowerCase(),i=Ut(r);return!s.some(c=>{if(na(r,c))return!0;const l=String((c==null?void 0:c.role)||"").toLowerCase();if(!n||!a||a!==l)return!1;const u=As(c);if(!Pn(u,n)&&u!==n)return!1;const p=Ut(c);return i&&p?Math.abs(i-p)<=15e3:!0})})}const zd=60,Vd=200;function Gd(e={}){return e.isCliLike?Vd:zd}const sr=60,qa=new Map;function qd(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 li(e,s){return`${e}::${s}`}function Dn(e=sr){return{liveMessages:[],cursor:Yd([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function di(e){if(!e)return"";let s="";try{s=JSON.stringify(e.content??"")}catch{s=String(e.content??"")}return qd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),s])}function Yd(e,s=sr){return{knownMessageCount:e.length,lastMessageSignature:di(e[e.length-1]),tailLimit:s}}function Ya(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 Xd(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return Qs([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return Qs([...e.slice(0,n),...r])}case"full":default:return r}}class Qd{constructor(s){Ye(this,"manager");Ye(this,"sendData");Ye(this,"daemonId");Ye(this,"sessionId");Ye(this,"historySessionId");Ye(this,"subscriptionKey");Ye(this,"snapshot");Ye(this,"transportSubscription",null);Ye(this,"listeners",new Set);Ye(this,"retainCount",0);Ye(this,"loadHistoryPromise",null);this.manager=s.manager||Gt,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=Dn(Math.max(0,s.tailLimit??sr))}updateOptions(s){s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId)}getSnapshot(){return this.snapshot}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}retain(){this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),this.retainCount===0&&this.disconnect()}async loadHistoryPage(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await s(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}},s=>{this.handleUpdate(s)}))}disconnect(){var s;(s=this.transportSubscription)==null||s.call(this),this.transportSubscription=null}dispose(){this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){const r=Xd(this.snapshot.liveMessages,s),n={knownMessageCount:Math.max(r.length,Number(s.totalMessages||0)),lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:di(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};Ya(this.snapshot.liveMessages)===Ya(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 ui(e){const s=li(e.daemonId,e.sessionId),r=qa.get(s);if(r)return r.updateOptions(e),r;const n=new Qd(e);return qa.set(s,n),n}function Jd(e,s){return{...e,loadHistoryPage:s}}function Zd(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function eu(e){const s=new Set,r=[];for(const n of e){const a=er(n),i=n.sessionId||"";if(!a||!i)continue;const c=li(a,i);s.has(c)||(s.add(c),r.push({daemonId:a,sessionId:i,historySessionId:n.providerSessionId||i,subscriptionKey:`daemon:${a}:session:${i}`}))}return r.sort(Zd),{descriptors:r,signature:r.map(n=>`${n.subscriptionKey}|${n.historySessionId}`).join("||")}}function tu(e,s){const{sendData:r,sendCommand:n}=Tt(),a=(s==null?void 0:s.enabled)!==!1,i=er(e),c=e.sessionId||"",l=e.providerSessionId||c,u=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??sr),m=o.useMemo(()=>!a||!i||!c?null:ui({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:p}),[i,a,l,r,c,u,p]),[f,w]=o.useState(()=>(m==null?void 0:m.getSnapshot())||Dn(p));o.useEffect(()=>{if(!m){w(Dn(p));return}m.retain(),w(m.getSnapshot());const T=m.subscribe(d=>{w(d)});return()=>{T(),m.release()}},[m,p]);const S=o.useCallback(async()=>{!m||!i||!c||await m.loadHistoryPage(async()=>{const T=e.agentType,d=await n(i,"chat_history",{agentType:T,offset:m.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),b=d&&typeof d=="object"&&"result"in d?d.result||{}:d||{};return{messages:Array.isArray(b.messages)?b.messages:[],hasMore:b.hasMore===!0}})},[e.agentType,m,i,l,n,c]);return o.useMemo(()=>Jd(f,S),[S,f])}function su(e,s){const{sendData:r}=Tt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,sr),i=o.useMemo(()=>eu(e),[e]);o.useEffect(()=>{if(!r||i.descriptors.length===0)return;const c=i.descriptors.map(l=>ui({...l,sendData:r,tailLimit:a}));return c.forEach(l=>l.retain()),()=>{c.forEach(l=>l.release())}},[i.signature,n,r,a])}function ru(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function nu(e){return ru(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const au=60;function En({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:a,isFocusingAgent:i,actionLogs:c,userName:l,showMetaChips:u=!1,scrollToBottomRequestNonce:p,isInputActive:m=!0}){var I,B;const f=o.useRef(new Map),w=tr();Zs("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const S=nt.useMemo(()=>Rs(e),[e.status,e.connectionState]),T=o.useMemo(()=>_d(e,s),[e,s]),d=Gd({isCliLike:T.isCli||T.isAcp}),b=tu(e,{enabled:!!e.sessionId}),[y,h]=o.useState(d),C=e.tabKey,P=b.historyMessages,v=b.hasMoreHistory,j=b.historyError,k=Ud(b.liveMessages,e.messages);o.useEffect(()=>{h(d)},[d,C]);const g=Math.max(0,k.length-y),x=sa(e),$=er(e),A=nu(e),[M,L]=o.useState(!1);o.useEffect(()=>{const D=T.targetEntry;$&&(!D||D.providerControls===void 0||D.controlValues===void 0)&&w($,{minFreshMs:3e4}).catch(()=>{})},[$,T.isAcp,(I=T.targetEntry)==null?void 0:I.providerControls,(B=T.targetEntry)==null?void 0:B.controlValues,w]);const O=o.useCallback(async()=>{if(!M){if(k.length>y){h(D=>Math.min(k.length,D+au));return}L(!0);try{await b.loadHistoryPage()}finally{L(!1)}}},[b,M,k.length,y]),{allMessages:R,receivedAtMap:N}=o.useMemo(()=>{const D=g>0?k.slice(-y):k;if(P.length===0){const Le=Va(Qs(D)),ie={};return Le.forEach((Ie,te)=>{const de=`${e.tabKey}:${ys(Ie,te)}`;let ae=Ut(Ie)||f.current.get(de)||0;ae||(ae=Date.now(),f.current.set(de,ae)),ie[ys(Ie,te)]=ae}),{allMessages:Le,receivedAtMap:ie}}const W=Fd(P,D),X=Va(Qs([...W,...D])),we={};return X.forEach((Le,ie)=>{const Ie=`${e.tabKey}:${ys(Le,ie)}`;let te=Ut(Le)||f.current.get(Ie)||0;te||(te=Date.now(),f.current.set(Ie,te)),we[ys(Le,ie)]=te}),{allMessages:X,receivedAtMap:we}},[e.tabKey,g,P,k,y]),U=o.useMemo(()=>c.filter(D=>D.routeId===e.tabKey).sort((D,W)=>D.timestamp-W.timestamp),[c,e.tabKey]),G=o.useMemo(()=>{if(k.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((S.isGenerating||e.status==="streaming")&&L(!1),e.status==="not_monitored"&&A)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(Ys,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:a,disabled:i,className:"btn btn-primary",children:i?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ss,{size:14})," Open ",x," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&A)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(Uo,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:a,disabled:i,className:"btn btn-primary",children:i?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ss,{size:14})," Open ",x," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!M)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,A,a,i,M,k.length,x,S.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[u&&t.jsx(ci,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(_l,{messages:R,actionLogs:U,agentName:us(e)||x||"Agent",userName:l,isCliMode:T.isCli||T.isAcp,isWorking:S.isGenerating,contextKey:e.tabKey,receivedAtMap:N,onLoadMore:O,isLoadingMore:M,hasMoreHistory:v,hiddenLiveCount:g,loadError:j??void 0,emptyState:G,scrollToBottomRequestNonce:p}),m&&!T.isCliTerminal&&(()=>{var D,W;return t.jsx(Id,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:T.providerType,displayLabel:T.displayLabel,controls:(D=T.targetEntry)==null?void 0:D.providerControls,controlValues:(W=T.targetEntry)==null?void 0:W.controlValues})})(),!T.isCliTerminal&&t.jsx(Ad,{contextKey:e.tabKey,panelLabel:x,isSending:n,onSend:r,isActive:m})]})}let mi=cs;function pi(){return mi()}class ou{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 fi=new ou;class iu{sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,a){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let dt=new iu;function cu(e){e.dashboardWS&&(fi=e.dashboardWS),e.connectionManager&&(dt=e.connectionManager),e.useDaemonsHook&&(mi=e.useDaemonsHook)}function it(e){return sa(e)}function ms(e){return ii(e).join(" · ")}function hi(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=Ns(s==null?void 0:s.content);return r||(e.title?e.title:ms(e)||"No messages yet")}function xi(e,s){const{isReconnecting:r,isConnecting:n}=Rs(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function lu(e,s){const r=["Chat",...ii(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ts(e){return xi(e)||ms(e)}function du(e){return`${it(e)} · ${hi(e)}`}function uu(e){const s=Rr(e),r=s?at(s):us(e);return`${it(e)} — ${r||"Agent"}`}function mu(e){return us(e)||"CLI"}function bi(e){return e.title||us(e)||e.routeId}function gi(e){return e?`Remote · ${it(e)||e.workspaceName||"Session"}`:"Remote"}function pu({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,isVisible:i=!0}){var B;const{ides:c}=cs(),l=o.useRef(null),{sendCommand:u,sendData:p}=Tt(),[m,f]=o.useState(""),[w,S]=o.useState(!1),[T,d]=o.useState(1),b=o.useRef(!1),y=o.useRef(0),h=o.useRef(!1),C=o.useRef(""),P=o.useRef(null),v=o.useRef(!1),j=o.useRef(null),k=e.tabKey,g=e.sessionId||"",x=e.daemonId||((B=e.routeId)==null?void 0:B.split(":")[0])||e.routeId||"",$=c.find(D=>D.id===x&&D.type==="adhdev-daemon"),A=($==null?void 0:$.terminalSizingMode)==="fit"?"fit":"measured",M=.6,L=1.15,O=()=>{if(typeof window>"u")return 1;const D=window.innerWidth||0;return D<=360?.68:D<=390?.74:D<=430?.82:D<=480?.9:1},R=()=>{var D,W;y.current=0,h.current=!1,C.current="",P.current=null,v.current=!1,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),S(!1),(W=(D=r.current)==null?void 0:D.reset)==null||W.call(D)},N=()=>{var D,W;y.current=0,h.current=!1,C.current="",P.current=null,v.current=!1,j.current!==null&&(cancelAnimationFrame(j.current),j.current=null),S(!0),(W=(D=r.current)==null?void 0:D.reset)==null||W.call(D)},U=()=>{var W;if(j.current=null,!i)return;const D=C.current;D&&(C.current="",(W=r.current)==null||W.write(D))},G=D=>{D&&(C.current+=D,i&&j.current===null&&(j.current=requestAnimationFrame(U)))},I=(D,W=0,X,we)=>{var Le,ie,Ie,te,de;W>0&&y.current>=W||W===0&&h.current||(y.current=W,S(!0),typeof X=="number"&&typeof we=="number"&&X>0&&we>0&&((ie=(Le=r.current)==null?void 0:Le.resize)==null||ie.call(Le,X,we)),(te=(Ie=r.current)==null?void 0:Ie.reset)==null||te.call(Ie),D&&((de=r.current)==null||de.write(D)))};return o.useEffect(()=>{R()},[g]),o.useEffect(()=>{var W;if(!g)return;const D=((W=dt.onRuntimeEvent)==null?void 0:W.call(dt,g,X=>{if(!(!X||X.sessionId!==g)){if(X.type==="runtime_snapshot"){if(!i){P.current={text:X.text||"",seq:X.seq||0,cols:X.cols,rows:X.rows};return}I(X.text||"",X.seq||0,X.cols,X.rows);return}if(X.type==="session_output"){h.current=!0,typeof X.seq=="number"&&(y.current=Math.max(y.current,X.seq)),w||S(!0),typeof X.data=="string"&&G(X.data);return}if(X.type==="session_cleared"){if(!i){v.current=!0,C.current="",P.current=null;return}N()}}}))||(()=>{});return()=>{D()}},[x,g,r,i,w]),o.useEffect(()=>{var W,X,we;if(!g)return;x&&((W=dt.getState)==null?void 0:W.call(dt,x))==="connected"&&(S(!0),(X=dt.requestRuntimeSnapshot)==null||X.call(dt,x,g).catch(()=>{}));const D=(we=dt.onStateChange)==null?void 0:we.call(dt,(Le,ie)=>{var Ie;Le!==x||ie!=="connected"||(S(!0),(Ie=dt.requestRuntimeSnapshot)==null||Ie.call(dt,x,g).catch(()=>{}))});return()=>{D==null||D()}},[x,g,r]),o.useEffect(()=>{s&&R()},[s,k,r]),o.useEffect(()=>{f("")},[e.tabKey]),o.useEffect(()=>{const D=()=>{b.current||d(O())};return D(),window.addEventListener("resize",D),()=>window.removeEventListener("resize",D)},[]),o.useEffect(()=>{var W;if(!i){(W=l.current)==null||W.blur();return}v.current&&(v.current=!1,N());const D=P.current;D&&(P.current=null,I(D.text,D.seq,D.cols,D.rows)),C.current&&j.current===null&&(j.current=requestAnimationFrame(U)),requestAnimationFrame(()=>{var X;(X=r.current)==null||X.bumpResize()})},[i]),o.useEffect(()=>()=>{j.current!==null&&(cancelAnimationFrame(j.current),j.current=null)},[]),o.useEffect(()=>{const D=W=>{var we;const X=W.detail;X!=null&&X.sessionId&&X.sessionId!==g||w&&((we=r.current)==null||we.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",D),()=>{window.removeEventListener("adhdev:fit-cli-terminal",D)}},[w,g,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{b.current=!0,d(D=>Math.max(M,Number((D-.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(D=>Math.min(L,Number((D+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-auto rounded-lg",children:t.jsx("div",{style:{width:`${100/T}%`,height:`${100/T}%`,transform:`scale(${T})`,transformOrigin:"top left"},children:t.jsx(qo,{ref:r,readOnly:!w||!i,sizingMode:A,onInput:D=>{w&&(p!=null&&p(x,{type:"pty_input",sessionId:g,targetSessionId:g,data:D})||u(x,"pty_input",{targetSessionId:g,data:D}).catch(console.error))}})})}),!w&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),t.jsx("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:t.jsxs("div",{className:"flex gap-2.5 items-center",children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:l,type:"text",placeholder:`Send message to ${it(e)}...`,value:m,disabled:!w||!i||a,onChange:D=>f(D.target.value),onPaste:D=>{const W=D.clipboardData.getData("text");W&&f(X=>X+W),D.preventDefault()},onKeyDown:D=>{if(D.key!=="Enter")return;if(D.nativeEvent.isComposing){D.preventDefault();return}D.preventDefault();const W=m.trim();!w||!W||a||(f(""),n(W))},className:"w-full h-9 rounded-[18px] px-4 bg-bg-secondary text-[13px] text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{const D=m.trim();!w||!D||a||(f(""),n(D))},disabled:!w||!i||!m.trim()||a,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${m.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:m.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:m.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function fu({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 hu({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 aa({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(Hr,{size:n}):t.jsx(Ht,{size:n})})}function Xa({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Qa({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=Fr(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 xu({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetCliViewMode:p,onHideConversation:m,hiddenConversations:f=[],onShowConversation:w,onShowAllHidden:S,onResetPanelsToMain:T,inboxOpen:d,onInboxOpenChange:b,hiddenOpen:y,onHiddenOpenChange:h,onOpenNewSession:C,actionShortcuts:P,notifications:v,notificationUnreadCount:j,onOpenNotification:k,onMarkNotificationRead:g,onMarkNotificationUnread:x,onDeleteNotification:$}){const{ides:A,p2pStates:M={}}=cs(),L=!!e&&et(e)&&!Xe(e),O=!!e&&Xe(e),R=u||(e?ai(e)?"terminal":"chat":null),[N,U]=o.useState(!1),G=o.useRef(null),I=o.useRef(null),B=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",D=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",W=A.filter(F=>F.type==="adhdev-daemon"),X=Object.values(M),we=X.filter(F=>F==="connected").length,Le=X.filter(F=>F==="connecting"||F==="new"||F==="checking").length,Ie=r!=="connected"||W.length===0?null:Le>0&&we===0?"P2P connecting...":we>0&&s===0?"Waiting for IDE...":null,te=o.useMemo(()=>v.filter(F=>!F.readAt),[v]),de=o.useMemo(()=>v.filter(F=>!!F.readAt),[v]),ae=o.useMemo(()=>te.slice(0,9),[te]),ge=j;o.useEffect(()=>{if(!d)return;const F=xe=>{var se;(se=G.current)!=null&&se.contains(xe.target)||b(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[d,b]),o.useEffect(()=>{if(!y)return;const F=xe=>{var se;(se=I.current)!=null&&se.contains(xe.target)||h(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[y,h]),o.useEffect(()=>{if(!y&&!d)return;const F=xe=>{if(!xe.altKey)return;const se=xe.code.match(/^Digit([1-9])$/);if(!se)return;const pe=Number(se[1])-1,Z=y?f[pe]:void 0,le=d?ae[pe]:void 0;if(!(!Z&&!le)){if(xe.preventDefault(),xe.stopPropagation(),Z){w==null||w(Z),h(!1);return}le&&(k(le),b(!1))}};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)},[f,y,d,ae,h,b,k,w]);const oe=F=>{if(!F)return;const xe=a.find(se=>se.tabKey===F);xe&&(m==null||m(xe))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(Ht,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?it(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:B,boxShadow:D}})})]}),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:B,boxShadow:D}}),Ie&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",Ie]}),C&&t.jsx("button",{type:"button",onClick:C,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(dl,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(L||O||!Xe(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:ms(e)||it(e),children:it(e)}),(L||O)&&l&&t.jsxs(t.Fragment,{children:[L&&p&&R&&t.jsx(aa,{mode:R,onChange:p,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:O?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(St,{size:14})})]}),!Xe(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(Xn,{size:14})}),!L&&!Xe(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(At,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:G,children:[t.jsxs("div",{className:`dashboard-header-hidden${N?" is-drop-target":""}`,ref:I,onDragEnter:F=>{F.dataTransfer.types.includes("text/tab-key")&&(F.preventDefault(),U(!0))},onDragOver:F=>{F.dataTransfer.types.includes("text/tab-key")&&(F.preventDefault(),F.dataTransfer.dropEffect="move",U(!0))},onDragLeave:F=>{F.currentTarget.contains(F.relatedTarget)||U(!1)},onDrop:F=>{const xe=F.dataTransfer.getData("text/tab-key");F.preventDefault(),U(!1),oe(xe)},children:[t.jsxs("button",{type:"button",onClick:()=>h(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${P!=null&&P.toggleHiddenTabs?` (${P.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(Fo,{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(Xa,{value:P==null?void 0:P.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[T&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:T,children:"Reset panels"}),f.length>0&&S&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{S(),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(Xa,{value:P==null?void 0:P.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:it(e)})]}),f.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:f.map(F=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{w==null||w(F),h(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:it(F)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[f.indexOf(F)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",f.indexOf(F)+1]}):null,ms(F)]})]},F.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>b(!d),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(Ur,{size:16}),ge>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:ge})]}),d&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[te.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),te.map(F=>t.jsx(Qa,{notification:F,shortcutIndex:ae.indexOf(F)>=0?ae.indexOf(F)+1:void 0,onOpen:()=>k(F),onMarkRead:()=>g(F.id),onMarkUnread:()=>x(F.id),onDelete:()=>$(F.id)},F.id))]}),de.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),de.map(F=>t.jsx(Qa,{notification:F,onOpen:()=>k(F),onMarkRead:()=>g(F.id),onMarkUnread:()=>x(F.id),onDelete:()=>$(F.id)},F.id))]}),v.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function gt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function bu(e,s){return String(e||"")!==String(s||"")}function gu(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&&!ei(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
32
+ `).includes(a)))}function yu(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 yi(e,s={}){return yu(gu(e,s),s.sortMode||"recent")}function Dr(e){return e?"Resume saved history":"Start fresh"}function oa(e){return e?"Resuming saved history…":"Starting fresh…"}function vu(){return"Start fresh"}function vi(e,s=!1){return e==="cli"?Dr(s):e==="ide"?"Start IDE":"Start ACP session"}function wi(e,s=!1){return e==="cli"?oa(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function wu(){return"Recover hosted runtime"}function ju(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function ku(){return"Open saved history"}function Su(){return"Saved History"}function ia(){return"Use saved history when you want continuity in the same provider conversation."}function Nu(){return"No saved history found yet."}function Cu(){return"Refresh saved history"}function Iu(){return"Refreshing saved history…"}function ss(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function rs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Ts(e){return e==="start-fresh"?"Start fresh":"Restart"}function Ms(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function ca(e){return`Resume saved history with ${e}?`}function la(){return"Review or change the target workspace before resuming saved history."}function Au(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 da({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:p,onNewChat:m,onSwitchSession:f,onRefreshHistory:w,onResumeSavedSession:S}){var g;const T=s.find(x=>x.id===e.routeId),d=(T==null?void 0:T.chats)||[],b=(g=T==null?void 0:T.activeChat)==null?void 0:g.id,y=et(e)&&!Xe(e),[h,C]=o.useState(()=>gt()),P=l||h,v=x=>{if(u){u(x);return}C(x)},j=o.useMemo(()=>yi(a,{textQuery:P.textQuery,workspaceQuery:P.workspaceQuery,modelQuery:P.modelQuery,resumableOnly:P.resumableOnly,sortMode:P.sortMode}),[P.modelQuery,P.resumableOnly,P.sortMode,P.textQuery,P.workspaceQuery,a]),k=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick: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?Su():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:uu(e)}),y&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:ia()})]}),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(St,{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:P.textQuery,onChange:x=>v({...P,textQuery:x.target.value}),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:P.workspaceQuery,onChange:x=>v({...P,workspaceQuery:x.target.value}),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("input",{type:"text",value:P.modelQuery,onChange:x=>v({...P,modelQuery:x.target.value}),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsxs("select",{value:P.sortMode,onChange:x=>v({...P,sortMode:x.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:P.resumableOnly,onChange:x=>v({...P,resumableOnly:x.target.checked})}),"Resume-ready only"]})]}),j.map(x=>{const $=e.providerSessionId===x.providerSessionId,A=$||!x.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{A||!S||S(x)},disabled:A,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${$?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${A?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${$?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children: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:Au(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",ds(x.summaryMetadata)?` · ${ds(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:$?"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&&j.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(fl,{size:32})}),t.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":Nu():"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:Iu()})})]}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:t.jsx("button",{onClick:w,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(_s,{size:13})," ",y?Cu():"Refresh History"]})})})]})]});return typeof document>"u"?k:qs.createPortal(k,document.body)}const Ja={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 ji({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=Ja[n.type]||Ja.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(St,{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 Tu=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Mu(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function Lu(e){return e.sessionId||e.instanceId||e.agentType}function un(e,s){return e||s}function Za(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 ki(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=It(r,{fallbackId:r.id}));return s}function Si(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 ua(e,s,r={}){return _u(e,s,Si(e,r))}function _u(e,s,r={}){var f,w,S,T,d,b;const n=[],a=r.machineName,i=r.connectionState,c=Mu(e),l=Xl(e.type,{agentName:e.cliName}),u=et(e)||Xe(e)?l:at(e.type),p=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var h,C;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||at(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:((C=y.activeChat)==null?void 0:C.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,surfaceHidden:y.surfaceHidden}}):[],m=Tu(e);if(m){const y=e.sessionId||e.instanceId,h=l,C=(f=e.activeChat)==null?void 0:f.activeModal,P=C&&Array.isArray(C.buttons)&&C.buttons.length>0,v=wt((w=e.activeChat)==null?void 0:w.status,{activeModal:(S=e.activeChat)==null?void 0:S.activeModal})||wt((d=(T=e.agents)==null?void 0:T[0])==null?void 0:d.status)||"idle",j=e.activeChat||{title:"",messages:[]};let k=j.title&&String(j.title).trim()?String(j.title).trim():"";const g=(b=e.activeChat)==null?void 0:b.id,x=e.chats;if(g&&Array.isArray(x)&&x.length>0){const R=x.find(N=>N.id===g||N.id&&String(N.id)===String(g));R!=null&&R.title&&String(R.title).trim()&&(k=String(R.title).trim())}const $=(et(e)||Xe(e),e.type),A=(et(e)||Xe(e))&&Wa(k,h,$)?"":k,M=j.messages||[],L=Za(s,[e.id,y]),O=Ga(M,L);n.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:et(e)?e.mode||"terminal":"chat",agentName:h,agentType:$,status:v,title:A,messages:[...M,...O],resume:e.resume,hostIdeType:!et(e)&&!Xe(e)?e.type:void 0,workspaceName:c,displayPrimary:A||c||(et(e)?e.mode==="chat"?h:"Terminal":h),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:P?C.buttons:void 0,modalMessage:P?C.message:void 0,streamSource:"native",tabKey:un(y,e.id),machineName:a,connectionState:i})}if(m&&(et(e)||Xe(e)))return n;for(const y of p){const h=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,C=Ql(y),P=Lu(y),v=`${e.id}:${P}`,j=y.title&&String(y.title).trim()||"",k=Wa(j,y.agentName,y.agentType)?"":j,g=y.messages||[],x=Za(s,[v,y.sessionId,y.instanceId]),$=Ga(g,x);(y.transport==="cdp-webview"||y.sessionId||y.providerSessionId||g.length>0||$.length>0||h||k||!["idle","panel_hidden","disconnected","not_monitored"].includes(C))&&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:C,title:k,messages:[...g,...$],hostIdeType:e.type,workspaceName:c,displayPrimary:k||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,v),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 Ru(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 Pu(e,s){const r=Ru(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Ni=[{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:"🏄"}],Ci=[{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:"🧩"}],Ii=[{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:"🟠"}],Du=Ni,Eu=Ci,$u=Ii;function ps(...e){return Kc(Wc(e))}function Bu({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:ps("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 Ai({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(Bu,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:ps("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Pt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:ps("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 Ti({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:ps("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 Ku={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"},Wu={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ou({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:ps("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Ku[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:Wu[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 Hu={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"},Uu={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Fu({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:ps("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Hu[e],r),children:[t.jsx("span",{className:ps("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Uu[e])}),n]})}const $n="adhdev:themechange";function zu(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function bs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function gs(e){return e==="system"?zu():e}function Mi(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Nr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent($n,{detail:{preference:e,theme:s}}))}function Vu(){const e=bs(),s=gs(e);Mi(s),Nr(e,s)}function ma(){const[e,s]=o.useState(bs),[r,n]=o.useState(()=>gs(bs()));o.useEffect(()=>{Mi(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),Nr("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:bs()),n(f==="dark"||f==="light"?f:gs(bs()))},l=u=>{if(u.key!=="theme")return;const p=bs(),m=gs(p);s(p),n(m)};return window.addEventListener($n,c),window.addEventListener("storage",l),()=>{window.removeEventListener($n,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=gs(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Nr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=gs(l);n(u);try{localStorage.setItem("theme",l)}catch{}return Nr(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const eo={dark:"Dark",light:"Light",system:"System"};function Gu({collapsed:e}){const{preference:s,cycleTheme:r}=ma(),n=s==="dark"?t.jsx(xl,{size:16}):s==="light"?t.jsx(hl,{size:16}):t.jsx(bl,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${eo[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:eo[s]})]})}function es({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 qu({onPrefChange:e}){const[s,r]=id(),n=(a,i)=>{r({[a]:i}),e==null||e(a,i)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ur,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:a=>n("globalEnabled",a)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(At,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:a=>n("browserNotifications",a)}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gl,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:a=>n("completionAlert",a)}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(yl,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:a=>n("approvalAlert",a)}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ys,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:a=>n("disconnectAlert",a)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Er(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Yu(e,s){const r=Er(e),n=Er(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 Li(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function zs(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Yu(r,s)>=0)return!1;const n=Er(r),a=Er(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Xu(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function mn(e,s){return e instanceof Error?e.message:s}function Qu({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(Ti,{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(Zu,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function to({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 qs.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 Ju(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Du,...Eu,...$u].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 Zu({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var O,R;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[p,m]=o.useState(null),[f,w]=o.useState("idle"),[S,T]=o.useState(""),d=e.version||null,b=((O=e.machine)==null?void 0:O.platform)||((R=e.system)==null?void 0:R.platform)||"",y=It(e,{fallbackId:e.id}),h=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",C=s.filter(N=>N.daemonId===e.id&&N.transport==="cdp-page"),P=s.filter(N=>N.daemonId===e.id&&N.transport==="pty"),v=s.filter(N=>N.daemonId===e.id&&N.transport==="acp"),j=e.p2p,k=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const N=Xu(await r(e.id,"daemon_upgrade",{}));N.alreadyLatest?(c("done"),u(`Already on v${N.version||"latest"}.`)):N.upgraded||N.success?(c("done"),u(`Upgrade to v${N.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(N.error||"Upgrade failed"))}catch(N){c("error"),u(mn(N,"Connection lost during upgrade"))}}},g=async()=>{if(m(null),!!n){w("loading");try{await n(e.id),w("done"),T("Machine disconnected.")}catch(N){w("error"),T(mn(N,"Failed to disconnect"))}}},x=async()=>{if(m(null),!!a){w("loading");try{await a(e.id),w("done"),T("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(N){w("error"),T(mn(N,"Failed to revoke token"))}}},$="0.8.70",A=Li(e,$),M=zs(e,$),L=C.length+P.length+v.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] ${A?"":"bg-bg-secondary"}`,style:A?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",d,!A&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&A&&t.jsx("button",{onClick:k,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${$}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${M?"↑ Update now":`↑ Update${` to v${$}`}`}`}),n&&t.jsx("button",{onClick:()=>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(Fu,{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:[j&&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 ${j.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${j.state==="connecting"||j.state==="new"?"animate-pulse":""}`,style:j.state==="connecting"||j.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",j.state==="connected"?"connected":j.state==="connecting"||j.state==="new"?"connecting...":j.state||"off"]}),j.peers!==void 0&&j.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",j.peers," peer",j.peers!==1?"s":"",")"]})]}),j&&L>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),L>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[C.map(N=>{const U=Ju(N.type),G=N.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:U.icon}),t.jsx("span",{children:U.name}),G!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${G?"bg-green-400":"animate-pulse"}`,style:G?void 0:{background:"var(--status-warning)"},title:G?"CDP connected":"CDP connecting..."})]},N.id)}),P.map(N=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:N.cliName||"CLI"})]},N.id)),v.map(N=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:N.cliName||"ACP"})]},N.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||S)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-red-400":i==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:S||l})]}),p==="disconnect"&&t.jsx(to,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
33
+
34
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
35
+
36
+ Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:g,onCancel:()=>m(null)}),p==="revoke"&&t.jsx(to,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
37
+
38
+ This will:
39
+ • Immediately disconnect the machine
40
+ • Delete the machine registration
41
+ • Require restarting ADHDev on that machine
42
+
43
+ Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:x,onCancel:()=>m(null)})]})}const em=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function tm(){const{preference:e,setPreference:s}=ma();return t.jsx("div",{className:"flex gap-2",children:em.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 sm(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 rm(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function pn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function so(e){const{r:s,g:r,b:n}=rm(e);return .2126*pn(s)+.7152*pn(r)+.0722*pn(n)}function ro(e,s){const r=so(e),n=so(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function _i(e){const s=sm(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return ro(s,r)>=ro(s,n)?r:n}const Bn={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},Kn={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},nm=[{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"}}}],Ri="adhdev-chat-theme",Pi="adhdev-chat-theme-custom";function Cr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ri)||"ember"}catch{return"ember"}}function Et(e){try{const s=localStorage.getItem(Pi);if(s){const r=JSON.parse(s);return{...e==="dark"?Bn:Kn,...r[e]}}}catch{}return e==="dark"?Bn:Kn}function pr(e,s){try{localStorage.setItem(Pi,JSON.stringify({dark:e,light:s}))}catch{}}function Lt(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 $r(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),a=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const am={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Vs(e,s){var a;const r=(a=am[e])==null?void 0:a[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",$r(r,24)),n.style.setProperty("--accent-on-primary",_i(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${$r(r,18)})`),n.style.setProperty("--border-accent",Lt(r,.35)),n.style.setProperty("--nav-active-bg",Lt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Lt(r,.06)}`)}function ns(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Lt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Lt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Lt(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",Lt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Lt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",$r(e.accentColor,30)),s.style.setProperty("--accent-on-primary",_i(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${$r(e.accentColor,40)})`),s.style.setProperty("--border-accent",Lt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Lt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Lt(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 ${Lt(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 pa(){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 om(e){try{localStorage.setItem(Ri,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Et(s))}else pa(),Vs(e,as()?"dark":"light")}function im(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Cr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=as()?"dark":"light";ns(Et(s))}else pa(),Vs(e,as()?"dark":"light")}function as(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function vt({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function $s({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 cm({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Et(r));o.useEffect(()=>{a(Et(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const p={...u,[c]:l},f=Et(r==="dark"?"light":"dark");return r==="dark"?pr(p,f):pr(f,p),ns(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($s,{title:"App Background",children:[t.jsx(vt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(vt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(vt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs($s,{title:"App Text",children:[t.jsx(vt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(vt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(vt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs($s,{title:"Borders & Accent",children:[t.jsx(vt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(vt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(vt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs($s,{title:"Chat Bubbles",children:[t.jsx(vt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(vt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(vt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(vt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs($s,{title:"Chat Layout",children:[t.jsx(vt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(vt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(vt,{label:"Input border",value:n.inputBorder,onChange:c=>i("inputBorder",c)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const c=e?Bn:Kn,u=Et(e?"light":"dark");e?pr(c,u):pr(u,c),a(c),ns(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 lm(){const[e,s]=o.useState(Cr),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Et("dark"));o.useEffect(()=>{n(as());const u=new MutationObserver(()=>{const f=as();n(f);const w=Cr();w==="custom"?ns(Et(f?"dark":"light")):Vs(w,f?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=as();n(f);const w=Cr();w==="custom"?ns(Et(f?"dark":"light")):Vs(w,f?"dark":"light")};return p.addEventListener("change",m),()=>{u.disconnect(),p.removeEventListener("change",m)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ns(Et(r?"dark":"light")):(pa(),Vs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Et(r?"dark":"light"))},[r]);const c=u=>{s(u),om(u)},l=[...nm,{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(cm,{dark:r,onColorsChange:u=>i(u)})]})}const Di="adhdev_mobileDashboardMode_v1";function Ei(){try{return localStorage.getItem(Di)==="workspace"?"workspace":"chat"}catch{return"chat"}}function dm(e){try{localStorage.setItem(Di,e)}catch{}}function um(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(Ei()==="chat")},[]),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ht,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{s(r),dm(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function mm(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 pm(e,s){const{sendData:r}=Tt(),{injectEntries:n,getIdes:a}=Lr(),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=>Gt.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const m=a().find(w=>w.id===u),f=mm(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 fm=4e3;function $i(e,s){const{sendData:r}=Tt(),[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=Gt.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)},fm):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 hm(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Bi(e){const{sendData:s}=Tt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=hm(e);if(!a||!e.sessionId||!s){n({});return}const i=Gt.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 Ki="adhdev_hiddenTabs";function xm(){try{const e=localStorage.getItem(Ki);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function hs(e){try{localStorage.setItem(Ki,JSON.stringify([...e]))}catch{}}function bm(){const[e,s]=o.useState(xm),r=o.useCallback(p=>{s(m=>{const f=new Set(m);return f.has(p)?f.delete(p):f.add(p),hs(f),f})},[]),n=o.useCallback(p=>{s(m=>{if(m.has(p))return m;const f=new Set(m);return f.add(p),hs(f),f})},[]),a=o.useCallback(p=>{s(m=>{if(!m.has(p))return m;const f=new Set(m);return f.delete(p),hs(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const m=new Set;return hs(m),m})},[]),c=o.useCallback((p,m)=>{s(f=>{const w=new Set(f);for(const S of m)w.add(S);return hs(w),w})},[]),l=o.useCallback((p,m)=>{s(f=>{const w=new Set(f);for(const S of m)w.delete(S);return hs(w),w})},[]),u=o.useCallback(p=>e.has(p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function no(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 gm(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=no(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>no(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Wi(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 ym(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))Wi(s,a)===i&&(delete n[a],r=!0);return r?n:e}function vm({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{ld()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:bi(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return ud(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 wm(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function os(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||wm(s==null?void 0:s.receivedAt)||0}function Wn(e,s=0){return os(e)||e.lastUpdated||s||0}function Oi(e){return os(e)||e.lastUpdated||0}function Hi(e,s,r=Oi){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 On(e){var r;const s=wt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function jm(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!On(e)&&!e.title.trim()}function km(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(On(r))-Number(On(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Hi(s,r)})[0]||null}function Bt(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=km(a);return n?i&&jm(n)?i:n:i||r[0]||null}function Sm(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 fn(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 Nm(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 ao(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?Nm(Ns(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 Cm(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||""),ao(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),ao(r.activeChat)].join(":"))].join("|")}function Im(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 Am(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 Tm(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 Mm(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Lm(e){const s=Mm(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=Ns(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function _m({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>Sm(e),[e]),c=o.useMemo(()=>ki(e),[e]),l=o.useRef([]),u=o.useRef([]),p=o.useRef([]),m=o.useRef(new Map),f=o.useRef(new Map),w=o.useMemo(()=>{const v=new Map,j=[];for(const $ of i){const{connectionState:A="new",machineName:M}=Si($,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),L=Am($,r),O=Cm($),R=m.current.get($.id);if(R&&R.ide===$&&R.sourceSignature===O&&R.connectionState===A&&R.machineName===M&&Tm(R.localRefs,L)){v.set($.id,R),j.push(...R.conversations);continue}const N=ua($,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),U={ide:$,sourceSignature:O,connectionState:A,machineName:M,localRefs:L,conversations:N};v.set($.id,U),j.push(...N)}m.current=v;const k=new Map,g=$=>{const A=Lm($),M=f.current.get($.tabKey);if(M&&M.signature===A)return k.set($.tabKey,M),M.timestamp;const L={signature:A,timestamp:Oi($)||(M==null?void 0:M.timestamp)||0};return k.set($.tabKey,L),L.timestamp},x=[...j].sort(($,A)=>Hi($,A,g));return f.current=k,x},[i,r,s,c]),S=o.useMemo(()=>{const v=Im(w,n);return fn(l.current,v)?l.current:(l.current=v,v)},[w,n]),T=o.useMemo(()=>{const v=new Map,j=Array.from(new Set(S.map(k=>k.routeId)));for(const k of j){const g=Bt(S,k);g&&v.set(k,g)}return v},[S]),d=o.useMemo(()=>{const v=new Map;for(const j of S)if(j.sessionId&&v.set(j.sessionId,j),j.streamSource==="native"&&j.sessionId){const k=T.get(j.routeId);k&&v.set(j.sessionId,k)}return v},[S,T]),b=o.useMemo(()=>{const v=new Map;for(const j of S)j.sessionId&&v.set(j.sessionId,j),v.set(j.routeId,T.get(j.routeId)||j),v.set(j.tabKey,j);return v},[S,T]),y=o.useCallback(v=>{if(v)return d.get(v)},[d]),h=o.useCallback(v=>{if(v)return b.get(v)},[b]),C=o.useMemo(()=>{const v=S.filter(j=>!a.has(j.tabKey));return fn(u.current,v)?u.current:(u.current=v,v)},[S,a]),P=o.useMemo(()=>{const v=C.map(j=>j.tabKey);return fn(p.current,v)?p.current:(p.current=v,v)},[C]);return{chatIdes:i,conversations:S,visibleConversations:C,visibleTabKeys:P,resolveConversationBySessionId:y,resolveConversationByTarget:h}}function Rm({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 Pm({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{ot.setIdes(e)},[e]),o.useEffect(()=>{ot.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=ot.onToast(u=>{r(m=>m.some(w=>w.message===u.message&&u.timestamp-w.timestamp<3e3)?m:[...m.slice(-4),{id:u.id,message:u.message,type:u.type,timestamp:u.timestamp,targetKey:u.targetKey,actions:u.actions}]);const p=u.duration||5e3;setTimeout(()=>r(m=>m.filter(f=>f.id!==u.id)),p)}),c=ot.onSystemMessage((u,p)=>{var S,T;const m=a(u),f=(S=p._localId)==null?void 0:S.startsWith("sys_approval_"),w=!!(m&&(m.status==="waiting_approval"||(T=m.modalButtons)!=null&&T.length||m.modalMessage));f&&w||n(d=>({...d,[u]:[...d[u]||[],p]}))}),l=ot.onClearSystemMessage((u,p)=>{n(m=>{var f;return(f=m[u])!=null&&f.length?{...m,[u]:m[u].filter(w=>{var S;return!(w.role==="system"&&((S=w._localId)!=null&&S.startsWith(p)))})}:m})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=fi.on("status_event",c=>{ot.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var b;const u=l.data;if((u==null?void 0:u.type)!=="notification_action"||typeof u.action!="string"||!u.action.startsWith("approval_")||!(u.daemonId||u.targetSessionId||u.targetKey))return;const p=u.targetSessionId||u.targetKey||u.daemonId,m=a(p),f=(m==null?void 0:m.routeId)||u.daemonId;if(!f)return;const w=Number(u.buttonIndex),S=u.button||((b=m==null?void 0:m.modalButtons)==null?void 0:b[w])||"Approve",T=String(S).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(T);s(f,"resolve_action",{action:d?"approve":"reject",button:S,...Number.isFinite(w)&&{buttonIndex:w},...(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 Dm="adhdev_dashboardLayout_v1",Em="adhdev_dashboardDockview_v1",$m="adhdev_dashboardDockviewHiddenRestore_v1",Bs={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function fa(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function Ui(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Fi(e){return`${Dm}:${e}`}function Bm(e){const s=Fi(e);return fa(s,null)}function Km(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=Fi(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function zi(e){return`${Em}:${e}`}function Wm(e){const s=zi(e);return fa(s,null)}function Om(e,s){try{const r=zi(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Vi(e){return`${$m}:${e}`}function Hm(e){const s=Vi(e);return fa(s,{})}function Um(e,s){try{const r=Vi(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Fm(){return{groupAssignments:[...Bs.groupAssignments],focusedGroup:Bs.focusedGroup,groupActiveTabIds:{...Bs.groupActiveTabIds},groupTabOrders:{...Bs.groupTabOrders},groupSizes:[...Bs.groupSizes]}}function zm(){const[e]=o.useState(()=>Ui(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[p,m]=o.useState([]),[f,w]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,T]=o.useState(!1),d=o.useCallback(()=>{if(S)return;const b=Bm(e)??Fm();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),u(b.groupTabOrders),m(b.groupSizes),T(!0)},[S,e]);return o.useEffect(()=>{S&&Km(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:p})},[S,e,s,n,i,l,p]),o.useEffect(()=>{const b=window.matchMedia("(max-width: 767px)"),y=h=>w(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:S,hydrateStoredLayout:d}}function Vm(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=[s.providerSessionId,s.sessionId].filter(a=>typeof a=="string"&&a.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Gm({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:p,activeConv:m,isRefreshingHistory:f,ides:w,handleRefreshHistory:S}){const T=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),y=o.useRef(!1);o.useEffect(()=>{if(!e||T.current||s.length===0)return;if(!a){i();return}const h=r(e);if(!h)return;const C=n.get(h.tabKey)??0;c(P=>({...P,[C]:h.tabKey})),l(C),T.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),u(P=>{const v=new URLSearchParams(P);return v.delete("activeTab"),v},{replace:!0})},[e,s,r,n,a,i,c,l,u]),o.useEffect(()=>{if(!(d.current||a)&&s.length!==0){if(!e){i(),d.current=!0;return}if(T.current){d.current=!0;return}if(b.current==null)return b.current=window.setTimeout(()=>{b.current=null,!(d.current||a)&&(i(),d.current=!0)},1500),()=>{b.current!=null&&(window.clearTimeout(b.current),b.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!p){y.current=!1;return}if(!m||y.current||f)return;const h=w.find(C=>C.id===m.routeId);h&&(!h.chats||h.chats.length===0||Vm(h.chats,m))&&(y.current=!0,S())},[p,m,f,w,S]),o.useEffect(()=>{if(!m)return;let h=null,C=0,P=-1,v=0;const j=()=>{h=null;const k=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(x=>x.offsetParent!==null);if(k.length===0){C<18&&(C+=1,h=requestAnimationFrame(j));return}let g=0;for(const x of k)x.scrollTop=x.scrollHeight,g+=x.scrollHeight;g===P?v+=1:(v=0,P=g),C+=1,!(v>=2||C>=18)&&(h=requestAnimationFrame(j))};return h=requestAnimationFrame(j),()=>{h!=null&&cancelAnimationFrame(h)}},[m==null?void 0:m.tabKey])}function qm({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,p]=o.useState(null),[m,f]=o.useState(null),w=o.useMemo(()=>{if(e||!n)return null;const y=l(n);return y&&!et(y)&&!Xe(y)?y:null},[e,n,l]),S=o.useMemo(()=>{const y=u==null?void 0:u.routeId;if(!y)return null;const h=u!=null&&u.tabKey?i.find(C=>C.tabKey===u.tabKey):a?i.find(C=>C.tabKey===a):null;return(h==null?void 0:h.routeId)===y?h:Bt(i,y)},[i,u,a]),T=o.useMemo(()=>{if(S)return c.find(y=>y.id===S.routeId)},[c,S]);o.useEffect(()=>{w&&(p({routeId:w.routeId,tabKey:Ua(w)}),f(w),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,w]);const d=o.useCallback(y=>{y&&(p({routeId:y.routeId,tabKey:Ua(y)}),f(y))},[]),b=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:T,remoteDialogActiveConv:m,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:b}}function ws(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:et(e)||Xe(e)?{agentType:Dt(e)}:e.streamSource==="agent-stream"?{agentType:Dt(e)}:s}function Js(e){return e?er(e):""}function Ks(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function hn(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=[s.providerSessionId,s.sessionId].filter(a=>typeof a=="string"&&a.length>0);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function oo({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=o.useState(!1),[p,m]=o.useState(!1),f=o.useCallback(async d=>{try{await e("standalone","launch_ide",{ideType:d,enableCdp:!0})}catch(b){console.error("Launch failed",b)}},[e]),w=o.useCallback(async(d,b)=>{try{const y=d||(s==null?void 0:s.daemonId)||"",h=await e(y,"switch_chat",{id:b,sessionId:b,...ws(s)}),C=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||C==="switched"||C==="switched-by-title")return;C===!1||C==="not_found"?Ks(a,"⚠️ Session tab not found — try refreshing history"):typeof C=="string"&&C.startsWith("error:")?Ks(a,`⚠️ Switch error: ${C}`):Ks(a,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),Ks(a,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,e,a]),S=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const d=Js(s);await e(d,"new_chat",{...ws(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{u(!1)}}},[s,l,e,c,i]),T=o.useCallback(async()=>{var d,b;if(!(!s||p)){m(!0);try{const y=Js(s),h=async()=>e(y,"list_chats",{forceExpand:!0,...ws(s)});let C=await h(),P=(C==null?void 0:C.chats)||((d=C==null?void 0:C.result)==null?void 0:d.chats);hn(P,s)&&(await new Promise(v=>setTimeout(v,450)),C=await h(),P=(C==null?void 0:C.chats)||((b=C==null?void 0:C.result)==null?void 0:b.chats)),C!=null&&C.success&&Array.isArray(P)&&(n(s.routeId,P),hn(P,s)&&!hn(r,s)&&Ks(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:w,handleNewChat:S,handleRefreshHistory:T}}function Ym(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 Xm(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function io(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 fr(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 co(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 Qm(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 Jm(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 lo(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 uo(e){return Array(e).fill(100/e)}function Zm({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(()=>fr(e,p),[e,p]),w=f.assignments,S=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),T=S>1,d=o.useCallback((v,j)=>{s(k=>{const g=new Map(fr(k,p).assignments);return j===0?g.delete(v):g.set(v,j),g}),n(k=>({...k,[j]:v})),r(j)},[s,p,n,r]),b=o.useCallback(v=>{s(j=>{const k=fr(j,p).assignments,g=new Map;for(const[x,$]of k)$!==v&&($>v?g.set(x,$-1):g.set(x,$));return g}),c(j=>{if(j.length<=1)return[];const k=[...j];k.splice(v,1);const g=k.reduce((x,$)=>x+$,0);return g>0?k.map(x=>x/g*100):[]}),r(0)},[s,p,c,r]),y=o.useCallback((v,j)=>{j.preventDefault();const k=m.current;if(!k)return;const g=j.clientX,x=k.offsetWidth,$=i.length===S?[...i]:uo(S),A=L=>{const R=(L.clientX-g)/x*100,N=[...$];N[v]=Math.max(15,$[v]+R),N[v+1]=Math.max(15,$[v+1]-R),c(N)},M=()=>{document.removeEventListener("mousemove",A),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",A),document.addEventListener("mouseup",M)},[i,S,c]),h=o.useCallback((v,j,k)=>{if(S>=4)return;const g=k==="left"?j:j+1;s(x=>{const $=fr(x,p).assignments,A=new Map;for(const M of u){const L=$.get(M.tabKey)??0,O=L>=g?L+1:L;O>0&&A.set(M.tabKey,O)}return g>0&&A.set(v,g),A}),c(x=>{const $=x.length===S?[...x]:uo(S),A=$[j]??100/S,M=Math.max(15,A/2),L=Math.max(15,A/2),O=[...$];O[j]=M,O.splice(g,0,L);const R=O.reduce((N,U)=>N+U,0);return O.map(N=>N/R*100)}),n(x=>{const $=lo(x,g);return $[g]=v,$}),a(x=>{const $=lo(x,g);return $[g]=[v],$}),r(g)},[S,s,p,u,c,n,a,r]);o.useEffect(()=>{Ym(e,w)||s(w)},[e,w,s]),o.useEffect(()=>{const{mapping:v,usedGroups:j}=f;n(k=>{const g=co(k,v);return io(k,g)?k:g}),a(k=>{const g=co(k,v);return io(k,g)?k:g}),r(k=>{const g=l?0:Qm(k,j,v);return k===g?k:g}),c(k=>{const g=l?[]:Jm(k,j,f.groupCount);return Xm(k,g)?k:g})},[f,l,n,a,r,c]);const C=o.useMemo(()=>{const v=Array.from({length:S},()=>[]);for(const j of u){const k=w.get(j.tabKey)??0,g=Math.min(k,S-1);v[g].push(j)}return v},[u,w,S]),P=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:m,normalizedGroupAssignments:w,numGroups:S,isSplitMode:T,groupedConvs:C,moveTabToGroup:d,closeGroup:b,handleResizeStart:y,splitTabRelative:h,clearAllSplits:P}}function ep({ides:e,sendDaemonCommand:s}){const r="0.8.70",n=o.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Li(m,r)).sort((m,f)=>Number(zs(f,r))-Number(zs(m,r))),[r,e]),a=o.useMemo(()=>n.some(m=>zs(m,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),p=o.useCallback(async m=>{var f,w;u(S=>({...S,[m]:"upgrading"}));try{const S=await s(m,"daemon_upgrade",{});(f=S==null?void 0:S.result)!=null&&f.upgraded||(w=S==null?void 0:S.result)!=null&&w.success?u(T=>({...T,[m]:"done"})):u(T=>({...T,[m]:"error"}))}catch{u(S=>({...S,[m]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const Hn="adhdev_dashboard_notifications_v1",ha=80;function Ir(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Br(e){return{...e,createdAt:Ir(e.createdAt),updatedAt:Ir(e.updatedAt,e.createdAt),lastEventAt:Ir(e.lastEventAt,e.updatedAt||e.createdAt)}}function tp(e){return e.providerSessionId||e.sessionId||e.tabKey||e.id}function sp(e){return[e.type,e.providerSessionId||e.sessionId||e.tabKey||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function rp(e,s){const r=Date.now(),n=[];for(const a of e){const i=a.sessionId?s.get(a.sessionId):void 0;if(i!=null&&i.surfaceHidden)continue;const c=(i==null?void 0:i.inboxBucket)||"idle",l=c==="needs_attention"?"needs_attention":c==="task_complete"&&(i!=null&&i.unread)?"task_complete":null;if(!l)continue;const u=Ir(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),p=sp({type:l,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(i==null?void 0:i.lastUpdated)||a.lastUpdated});n.push(Br({id:p,dedupKey:p,type:l,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:a.title||a.displayPrimary||a.agentName||a.tabKey,preview:a.lastMessagePreview||a.displaySecondary||"",createdAt:u,updatedAt:u,lastEventAt:u}))}return n.sort((a,i)=>i.updatedAt-a.updatedAt)}function np(e,s,r=ha){const n=new Map;for(const i of e)i.deletedAt||n.set(i.id,Br(i));for(const i of s){const c=Br(i),l=n.get(c.id);if(!l){n.set(c.id,c);continue}n.set(c.id,{...l,...c,createdAt:l.createdAt,readAt:l.readAt,deletedAt:l.deletedAt})}const a=new Map;for(const i of Array.from(n.values())){if(i.deletedAt)continue;const c=tp(i),l=a.get(c);if(!l){a.set(c,i);continue}(i.updatedAt>l.updatedAt||i.updatedAt===l.updatedAt&&i.createdAt>l.createdAt)&&a.set(c,i)}return Array.from(a.values()).sort((i,c)=>{const l=c.updatedAt-i.updatedAt;return l!==0?l:c.createdAt-i.createdAt}).slice(0,Math.max(0,r))}function ap(e,s,r=Date.now()){return e.map(n=>n.id===s?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function op(e,s){return e.map(r=>{if(r.id!==s)return r;const n={...r};return delete n.readAt,n})}function ip(e,s,r=Date.now()){return e.map(n=>{const a=!!s.sessionId&&n.sessionId===s.sessionId,i=!!s.providerSessionId&&n.providerSessionId===s.providerSessionId,c=!!s.tabKey&&n.tabKey===s.tabKey;return!a&&!i&&!c?n:{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}})}function cp(e,s){return e.filter(r=>r.id!==s)}function lp(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function dp(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=[r.providerSessionId,r.sessionId,r.tabKey].filter(Boolean);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 up(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(Hn),s=e?JSON.parse(e):[];return Array.isArray(s)?s.map(r=>Br(r)).filter(r=>!r.deletedAt):[]}catch{return[]}}function mp(e){if(!(typeof window>"u"))try{const s=e.filter(r=>!r.deletedAt).slice(0,ha);if(s.length===0){window.localStorage.removeItem(Hn);return}window.localStorage.setItem(Hn,JSON.stringify(s))}catch{}}function pp(e,s){return e===s?!0:e.length!==s.length?!1:e.every((r,n)=>{const a=s[n];return a?r.id===a.id&&r.updatedAt===a.updatedAt&&r.createdAt===a.createdAt&&r.readAt===a.readAt&&r.preview===a.preview&&r.title===a.title&&r.deletedAt===a.deletedAt:!1})}function fp(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=ha}=e,a=o.useMemo(()=>rp(s,r),[s,r]),[i,c]=o.useState(()=>up());o.useEffect(()=>{c(S=>{const T=np(S,a,n);return pp(S,T)?S:T})},[a,n]),o.useEffect(()=>{mp(i)},[i]);const l=o.useMemo(()=>lp(i),[i]),u=o.useMemo(()=>dp(i),[i]),p=o.useCallback((S,T)=>{c(d=>ap(d,S,T))},[]),m=o.useCallback(S=>{c(T=>op(T,S))},[]),f=o.useCallback((S,T)=>{c(d=>ip(d,S,T))},[]),w=o.useCallback(S=>{c(T=>cp(T,S))},[]);return{notifications:i,unreadCount:l,notificationStateBySessionId:u,markRead:p,markUnread:m,markTargetRead:f,deleteNotification:w}}function Gi(){return"select_session"}function hp(){return"open_panel"}function xp(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function bp(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function mo(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function xa(e){return e instanceof Error?e.message:String(e||"")}function po(e){const s=xa(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function fo(e,s){const r=xa(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Gr({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),p=o.useRef(!1),m=o.useRef(null),f=o.useCallback(async d=>{if(!s)return;const b=d.trim();if(!b||p.current)return;const y=Date.now(),h={tabKey:s.tabKey,message:b,timestamp:y};if(xp(m.current,h))return;p.current=!0,u(!0),m.current=h;const C=`${y}-${Math.random().toString(36).slice(2,8)}`,P={role:"user",content:b,timestamp:y,_localId:C},v=!(et(s)||Xe(s));v&&r(j=>({...j,[h.tabKey]:[...j[h.tabKey]||[],P]}));try{const j=Js(s);if(!j)return;const k=await e(j,"send_chat",{message:b,...ws(s)}),g=mo(k);if(v&&(g!=null&&g.deduplicated||(g==null?void 0:g.sent)===!1)){r(x=>({...x,[h.tabKey]:(x[h.tabKey]||[]).filter($=>$._localId!==C)}));return}if((g==null?void 0:g.success)===!1)throw new Error((g==null?void 0:g.error)||"Send failed");setTimeout(()=>{const x=Date.now()-6e4;r($=>{const A=$[h.tabKey];if(!A)return $;const M=A.filter(L=>L.timestamp>x);return M.length===A.length?$:{...$,[h.tabKey]:M}})},6e4)}catch(j){const k=xa(j);k.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",k):console.error("Send failed",j),m.current=bp(m.current,h),v&&r(g=>({...g,[h.tabKey]:(g[h.tabKey]||[]).filter(x=>x._localId!==C)})),n(g=>[...g,{routeId:h.tabKey,text:`❌ **Send failed** — ${k||"Unknown error"}`,timestamp:Date.now()}])}finally{p.current=!1,u(!1)}},[s,e,n,r]),w=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(d){console.error("Relaunch failed",d)}},[s,e]),S=o.useCallback(async d=>{if(s)try{const y=(s.modalButtons||[]).indexOf(d),h=d.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),C=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(h),P=Js(s);if(!P)return;const v=await e(P,"resolve_action",{button:d,action:C?"approve":"reject",...y>=0&&{buttonIndex:y},...ws(s)}),j=mo(v);j.success||n(k=>[...k,{routeId:s.tabKey,text:fo(d,j==null?void 0:j.error),timestamp:Date.now()}])}catch(b){po(b)||console.error("[ModalButton] Error:",b),n(y=>[...y,{routeId:s.tabKey,text:po(b)?fo(d,b):`❌ **${d}** error`,timestamp:Date.now()}])}},[s,e,n]),T=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,hp(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(d){console.error("Focus agent failed",d)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,isFocusingAgent:i,handleSendChat:f,handleRelaunch:w,handleModalButton:S,handleFocusAgent:T}}const ba=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:p,handleFocusAgent:m,isFocusingAgent:f,actionLogs:w,userName:S,scrollToBottomRequestNonce:T,isInputActive:d=!0}){const b=Bi(s),y=b.status||b.modalMessage||b.modalButtons?{...s,...b.status?{status:b.status}:{},...b.modalMessage!==void 0?{modalMessage:b.modalMessage}:{},...b.modalButtons!==void 0?{modalButtons:b.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(Qo,{activeConv:y,onModalButton:c}),y.transport!=="pty"&&y.transport!=="acp"&&y.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(ls,{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,y.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(pu,{activeConv:y,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:p,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(En,{activeConv:y,ideEntry:a,handleSendChat:u,isSendingChat:p,handleFocusAgent:m,isFocusingAgent:f,actionLogs:w,userName:S,scrollToBottomRequestNonce:T,isInputActive:d})})]}):t.jsx(En,{activeConv:y,ideEntry:a,handleSendChat:u,isSendingChat:p,handleFocusAgent:m,isFocusingAgent:f,actionLogs:w,userName:S,scrollToBottomRequestNonce:T,isInputActive:d})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function gp({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,isFocusingAgent:l,onBack:u,onOpenNativeConversation:p,onOpenMachine:m,onOpenHistory:f,onOpenRemote:w,onHideConversation:S,onStopCli:T,cliViewMode:d,onSetCliViewMode:b,handleSendChat:y,handleFocusAgent:h,handleModalButton:C,handleRelaunch:P}){const v=o.useRef(null),j=et(e)&&!s,k=j&&d==="terminal",g=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${g} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:u,type:"button","aria-label":"Back",children:t.jsx(qn,{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:it(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(ci,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>p(e),onOpenMachine:()=>m(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&d&&t.jsx(aa,{mode:d,onChange:b,compact:!0}),j&&T&&t.jsx("button",{onClick:()=>{T(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(St,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:t.jsx(Xn,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:t.jsx(At,{size:14})}),S&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Close chat",children:t.jsx(St,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(ba,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:v,handleModalButton:C,handleRelaunch:P,handleSendChat:y,isSendingChat:c,handleFocusAgent:h,isFocusingAgent:l,actionLogs:a,userName:i})})]})}const xn={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 yp(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function qi(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(yp())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(xn[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:xn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:xn[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 Yi({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:At},{key:"chats",label:"Chats",icon:Ht}];return t.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:t.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:i})=>{const c=e===n;return t.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${c?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>s(n),type:"button","aria-pressed":c,children:[t.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${c?"text-accent-primary":"bg-transparent text-current"}`,style:c?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:t.jsx(i,{size:15})}),t.jsx("span",{children:a})]},n)})})})}function hr({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 xs({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 Ws({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 xr({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}=Rs(e.conversation),m=it(e.conversation),f=ms(e.conversation),w=xi(e.conversation,{requiresAction:s==="needs_attention"}),S=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",T=a?"bg-accent-primary shadow-glow":i?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":c?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",d=c?"text-text-secondary":"text-text-primary",b=c?"text-text-muted":"text-text-secondary",y=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",C="text-[color:var(--status-warning)]";return t.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${S}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${T}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(m)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${d}`,children:m}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${h}`,children:Xo(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[f,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${C} animate-pulse`,children:"Reconnecting…"})]}):p?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):w==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:C,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${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 ho({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 vp({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:p,onShowAllHidden:m,onOpenNewSession:f,onOpenMachine:w,onOpenSettings:S,onSectionChange:T,wsStatus:d="connected",isStandalone:b=!1}){const y=d==="disconnected"||d==="reconnecting"||d==="offline"||d==="auth_failed",h=c.length>0,C=s.length>0||r.length>0||n.length>0||a.length>0,P=e==="machines"?"Machines":"Chats",v=b?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",j=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 ${v}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:P}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[t.jsx(Ur,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:S,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(Or,{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] ${j}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:y?t.jsx(Ws,{icon:t.jsx(ho,{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(Ws,{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(qi,{})})}):t.jsx(xs,{children:c.map((k,g)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${g>0?"border-t border-border-subtle/70":""}`,onClick:()=>w(k.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(k.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:k.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:k.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[k.unread," new"]}):k.total>0?`${k.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:k.subtitle}),k.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[k.total," chat",k.total!==1?"s":"",k.unread>0?` · ${k.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},k.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(hr,{title:"Needs attention",className:"mb-0"}),t.jsx(xs,{children:s.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(xr,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(hr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(xs,{children:r.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(xr,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(hr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(xs,{children:n.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(xr,{item:k,type:"working",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(hr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(xs,{children:a.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(xr,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:u})},k.conversation.tabKey))}):C?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):y?t.jsx(Ws,{icon:t.jsx(ho,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(Ws,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Ht,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(Ws,{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(xs,{className:"bg-bg-secondary/25",children:i.map((k,g)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${g>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(k),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(it(k))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:it(k)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:ms(k)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},k.tabKey))})]})]}),e==="chats"&&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(Yi,{section:e,onSectionChange:T})]})}function wp(e){if(!e)return"";try{return new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(e))}catch{return new Date(e).toLocaleString()}}function Xi(e){const s=[e.workspace||"Workspace unknown"],r=ds(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=wp(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function qr(...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 jp(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 Yr(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=jp(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 kp(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 Sp(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Xr(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=Sp(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 Qr({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:p}){const[m,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const w=kp(r),S=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(St,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!w||a||u(w)},disabled:!w||a,children:[t.jsx(qn,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:m,onChange:T=>f(T.target.value),onKeyDown:T=>{T.key!=="Enter"||!S||a||(T.preventDefault(),u(S))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!S||a||u(S)},disabled:!S||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(T=>t.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(T.path),children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Ss,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:T.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:T.path})]})]},T.path))})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:l,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(S||r),disabled:!S&&!r||a,children:c})]})]})})}function ga({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:p,argsValue:m,onArgsChange:f,showModelInput:w,modelValue:S,onModelChange:T,historyProviderNode:d,onConfirm:b,onCancel:y}){const h=n==null?void 0:n.find(C=>C.key===a);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":"Close launch confirmation",children:t.jsx(St,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:a||"",onChange:C=>i(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(C=>t.jsx("option",{value:C.key,children:C.label},C.key))}),(h==null?void 0:h.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),d,r.map(C=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:C.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:C.value})]},`${C.label}:${C.value}`)),w&&T&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:S||"",onChange:C=>T(C.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&f&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:m||"",onChange:C=>f(C.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick: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(Qn,{size:14}),u?l:c]})]})]})})}function xo(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function is(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?"⭐ ":""}${xo(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:xo(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 Np(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Cp(e){return[Np(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Ip(e){return e.lastLaunchedAt?Fr(e.lastLaunchedAt):""}function Qi(e){return{metaText:Cp(e),updatedLabel:Ip(e)}}function bn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function Ap({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var mt,tt,xt,pt;const c=tr(),[l,u]=o.useState(!1),p=(((mt=e.detectedIdes)==null?void 0:mt.length)||0)>0,m=o.useMemo(()=>(e.workspaces||[]).map(ce=>({id:ce.id,path:ce.path,label:ce.label})),[e]),f=e.defaultWorkspaceId||null,[w,S]=o.useState(f||((tt=m[0])==null?void 0:tt.id)||""),[T,d]=o.useState(""),[b,y]=o.useState(""),[h,C]=o.useState([]),[P,v]=o.useState(!1),[j,k]=o.useState(""),[g,x]=o.useState(!1),[$,A]=o.useState(bn(p,s.length,r.length)),M=o.useRef(null),[L,O]=o.useState(null),R=o.useRef("__home__"),[N,U]=o.useState("__home__"),[G,I]=o.useState(""),[B,D]=o.useState(""),[W,X]=o.useState(""),[we,Le]=o.useState([]),[ie,Ie]=o.useState(()=>gt().textQuery),[te,de]=o.useState(()=>gt().workspaceQuery),[ae,ge]=o.useState(()=>gt().modelQuery),[oe,F]=o.useState(()=>gt().resumableOnly),[xe,se]=o.useState(()=>gt().sortMode),[pe,Z]=o.useState(!1),[le,ne]=o.useState(!1),be=o.useRef(null),me=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const E=w==="__custom__"?T.trim():((xt=m.find(ce=>ce.id===w))==null?void 0:xt.path)||"",ye=w==="__custom__"&&!!E&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),he=w!=="__custom__"&&((pt=m.find(ce=>ce.id===w))==null?void 0:pt.path)||"",ke=o.useMemo(()=>(e.recentLaunches||[]).map(ce=>ce.workspace),[e]),J=o.useCallback(async ce=>{v(!0),k("");try{const Ve=await a(ce);y(Ve.path),d(Ve.path),C(Ve.directories)}catch(Ve){k(Ve instanceof Error?Ve.message:"Could not load folder")}finally{v(!1)}},[a]),Se=o.useCallback(()=>{var Ve;S("__custom__"),x(!0);const ce=Yr(e.platform,qr(T.trim(),he,ke,e.defaultWorkspacePath,(Ve=m.find(ct=>ct.id===f))==null?void 0:Ve.path,m.map(ct=>ct.path)));J(ce)},[T,f,J,ke,he,e.platform,m]),Ue=o.useCallback(ce=>{if(ce!=null&&ce.workspaceId){S(ce.workspaceId),d("");return}if(ce!=null&&ce.workspacePath){S("__custom__"),d(ce.workspacePath);return}S(""),d("")},[]),De=o.useCallback(ce=>{if(S(ce),ce==="__custom__"){Se();return}d("")},[Se]),Ge=o.useCallback(ce=>{S("__custom__"),d(ce)},[]),Qe=o.useCallback((ce,Ve)=>{M.current=Ve,R.current=ce.selectedWorkspaceKey||"__home__",U(ce.selectedWorkspaceKey||"__home__"),I(ce.initialArgs||""),D(ce.initialModel||""),X(""),Le([]);const ct=ce.providerType?`${e.id}:${ce.providerType}`:null;if(bu(me.current,ct)){const Je=gt();Ie(Je.textQuery),de(Je.workspaceQuery),ge(Je.modelQuery),F(Je.resumableOnly),se(Je.sortMode)}me.current=ct,O(ce),ce.providerType&&i&&(Z(!0),i(ce.providerType).then(Je=>Le(Je||[])).catch(Je=>console.warn("Failed to load saved sessions",Je)).finally(()=>Z(!1)))},[i,e.id]),Ze=o.useMemo(()=>yi(we,{textQuery:ie,workspaceQuery:te,modelQuery:ae,resumableOnly:oe,sortMode:xe}),[ae,oe,we,xe,ie,te]);o.useEffect(()=>{W&&(Ze.some(ce=>ce.providerSessionId===W)||X(""))},[Ze,W]);const ut=o.useCallback(()=>{M.current&&(ne(!0),M.current().finally(()=>{M.current=null,ne(!1),O(null)}))},[]),qe=o.useCallback(()=>{M.current=null,O(null)},[]),ht=o.useCallback(ce=>{R.current=ce,U(ce)},[]);return o.useEffect(()=>{var ce;be.current!==e.id&&(be.current=e.id,S(f||((ce=m[0])==null?void 0:ce.id)||"__custom__"),d(""),y(""),C([]),k(""),x(!1),Ie(gt().textQuery),de(gt().workspaceQuery),ge(gt().modelQuery),F(gt().resumableOnly),se(gt().sortMode),me.current=null,A(bn(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,m]),o.useEffect(()=>{var ce;w!=="__custom__"&&(w&&m.some(Ve=>Ve.id===w)||S(f||((ce=m[0])==null?void 0:ce.id)||"__custom__"))},[f,w,m]),o.useEffect(()=>{$==="ide"&&p||$==="cli"&&s.length>0||$==="acp"&&r.length>0||A(bn(p,s.length,r.length))},[$,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:m,defaultWorkspaceId:f,workspaceChoice:w,customWorkspacePath:T,browseCurrentPath:b,browseDirectories:h,browseBusy:P,browseError:j,browseDialogOpen:g,activeLauncherKind:$,launchConfirm:L,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:N,launchConfirmArgs:G,launchConfirmModel:B,launchConfirmResumeId:W,launchConfirmSavedSessions:we,launchConfirmTextFilter:ie,launchConfirmWorkspaceFilter:te,launchConfirmModelFilter:ae,launchConfirmResumableOnly:oe,launchConfirmSortMode:xe,filteredLaunchConfirmSavedSessions:Ze,launchConfirmSessionsLoading:pe,launchConfirmBusy:le,resolvedWorkspacePath:E,canCreateMissingWorkspace:ye,openBrowseDialog:Se,loadBrowsePath:J,handleWorkspaceChoiceChange:De,chooseCustomWorkspacePath:Ge,setCustomWorkspacePath:d,setBrowseDialogOpen:x,setActiveLauncherKind:A,openLaunchConfirm:Qe,handleConfirmLaunch:ut,closeLaunchConfirm:qe,setWorkspaceSelectionFromOption:Ue,setLaunchConfirmWorkspaceKeyAndSync:ht,setLaunchConfirmArgs:I,setLaunchConfirmModel:D,setLaunchConfirmResumeId:X,setLaunchConfirmTextFilter:Ie,setLaunchConfirmWorkspaceFilter:de,setLaunchConfirmModelFilter:ge,setLaunchConfirmResumableOnly:F,setLaunchConfirmSortMode:se}}function Tp({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:p,showBottomNav:m,onBack:f,onSectionChange:w,onOpenConversation:S,onOpenRecent:T,onOpenMachineDetails:d,onMachineUpgrade:b,onLaunchDetectedIde:y,onAddWorkspace:h,onBrowseDirectory:C,onLaunchWorkspaceProvider:P,onListSavedSessions:v}){const j=N=>N==="ide"?"IDE":N==="cli"?"CLI":"ACP",k=r.slice(0,4),g=s.slice(0,3),x=Ap({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:v}),$=o.useMemo(()=>k.map(N=>{const{metaText:U,updatedLabel:G}=Qi(N);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:U,updatedLabel:G,onClick:()=>{const{options:I,selectedKey:B}=is({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:N.workspace});x.openLaunchConfirm({title:N.kind==="ide"?ss("restart-ide",N.label):N.providerSessionId?ca(N.label):ss("start-fresh",N.label),description:N.kind==="ide"?rs("restart-ide"):N.providerSessionId?la():rs("start-fresh"),confirmLabel:N.kind==="ide"?Ts("restart-ide"):N.providerSessionId?Dr(!0):Ts("start-fresh"),busyLabel:N.kind==="ide"?Ms("restart-ide"):N.providerSessionId?oa(!0):Ms("start-fresh"),workspaceOptions:I,selectedWorkspaceKey:B,details:[{label:"Mode",value:j(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const D=I.find(W=>W.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),await T({...N,workspace:(D==null?void 0:D.workspacePath)??null})})}}}),[x,T,k]),A=o.useMemo(()=>g.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:it(N.conversation),secondary:lu(N.conversation,{timestampLabel:N.timestamp?Xo(N.timestamp):null}),unread:N.unread,onClick:()=>S(N.conversation)})),[S,g]),M=x.showAllRecent?$:$.slice(0,4),L=$.length>0,O=A.length>0,R=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${R} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:f,type:"button","aria-label":"Back",children:t.jsx(qn,{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:It(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[O&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:A.map(N=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${N.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:N.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:N.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))})]}),L&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:M.map(N=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:N.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:N.primary}),N.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:N.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:N.secondary})]},N.key))}),$.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>x.setShowAllRecent(N=>!N),children:x.showAllRecent?"Show fewer":`Show ${$.length-4} more`})})]}),(x.hasIdeOptions||n.length>0||a.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.jsxs("div",{className:"flex flex-col gap-2.5 w-full p-3.5 rounded-2xl border border-border-default/80 bg-surface-primary/90",children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:x.workspaceChoice,onChange:N=>x.handleWorkspaceChoiceChange(N.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:x.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[x.workspaceRows.map(N=>t.jsxs("option",{value:N.id,children:[N.id===x.defaultWorkspaceId?"⭐ ":"",Vr(N.path,N.label)||N.path]},N.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),x.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Ss,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:x.resolvedWorkspacePath||x.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:x.openBrowseDialog,children:"Select workspace…"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{x.resolvedWorkspacePath&&h(x.resolvedWorkspacePath)},disabled:!x.resolvedWorkspacePath||x.browseBusy,children:"Save as workspace"})]})]}),x.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[x.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>x.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>x.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${x.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>x.setActiveLauncherKind("acp"),children:"ACP"})]}),x.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:x.activeLauncherKind==="ide"?"Choose an IDE":x.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:x.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(N=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:U,selectedKey:G}=is({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${N.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:U,selectedWorkspaceKey:G,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:N.name}]},async()=>{const I=U.find(B=>B.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(I),y(N.type,{workspacePath:(I==null?void 0:I.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:N.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},N.type)):(x.activeLauncherKind==="cli"?n:a).map(N=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const U=x.activeLauncherKind==="cli"?"cli":"acp",{options:G,selectedKey:I}=is({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspaceId:x.workspaceChoice!=="__custom__"?x.workspaceChoice:null,currentWorkspacePath:x.resolvedWorkspacePath});x.openLaunchConfirm({title:`Launch ${N.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${U.toUpperCase()}`,workspaceOptions:G,selectedWorkspaceKey:I,details:[{label:"Mode",value:U.toUpperCase()},{label:"Provider",value:N.displayName}],showArgsInput:!0,showModelInput:U==="acp",initialArgs:"",initialModel:"",providerType:N.type},async()=>{const B=G.find(D=>D.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(B),P(U,N.type,{workspaceId:(B==null?void 0:B.workspaceId)??null,workspacePath:(B==null?void 0:B.workspacePath)??null,args:x.launchConfirmArgs,model:x.launchConfirmModel,resumeSessionId:x.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[N.icon?`${N.icon} `:"",N.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},N.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,x.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>h(x.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:b,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:d,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),x.browseDialogOpen&&t.jsx(Qr,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:x.browseCurrentPath,directories:x.browseDirectories,busy:x.browseBusy,error:x.browseError,confirmLabel:"Use this folder",onClose:()=>x.setBrowseDialogOpen(!1),onNavigate:N=>{x.loadBrowsePath(N)},onConfirm:N=>{x.chooseCustomWorkspacePath(N),x.setBrowseDialogOpen(!1)}}),x.launchConfirm&&t.jsx(ga,{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?Dr(!!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:ia()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:x.launchConfirmTextFilter,onChange:N=>x.setLaunchConfirmTextFilter(N.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmWorkspaceFilter,onChange:N=>x.setLaunchConfirmWorkspaceFilter(N.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:x.launchConfirmModelFilter,onChange:N=>x.setLaunchConfirmModelFilter(N.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),t.jsxs("select",{value:x.launchConfirmSortMode,onChange:N=>x.setLaunchConfirmSortMode(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:x.launchConfirmResumableOnly,onChange:N=>x.setLaunchConfirmResumableOnly(N.target.checked),disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:x.launchConfirmResumeId,onChange:N=>x.setLaunchConfirmResumeId(N.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:x.launchConfirmBusy||x.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:vu()}),x.filteredLaunchConfirmSavedSessions.map(N=>t.jsxs("option",{value:N.providerSessionId,disabled:!N.canResume,children:[N.title||N.providerSessionId," ",N.canResume?"":"(workspace missing)"]},N.providerSessionId))]}),!x.launchConfirmSessionsLoading&&x.launchConfirmSavedSessions.length>0&&x.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),x.launchConfirmResumeId&&(()=>{const N=x.filteredLaunchConfirmSavedSessions.find(G=>G.providerSessionId===x.launchConfirmResumeId);if(!N)return null;const U=Xi(N);return t.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:U.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:U.providerSessionId}),t.jsx("div",{className:"mt-1",children:U.metaLine}),U.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:U.updatedLabel}),U.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:U.preview})]})})()]}),onConfirm:x.handleConfirmLaunch,onCancel:x.closeLaunchConfirm}),m&&t.jsx(Yi,{section:p,onSectionChange:w})]})}function Ji(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 Mp(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:ds(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=Xs(n)?"cli":vs(n)?"acp":"ide",i=ds(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Xs(n)?n.cliName||n.type:vs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:vs(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 Lp(e,s){const r=new Map;for(const n of s){const a=qt(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((f,w)=>w.timestamp-f.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=_n(n),u=a.filter(f=>f.unread||f.requiresAction).length,p=Ji(n),m=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:It(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?du(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 br(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 _p({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:m,onRequestedMachineConsumed:f,requestedMobileSection:w,onRequestedMobileSectionConsumed:S,setSelectedTabKey:T,setScreen:d,setSelectedMachineId:b,setSection:y,setMachineBackTarget:h,resetMachineAction:C,markNotificationTargetRead:P}){const v=o.useRef(null),j=o.useCallback(k=>{if(!(k!=null&&k.sessionId))return;const g=_r(k,c),x=Math.max(Date.now(),os(k),g.lastUpdated||0);br("mark_read:start",{tabKey:k.tabKey,sessionId:k.sessionId,displayPrimary:it(k),inboxBucket:g.inboxBucket,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,activityAt:os(k),readAt:x}),P({sessionId:k.sessionId,tabKey:k.tabKey}),l(qt(k)||k.routeId,"mark_session_seen",{sessionId:k.sessionId,seenAt:x}).then($=>{br("mark_read:result",{tabKey:k.tabKey,sessionId:k.sessionId,result:$})}).catch($=>{br("mark_read:error",{tabKey:k.tabKey,sessionId:k.sessionId,error:$ instanceof Error?$.message:String($)})})},[c,l]);return o.useEffect(()=>{var g;if(!n){d("inbox"),T(((g=e[0])==null?void 0:g.tabKey)||null),v.current=null;return}if(i!=="chat"){v.current=null;return}const k=`${n.tabKey}:${n.sessionId||""}`;v.current!==k&&(v.current=k,j(n))},[e,j,i,n,d,T]),o.useEffect(()=>{if(!u)return;const k=e.find(g=>g.tabKey===u);k&&(T(k.tabKey),d("chat"),p==null||p())},[e,p,u,d,T]),o.useEffect(()=>{if(!m)return;const k=s.find(g=>g.id===m);k&&(b(k.id),C(),y("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,m,C,h,d,y,b]),o.useEffect(()=>{w&&(y(w),d("inbox"),S==null||S())},[S,w,d,y]),o.useEffect(()=>{const k=r.filter(g=>g.inboxBucket==="task_complete"||g.unread);k.length!==0&&br("inbox_state",{screen:i,selectedTabKey:a,items:k.map(g=>{const x=_r(g.conversation,c);return{liveState:x,tabKey:g.conversation.tabKey,sessionId:g.conversation.sessionId,displayPrimary:it(g.conversation),serverBucket:x.inboxBucket,computedBucket:g.inboxBucket,serverUnread:x.unread,computedUnread:g.unread,lastSeenAt:x.lastSeenAt,lastUpdated:x.lastUpdated,activityAt:os(g.conversation)}})})},[r,c,i,a]),{markConversationRead:j}}function Rp(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function bo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Pp(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Dp({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,p]=o.useState(null),m=o.useCallback(()=>{i("idle"),l(""),p(null)},[]),f=o.useCallback(async(h,C,P)=>{var v;try{i("loading"),l(`Launching ${C}…`);const j={ideType:C,enableCdp:!0};(v=P==null?void 0:P.workspacePath)!=null&&v.trim()&&(j.workspace=P.workspacePath.trim()),await e(h,"launch_ide",j),i("done"),l(`${C} launch requested`)}catch(j){i("error"),l(j instanceof Error?j.message:"Launch IDE failed"),console.error("Launch IDE failed",j)}},[e]),w=o.useCallback(async(h,C,P)=>{if(C.trim())try{i("loading"),l(P!=null&&P.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(h,"workspace_add",{path:C.trim(),createIfMissing:(P==null?void 0:P.createIfMissing)===!0});if(v!=null&&v.success){i("done"),l(P!=null&&P.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((v==null?void 0:v.error)||"Could not save workspace")}catch(v){i("error"),l(v instanceof Error?v.message:"Could not save workspace")}},[e]),S=o.useCallback(async h=>{var C,P,v,j,k,g;try{i("loading"),l("Starting daemon upgrade…");const x=await e(h,"daemon_upgrade",{});if((C=x==null?void 0:x.result)!=null&&C.alreadyLatest){i("done"),l(`Already on v${((P=x==null?void 0:x.result)==null?void 0:P.version)||"latest"}.`);return}if((v=x==null?void 0:x.result)!=null&&v.upgraded||(j=x==null?void 0:x.result)!=null&&j.success){i("done"),l(`Upgrade to v${((k=x==null?void 0:x.result)==null?void 0:k.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((g=x==null?void 0:x.result)==null?void 0:g.error)||"Upgrade failed")}catch(x){i("error"),l(x instanceof Error?x.message:"Upgrade failed")}},[e]),T=o.useCallback(async(h,C,P,v)=>{var g,x,$;const j=Date.now(),k={machineId:h,kind:C,providerType:P,workspaceId:(v==null?void 0:v.workspaceId)||null,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:j};try{i("loading"),l(`Launching ${P}…`),p(k);const A={cliType:P};(g=v==null?void 0:v.workspacePath)!=null&&g.trim()?A.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(A.workspaceId=v.workspaceId),v!=null&&v.resumeSessionId&&(A.resumeSessionId=v.resumeSessionId),(x=v==null?void 0:v.args)!=null&&x.trim()&&(A.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),($=v==null?void 0:v.model)!=null&&$.trim()&&(A.initialModel=v.model.trim());const M=await e(h,"launch_cli",A),L=(M==null?void 0:M.result)||M,O=(L==null?void 0:L.sessionId)||(L==null?void 0:L.id);if(M!=null&&M.success&&O){p(null),i("done"),l(`${P} launched`),s(`/dashboard?activeTab=${encodeURIComponent(O)}`);return}if(M!=null&&M.success){i("loading"),l(`${P} launch requested — waiting for session…`);return}p(null),i("error"),l((M==null?void 0:M.error)||(L==null?void 0:L.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(A){if(Pp(A)){i("loading"),l(`${P} launch requested — waiting for session…`);return}p(null),i("error"),l(A instanceof Error?A.message:`Could not launch ${C.toUpperCase()} workspace`)}},[s,e]),d=o.useCallback(async(h,C)=>{try{const P=await e(h,"list_saved_sessions",{providerType:C,kind:"cli",limit:30}),v=(P==null?void 0:P.result)??P;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(P){return console.error("Failed to list saved sessions on mobile:",P),[]}},[e]),b=o.useCallback(async(h,C)=>Xr(e,h,C),[e]);o.useEffect(()=>{var v;if(!u)return;const h=bo(u.workspacePath),C=r.find(j=>{var M,L,O,R;if(!j||j.type==="adhdev-daemon"||Rp(j.daemonId||j.id)!==u.machineId||(j.transport==="acp"?"acp":j.transport==="pty"?"cli":null)!==u.kind||String(j.agentType||j.type||"")!==u.providerType)return!1;const $=String(j.providerSessionId||"");if(u.resumeSessionId&&$)return $===u.resumeSessionId;if(h){const N=bo(j.workspace||j.runtimeWorkspaceLabel);return N?N===h:!1}return Number(j.lastUpdated||j._lastUpdate||j.timestamp||((R=(O=(L=(M=j.activeChat)==null?void 0:M.messages)==null?void 0:L.at)==null?void 0:O.call(L,-1))==null?void 0:R.timestamp)||0)>=u.startedAt-5e3});if(!C)return;const P=typeof C.sessionId=="string"&&C.sessionId?C.sessionId:typeof C.instanceId=="string"&&C.instanceId?C.instanceId:(v=n.find(j=>j.routeId===C.id))==null?void 0:v.sessionId;P&&(p(null),i("done"),l(`${u.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(P)}`))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{p(C=>!C||C.startedAt!==u.startedAt?C:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[u]);const y=o.useCallback(async(h,C)=>{if(C.kind==="ide"&&C.providerType){await f(h,C.providerType,{workspacePath:C.workspace||null});return}(C.kind==="cli"||C.kind==="acp")&&C.providerType&&await T(h,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[f,T]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:w,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:T,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:y}}function Ep({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(C=>C.routeId===y.routeId&&C.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),w=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),S=o.useCallback((y,h="inbox")=>{l(y),a(),u("machines"),p(h),c("machine")},[a,p,c,u,l]),T=o.useCallback(y=>{const h=qt(y);h&&S(h,"chat")},[S]),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:w,openMachine:S,openConversationMachine:T,backFromMachine:d,changeMachineSection:b}}function $p(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Bp(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function gr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Kp({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:w,requestedMobileSection:S,onRequestedMobileSectionConsumed:T,onOpenHistory:d,onOpenRemote:b,onStopCli:y,wsStatus:h,isConnected:C,onShowHiddenConversation:P,onShowAllHiddenConversations:v,onHideConversation:j,onOpenNewSession:k,notificationStateBySessionId:g,onMarkNotificationTargetRead:x}){const[$,A]=o.useState(()=>{var J;return((J=e[0])==null?void 0:J.tabKey)||null}),[M,L]=o.useState(()=>e[0]?"chat":"inbox"),[O,R]=o.useState("chats"),[N,U]=o.useState(null),[G,I]=o.useState("inbox"),B=Ls(),D="0.8.70",W=o.useMemo(()=>e.find(J=>J.tabKey===$)||e[0]||null,[e,$]),X=o.useMemo(()=>W?r.find(J=>J.id===W.routeId):void 0,[r,W]),we=o.useMemo(()=>!W||Xe(W)||!et(W)?null:Is(W),[W]),Le=o.useMemo(()=>r.filter(J=>J.type==="adhdev-daemon").sort(ea),[r]),ie=o.useMemo(()=>Le.find(J=>J.id===N)||null,[Le,N]),Ie=o.useMemo(()=>zr(r),[r]),te=Gr({sendDaemonCommand:a,activeConv:W||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),de=Dp({sendDaemonCommand:a,navigate:B,ides:r,conversations:e}),ae=o.useMemo(()=>e.map(J=>{const Se=M==="chat"&&(W==null?void 0:W.tabKey)===J.tabKey,Ue=Zn(J,Ie,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Se,notificationStateBySessionId:g}),De=os(J),Ge=hi(J);return{conversation:J,timestamp:De,preview:Ge,unread:Ue.unread,requiresAction:Ue.requiresAction,isWorking:Ue.isWorking,inboxBucket:Ue.inboxBucket}}),[e,Ie,g,M,W]),{markConversationRead:ge}=_p({conversations:e,machineEntries:Le,items:ae,selectedConversation:W,selectedTabKey:$,screen:M,liveSessionInboxState:Ie,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:m,requestedMachineId:f,onRequestedMachineConsumed:w,requestedMobileSection:S,onRequestedMobileSectionConsumed:T,setSelectedTabKey:A,setScreen:L,setSelectedMachineId:U,setSection:R,setMachineBackTarget:I,resetMachineAction:de.resetMachineAction,markNotificationTargetRead:x}),oe=Ep({conversations:e,selectedConversation:W,machineBackTarget:G,markConversationRead:ge,resetMachineAction:de.resetMachineAction,setSelectedTabKey:A,setScreen:L,setSelectedMachineId:U,setSection:R,setMachineBackTarget:I}),F=o.useMemo(()=>gr(ae.filter(J=>J.requiresAction)),[ae]),xe=o.useMemo(()=>gr(ae.filter(J=>J.unread&&!J.requiresAction)),[ae]),se=o.useMemo(()=>gr(ae.filter(J=>!J.unread&&!J.requiresAction&&J.isWorking)),[ae]),pe=o.useMemo(()=>gr(ae.filter(J=>!J.unread&&!J.requiresAction&&!J.isWorking)),[ae]),Z=o.useMemo(()=>ie?ae.filter(J=>qt(J.conversation)===ie.id):[],[ae,ie]),le=o.useMemo(()=>Mp(ie,r),[r,ie]),ne=(ie==null?void 0:ie.version)||null,be=!!ie&&!!ne&&!0&&ne!==D,me=o.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),E=o.useMemo(()=>me.filter(J=>J.category==="cli"&&J.installed!==!1).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[me]),ye=o.useMemo(()=>me.filter(J=>J.category==="acp"&&J.installed!==!1).map(J=>({type:J.type,displayName:J.displayName||J.type,icon:J.icon})),[me]),he=o.useMemo(()=>Lp(Le,ae),[ae,Le]),ke=o.useCallback(async J=>{ie&&await de.handleOpenRecent(ie.id,J)},[de,ie]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&W?t.jsx(gp,{selectedConversation:W,isAcp:Xe(W),isStandalone:l,selectedIdeEntry:X,actionLogs:n,userName:u,isSendingChat:te.isSendingChat,isFocusingAgent:te.isFocusingAgent,handleModalButton:te.handleModalButton,handleRelaunch:te.handleRelaunch,onBack:oe.backFromConversation,onOpenNativeConversation:oe.openNativeConversation,onOpenMachine:oe.openConversationMachine,onHideConversation:j,onOpenHistory:d,onOpenRemote:b,onStopCli:y,cliViewMode:we,onSetCliViewMode:async J=>{if(W&&we!==J)try{await a(qt(W)||W.routeId,"set_cli_view_mode",{targetSessionId:W.sessionId,cliType:Dt(W),mode:J})}catch(Se){Bp(Se)?console.warn("Skipped CLI view mode switch:",Se instanceof Error?Se.message:String(Se)):console.error("Failed to switch CLI view mode:",Se)}},handleSendChat:te.handleSendChat,handleFocusAgent:te.handleFocusAgent}):M==="machine"&&ie?t.jsx(Tp,{selectedMachineEntry:ie,selectedMachineConversations:Z,selectedMachineRecentLaunches:le,cliProviders:E,acpProviders:ye,selectedMachineNeedsUpgrade:be,appVersion:D,machineAction:de.machineAction,isStandalone:l,section:O,showBottomNav:G==="inbox",onBack:oe.backFromMachine,onSectionChange:oe.changeMachineSection,onOpenConversation:oe.openConversation,onOpenRecent:ke,onOpenMachineDetails:()=>B(`/machines/${ie.id}`),onMachineUpgrade:()=>de.handleMachineUpgrade(ie.id),onLaunchDetectedIde:(J,Se)=>de.handleLaunchDetectedIde(ie.id,J,Se),onAddWorkspace:(J,Se)=>de.handleAddWorkspace(ie.id,J,Se),onBrowseDirectory:J=>de.handleBrowseDirectory(ie.id,J),onLaunchWorkspaceProvider:(J,Se,Ue)=>de.handleLaunchWorkspaceProvider(ie.id,J,Se,Ue),onListSavedSessions:J=>de.handleListSavedSessions(ie.id,J)}):t.jsx(vp,{section:O,attentionItems:F,unreadItems:xe,workingItems:se,completedItems:pe,hiddenConversations:s,machineCards:he,getAvatarText:$p,onOpenConversation:oe.openConversation,onShowConversation:P,onShowAllHidden:v,onOpenNewSession:k,onOpenMachine:oe.openMachine,onOpenSettings:()=>B("/settings"),onSectionChange:R,wsStatus:h,isConnected:C,isStandalone:l})})}function gn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Wp({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[p,m]=o.useState(null),f=o.useCallback(()=>{c.current=0,u(!1),m(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const w=o.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),S=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!gn(s,r)){m("merge");return}const y=b.currentTarget.getBoundingClientRect(),h=b.clientX-y.left,C=y.width/3;h<C?m("split-left"):h>C*2?m("split-right"):m("merge")},[s,r]),T=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),m(null))},[]),d=o.useCallback(b=>{c.current=0,u(!1);const y=b.dataTransfer.getData("text/tab-key"),h=y?e.some(P=>P.tabKey===y):!1,C=p;if(m(null),i(),!!y){if(b.preventDefault(),C==="split-left"&&gn(s,r)){r==null||r(y,"split-left");return}if(C==="split-right"&&gn(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:w,handleDragOver:S,handleDragLeave:T,handleDrop:d}}function Op(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 Hp({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[p,m]=o.useState(null),f=o.useRef(null),w=o.useRef(null),S=o.useRef(n),T=o.useRef(a);o.useEffect(()=>{S.current=n},[n]),o.useEffect(()=>{T.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(k=>{const g=Op(k,e);return g.length===k.length&&g.every((x,$)=>x===k[$])?k:g})},[e]);const d=o.useMemo(()=>{const k=p??l;if(k.length===0)return e;const g=new Map(k.map((x,$)=>[x,$]));return[...e].sort((x,$)=>{const A=g.get(x.tabKey)??999,M=g.get($.tabKey)??999;return A-M})},[e,p,l]);o.useEffect(()=>{var g,x;if(d.length===0){i!==null&&(c(null),(g=S.current)==null||g.call(S,null));return}if(i&&d.some($=>$.tabKey===i))return;const k=d[0].tabKey;k!==i&&(c(k),(x=S.current)==null||x.call(S,k))},[d,i]);const b=o.useMemo(()=>d.find(k=>k.tabKey===i),[d,i]),y=o.useCallback(k=>{var g;c(k),(g=S.current)==null||g.call(S,k)},[]),h=o.useCallback((k,g,x)=>{u($=>{var O;const A=$.filter(R=>R!==k),M=A.indexOf(g);if(M<0)return $;const L=x==="left"?M:M+1;return A.splice(L,0,k),(O=T.current)==null||O.call(T,A),A}),m(null)},[]),C=o.useCallback((k,g,x)=>{const A=(l.length>0?l:e.map(O=>O.tabKey)).filter(O=>O!==k),M=A.indexOf(g);if(M<0)return;const L=x==="left"?M:M+1;A.splice(L,0,k),f.current=A,m(A)},[l,e]),P=o.useCallback(()=>{var g;const k=f.current;k&&(u(k),(g=T.current)==null||g.call(T,k))},[]),v=o.useCallback(()=>{f.current=null,m(null)},[]),j=o.useCallback(k=>{u(g=>{var $;const x=g.filter(A=>A!==k);return x.push(k),($=T.current)==null||$.call(T,x),x})},[]);return{activeTabId:i,activeConv:b,sortedConversations:d,previewOrderRef:f,draggingTabRef:w,selectTab:y,handleTabReorder:h,updatePreviewOrder:C,commitPreviewOrder:P,clearPreviewOrder:v,moveTabToEnd:j,setDraggingTabKey:k=>{w.current=k}}}function Up({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 ya({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(qi,{}),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 Zi="adhdev-tab-shortcuts";function ec(){try{return JSON.parse(localStorage.getItem(Zi)||"{}")}catch{return{}}}function tc({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>ec()),[l,u]=o.useState(null),p=o.useCallback(f=>{const w=[];return f.metaKey&&w.push(a?"⌘":"Meta"),f.ctrlKey&&w.push("Ctrl"),f.altKey&&w.push(a?"⌥":"Alt"),f.shiftKey&&w.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(w.push(f.key.length===1?f.key.toUpperCase():f.key),w.join("+"))},[a]),m=o.useCallback(f=>{c(f);try{localStorage.setItem(Zi,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=w=>{if(w.preventDefault(),w.stopPropagation(),w.key==="Escape"){u(null);return}const S=p(w);if(!S)return;const T={...i};for(const[d,b]of Object.entries(T))b===S&&delete T[d];T[l]=S,m(T),u(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,m,p]),o.useEffect(()=>{if(!e)return;const f=w=>{if(!(!w.ctrlKey&&!w.metaKey&&!w.altKey)){for(const[S,T]of Object.entries(i))if(s.includes(S)&&p(w)===T){w.preventDefault(),r(),n(S);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 Fp=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:p,onConversationActivated:m,onPreviewReorder:f,onReorderTab:w,onCommitPreviewOrder:S,onClearPreviewOrder:T,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:h,longPressTimer:C,isGroupActive:P}){const v=Rs(s),j=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",k=v.isReconnecting,g=o.useCallback(U=>{l.current=s.tabKey,b(s.tabKey),U.dataTransfer.setData("text/tab-key",s.tabKey),U.dataTransfer.effectAllowed="move"},[s.tabKey,l,b]),x=o.useCallback(()=>{l.current=null,b(null),S(),T(),d()},[l,b,S,T,d]),$=o.useCallback(U=>{const G=l.current;if(!(!G||G===s.tabKey)&&U.dataTransfer.types.includes("text/tab-key")){U.preventDefault(),U.stopPropagation();const I=U.currentTarget.getBoundingClientRect(),B=U.clientX<I.left+I.width/2?"left":"right";f(G,s.tabKey,B)}},[s.tabKey,l,f]),A=o.useCallback(U=>{U.preventDefault(),U.stopPropagation();const G=U.dataTransfer.getData("text/tab-key");if(G&&G!==s.tabKey){const I=U.currentTarget.getBoundingClientRect(),B=U.clientX<I.left+I.width/2?"left":"right";c.includes(G)?w(G,s.tabKey,B):y&&y(G)}T()},[s.tabKey,c,w,y,T]),M=o.useCallback(U=>{U.stopPropagation(),u(),p(s.tabKey),m(s)},[s,m,u,p]),L=o.useCallback(U=>{U.preventDefault(),h(U.clientX,U.clientY,s.tabKey)},[s.tabKey,h]),O=o.useCallback(U=>{const G=U.touches[0];C.current=setTimeout(()=>{h(G.clientX,G.clientY,s.tabKey)},600)},[s.tabKey,C,h]),R=o.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),N=["adhdev-dockview-tab",j,r&&"is-active",P&&"is-group-active",k&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:N,draggable:!0,onDragStart:g,onDragEnd:x,onDragOver:$,onDrop:A,onClick:M,onContextMenu:L,onTouchStart:O,onTouchEnd:R,onTouchMove:R,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?t.jsx("div",{className:"tab-spinner"}):v.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.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:it(s),children:it(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:k?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(s)}):v.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ts(s),t.jsx("span",{className:"connecting-dots"})]}):ts(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 zp({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:w,onDragTabKeyChange:S,onReceiveTab:T,onHideTab:d,isGroupActive:b,allowTabShortcuts:y=!0}){const[h,C]=o.useState(null),P=o.useRef(null),v=o.useRef(null),j=o.useMemo(()=>e.map(L=>L.tabKey),[e]);Zs("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:k,tabShortcuts:g,shortcutListening:x,setShortcutListening:$,saveShortcuts:A}=tc({enabled:y,sortedTabKeys:e.map(L=>L.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const L=O=>{const R=document.querySelector("[data-pane-context-menu]");R&&R.contains(O.target)||C(null)};return window.addEventListener("mousedown",L,!0),()=>window.removeEventListener("mousedown",L,!0)},[h]),o.useEffect(()=>{const L=v.current;if(!L)return;const O=R=>{Math.abs(R.deltaY)<=Math.abs(R.deltaX)||(R.preventDefault(),L.scrollLeft+=R.deltaY)};return L.addEventListener("wheel",O,{passive:!1}),()=>L.removeEventListener("wheel",O)},[]);const M=o.useCallback((L,O,R)=>{C({x:L,y:O,tabKey:R})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(L=>t.jsx(Fp,{conv:L,isActive:s===L.tabKey,isDraggedTab:a.current===L.tabKey,isTaskCompleteUnread:n.has(L.tabKey),shortcut:y?g[L.tabKey]:void 0,conversationKeys:j,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:m,onClearPreviewOrder:f,onDragStateReset:w,onDragTabKeyChange:S,onReceiveTab:T,onOpenContextMenu:M,longPressTimer:P,isGroupActive:b},L.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&t.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:h.x,top:h.y},children:[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:L=>{L.stopPropagation(),$(h.tabKey),C(null)},children:["⌨ ",g[h.tabKey]?`Change shortcut (${g[h.tabKey]})`:"Set shortcut"]}),g[h.tabKey]&&t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const L={...g};delete L[h.tabKey],A(L),C(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),C(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:()=>$(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:L=>L.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",k?"⌘+1":"Ctrl+1",", ",k?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Vp({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:p,groupIndex:m,onFocus:f,isSplitMode:w,numGroups:S,onMoveTab:T,onReceiveTab:d,style:b,onActiveTabChange:y,initialActiveTabId:h,initialTabOrder:C,onTabOrderChange:P,onHideTab:v,isFocused:j,allowTabShortcuts:k=!0}){const{sendCommand:g}=Tt(),x=o.useRef(null),{activeTabId:$,activeConv:A,sortedConversations:M,draggingTabRef:L,selectTab:O,handleTabReorder:R,updatePreviewOrder:N,commitPreviewOrder:U,clearPreviewOrder:G,moveTabToEnd:I,setDraggingTabKey:B}=Hp({conversations:e,initialActiveTabId:h,initialTabOrder:C,onActiveTabChange:y,onTabOrderChange:P}),D=Gr({sendDaemonCommand:a,activeConv:A,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:W,dropAction:X,resetDragState:we,handleDragEnter:Le,handleDragOver:ie,handleDragLeave:Ie,handleDrop:te}=Wp({conversations:e,numGroups:S,onMoveTab:T,onReceiveTab:d,onOwnTabDrop:I,onClearPreviewOrder:G}),de=A&&!Xe(A)&&Is(A)==="terminal",ae=o.useMemo(()=>A?s.find(se=>se.id===A.routeId):void 0,[s,A]),ge=o.useMemo(()=>A?n.filter(se=>se.routeId===A.tabKey):[],[n,A]),oe=o.useMemo(()=>zr(s),[s]),F=o.useMemo(()=>new Set(M.filter(se=>Hl(se,oe,{isOpenConversation:se.tabKey===$})).map(se=>se.tabKey)),[$,oe,M]);Zs("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:$,dragOver:W});const xe=o.useCallback(se=>{se.streamSource==="agent-stream"&&se.agentType&&g(se.routeId,Gi(),{agentType:se.agentType,...se.sessionId&&{targetSessionId:se.sessionId}}).catch(()=>{})},[g]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:f,style:{...b,outline:W?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(zp,{conversations:M,activeTabId:$,groupIndex:m,numGroups:S,unreadTabKeys:F,draggingTabRef:L,onFocus:f,onSelectTab:O,onConversationActivated:xe,onPreviewReorder:N,onReorderTab:R,onCommitPreviewOrder:U,onClearPreviewOrder:G,onDragStateReset:we,onDragTabKeyChange:B,onMoveTab:T,onReceiveTab:d,onHideTab:v,isGroupActive:j??!1,allowTabShortcuts:k}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Le,onDragOver:ie,onDragLeave:Ie,onDrop:te,children:[W&&t.jsx(Up,{dropAction:X,canSplit:!!(S<4&&T)}),A?t.jsx(ba,{activeConv:A,clearToken:r[A.tabKey]||0,isCliTerminal:!!de,ideEntry:ae,terminalRef:x,handleModalButton:D.handleModalButton,handleRelaunch:D.handleRelaunch,handleSendChat:D.handleSendChat,isSendingChat:D.isSendingChat,handleFocusAgent:D.handleFocusAgent,isFocusingAgent:D.isFocusingAgent,actionLogs:ge,userName:p,isInputActive:!w||!!j}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(ya,{conversationsCount:e.length,isSplitMode:w,isStandalone:l,hasRegisteredMachines:u})})]})]})}function Gp({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:w,userName:S,focusedGroup:T,setFocusedGroup:d,moveTabToGroup:b,splitTabRelative:y,closeGroup:h,handleResizeStart:C,groupActiveTabIds:P,setGroupActiveTabIds:v,groupTabOrders:j,setGroupTabOrders:k,toggleHiddenTab:g,allowTabShortcuts:x=!0}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map(($,A)=>{const M=s&&n.length===r?`${n[A]}%`:void 0;return t.jsxs(nt.Fragment,{children:[s&&A>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:L=>C(A-1,L),onDoubleClick:()=>h(A),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(Vp,{style:s?{flexBasis:M??`${100/r}%`,flexGrow:M?0:1,flexShrink:M?0:1}:void 0,conversations:$,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:p,setActionLogs:m,isStandalone:f,hasRegisteredMachines:w,userName:S,groupIndex:A,isFocused:s&&T===A,onFocus:()=>d(A),isSplitMode:s,numGroups:r,onMoveTab:(L,O)=>{O==="left"&&A>0?b(L,A-1):O==="right"&&A<r-1?b(L,A+1):O==="split-left"&&r<4?y(L,A,"left"):O==="split-right"&&r<4&&y(L,A,"right")},onReceiveTab:L=>b(L,A),onActiveTabChange:L=>v(O=>(O[A]??null)===(L??null)?O:{...O,[A]:L}),initialActiveTabId:P[A],initialTabOrder:j[A],onTabOrderChange:L=>k(O=>{const R=O[A]||[];return R.length===L.length&&R.every((N,U)=>N===L[U])?O:{...O,[A]:L}}),onHideTab:g,allowTabShortcuts:x})]},A)})})}function sc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?dt.onScreenshot("ide-page",(m,f)=>{if(m!==e)return;const w=new FileReader;w.onload=()=>i(w.result),w.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var m;return e?((m=dt.onStatus)==null?void 0:m.call(dt,(f,w)=>{f===e&&w!=null&&w.screenshotUsage&&l(w.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const p=e?dt.get(e):null;if(!(!p||r!=="connected"))return n!=="chat"&&s?p.startScreenshots(s):p.stopScreenshots(s),()=>{p.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(p,m)=>{const f=e?dt.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(p,m,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const rc="adhdev-dashboard-action-shortcuts",qp=1200,Yp={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Xp(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function rt(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 nc(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:rt("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:rt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:rt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:rt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:rt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:rt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:rt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:rt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:rt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:rt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:rt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:rt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:rt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:rt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:rt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:rt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:rt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:rt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:rt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:rt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:rt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:rt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:rt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:rt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:rt("toggleCliView",e)}]}function Un(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Kr(e){const s=Object.fromEntries(nc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(rc)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Yp))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function ac(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Qp({enabled:e=!0,onTrigger:s}){const r=Xp(),[n,a]=o.useState(()=>Kr(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(ac(d.key)),b.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(rc,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=Kr(r),b=Object.entries(n),y=Object.entries(d);b.length===y.length&&b.every(([h,C])=>d[h]===C)||f(d)},[n,r,f]);const w=o.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),S=o.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},qp))},[]);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 C=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(l.length===0&&C){u([y]);return}const v=[...l,y].slice(0,2).join(" "),j={...n};for(const[k,g]of Object.entries(j))g===v&&delete j[k];j[i]=v,f(j),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(Un(b.target)&&!h)return;const C=p.current.parts,P=h?[y]:[...C.slice(-1),y].slice(-2),v=P.join(" "),j=P[P.length-1],k=Object.entries(n).filter(([,M])=>!!M),g=k.find(([,M])=>M===v);if(g){b.preventDefault(),w(),s(g[0]);return}if(k.some(([,M])=>M.startsWith(`${v} `))){b.preventDefault(),p.current.parts=P,S();return}const $=k.find(([,M])=>M===j);if($){b.preventDefault(),w(),s($[0]);return}if(k.some(([,M])=>M.startsWith(`${j} `))){b.preventDefault(),p.current.parts=[j],S();return}w()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,S,e,m,s,w,i]),o.useEffect(()=>()=>w(),[w]);const T=o.useMemo(()=>nc(r),[r]);return{isMac:r,actionDefinitions:T,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:f}}function Jp({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):s?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut"}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function Zp(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function go({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Zp(n):!0}const oc=o.createContext(null);function Jr(){const e=o.useContext(oc);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Ar(e){return it(e)||e.tabKey}function ef(e){return`remote:${e}`}function zt(e){return e.startsWith("remote:")}function yo(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function yn(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 yr(e,s){e.classList.remove(Tn.className,Mn.className),e.classList.add(s==="light"?Tn.className:Mn.className)}function vo(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 tf(e){const[,s]=o.useState(0);o.useEffect(()=>{const r=()=>s(a=>a+1),n=[e.api.onDidActiveGroupChange(r),e.api.onDidTitleChange(r),e.api.onDidGroupChange(r),e.containerApi.onDidActivePanelChange(r)];return()=>{for(const a of n)a.dispose()}},[e.api,e.containerApi])}function sf(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const p of l){const m=e.addPanel({id:p.tabKey,component:"conversation",title:Ar(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 wo(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])zt(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!==Ar(n)&&a.api.setTitle(Ar(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Ar(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 jo(e,s,r){var u,p;const n=r?ef(r):null;for(const m of[...e.panels])zt(m.id)&&(!n||m.id!==n)&&e.removePanel(m);if(!r||!n)return;const a=Bt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=gi(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=>!zt(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 rf({params:e,api:s}){var f;const r=Jr(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=Gr({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const w=[s.onDidActiveChange(S=>i(S.isActive)),s.onDidActiveGroupChange(S=>{if(!s.isActive&&!S.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const S of w)S.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(w=>w.id===c.routeId):void 0,[r.ides,c]),p=o.useMemo(()=>c?r.actionLogs.filter(w=>w.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(ya,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const m=!Xe(c)&&Is(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(ba,{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 nf({params:e}){var u;const s=Jr(),r=o.useMemo(()=>Bt([...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}=sc({doId:a,targetSessionId:r?ra(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(Yo,{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 af(){const e=Jr();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(ya,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function of(e){var S,T;tf(e);const s=Jr(),r=o.useCallback(d=>{"button"in d&&d.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const d=Bt([...s.conversationsByTabKey.values()],e.params.routeId),b=((S=e.api.group.activePanel)==null?void 0:S.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=((T=e.api.group.activePanel)==null?void 0:T.id)===e.api.id,i=e.api.isGroupActive,c=Zn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,p=c.isGenerating,m=c.isWaiting,f=c.unread,w=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:it(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:it(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:ts(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ts(n)}):t.jsx("span",{children:ts(n)})})]}),w&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:w,children:w})]})}function cf({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:p,userName:m,toggleHiddenTab:f,actionShortcuts:w,registerActionHandlers:S,onActiveTabChange:T,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:y,scrollToBottomRequest:h,notificationStateBySessionId:C}){var Ke,Re,ft;const{theme:P}=ma(),{sendCommand:v}=Tt(),j=o.useRef(null),k=o.useRef(null),g=o.useRef(!1),x=o.useRef(!1),$=o.useRef(!1),A=o.useRef(null),M=o.useRef([]),[L,O]=o.useState(null),[R,N]=o.useState(!1),[U,G]=o.useState(!1),[I,B]=o.useState(0),D=o.useRef(null),W=o.useMemo(()=>Ui(typeof window<"u"?window.innerWidth:1280),[]),X=o.useRef(typeof window>"u"?{}:Hm(W)),we=o.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),Le=o.useMemo(()=>zr(r),[r]),ie=o.useMemo(()=>{const K=j.current;return K?K.groups.some(H=>{try{const z=H.model.location.type;return z!=="floating"&&z!=="popout"?!1:H.panels.some(V=>we.has(V.id))}catch{return!1}}):!1},[we,I,e]),Ie=o.useCallback(()=>{var K;(K=j.current)==null||K.focus()},[]),te=o.useCallback(K=>{const H=document,z=K.document;for(const Ne of H.querySelectorAll('link[rel="stylesheet"]')){const Fe=z.createElement("link");Fe.rel="stylesheet",Fe.href=Ne.href,Ne.crossOrigin&&(Fe.crossOrigin=Ne.crossOrigin),z.head.appendChild(Fe)}for(const Ne of H.querySelectorAll("style")){const Fe=z.createElement("style");Fe.textContent=Ne.textContent,z.head.appendChild(Fe)}const V=[];for(const Ne of H.styleSheets)try{for(const Fe of Ne.cssRules)Fe instanceof CSSStyleRule&&(Fe.selectorText===":root"||Fe.selectorText==="html")&&V.push(Fe.cssText)}catch{}if(V.length>0){const Ne=z.createElement("style");Ne.textContent=V.join(`
44
+ `),z.head.appendChild(Ne)}const ee=H.documentElement.getAttribute("data-theme");ee&&z.documentElement.setAttribute("data-theme",ee),z.documentElement.style.colorScheme=ee==="light"?"light":"dark",z.body.className=H.body.className;const ve=H.documentElement.getAttribute("style");ve&&z.documentElement.setAttribute("style",ve);const Ce=z.getElementById("dv-popout-window");Ce instanceof HTMLElement&&(Ce.classList.add("adhdev-dockview"),yr(Ce,P))},[P]),de=o.useCallback(()=>{var H;const K=j.current;if(K)for(const z of K.groups)try{const V=(H=z.element)==null?void 0:H.ownerDocument;if(!V||V===document)continue;const ee=V.getElementById("dv-popout-window");ee instanceof HTMLElement&&(ee.classList.add("adhdev-dockview"),yr(ee,P));const ve=document.documentElement.getAttribute("data-theme");ve&&V.documentElement.setAttribute("data-theme",ve),V.documentElement.style.colorScheme=ve==="light"?"light":"dark",V.body.className=document.body.className;const Ce=document.documentElement.getAttribute("style");Ce?V.documentElement.setAttribute("style",Ce):V.documentElement.removeAttribute("style")}catch{}},[P]),ae=o.useCallback(()=>{var H;const K=j.current;if(K)for(const z of K.groups)try{const V=(H=z.element)==null?void 0:H.ownerDocument;if(!V||V===document)continue;const ee=V.getElementById("dv-popout-window");if(!(ee instanceof HTMLElement))continue;ee.classList.add("adhdev-dockview"),yr(ee,P),ee.classList.toggle("is-showing-dockview-overlay",U),ee.classList.toggle("is-dragging-dockview",R)}catch{}},[R,U,P]),ge=o.useCallback(K=>{const H=j.current;if(!H)return;const z=H.getPanel(K);z&&H.addPopoutGroup(z,{popoutUrl:"/popout.html",onDidOpen:({window:V})=>{te(V),be();const ee=we.get(K);V.document.title=ee?`${it(ee)} — ADHDev`:"ADHDev — Popout"}})},[we,te]),oe=o.useCallback(K=>{const H=j.current,z=H==null?void 0:H.getPanel(K);if(!H||!z)return;const V=H.groups.filter(ee=>{var ve;try{return((ve=ee.element)==null?void 0:ve.ownerDocument)===document}catch{return!0}});V.length>0?z.api.moveTo({group:V[0],position:"center"}):z.api.moveTo({position:"center"}),z.api.setActive()},[]),F=o.useCallback(K=>{var V;const H=j.current;if(!H)return!1;const z=H.getPanel(K);if(!z)return!1;try{return((V=z.group.element)==null?void 0:V.ownerDocument)!==document}catch{return!1}},[]),xe=o.useCallback(K=>{F(K)&&oe(K),f(K)},[F,oe,f]),se=o.useCallback(K=>{const H=j.current,z=H==null?void 0:H.getPanel(K);!H||!z||H.addFloatingGroup(z,{width:600,height:500})},[]),pe=o.useCallback(K=>{var z;const H=(z=j.current)==null?void 0:z.getPanel(K);if(!H)return!1;try{return H.group.model.location.type==="floating"}catch{return!1}},[]),Z=o.useCallback(()=>{var H,z;const K=(z=(H=j.current)==null?void 0:H.activePanel)==null?void 0:z.id;return!K||zt(K)?null:we.has(K)?K:null},[we]),le=o.useCallback(K=>{const H=j.current,z=H==null?void 0:H.getPanel(K);if(!H||!z)return;const V=H.groups.filter(ee=>{try{return ee.model.location.type==="grid"}catch{return!0}});V.length>0?z.api.moveTo({group:V[0],position:"center"}):z.api.moveTo({position:"center"}),z.api.setActive()},[]),ne=o.useCallback(()=>{var ve;const K=j.current;if(!K)return;const z=K.groups.filter(Ce=>{var Ne;try{return((Ne=Ce.element)==null?void 0:Ne.ownerDocument)===document&&Ce.model.location.type==="grid"}catch{return!1}})[0]||null,V=[...K.panels];for(const Ce of V){const Ne=(ve=Ce.group.element)==null?void 0:ve.ownerDocument,Fe=Ce.group.model.location.type;Ne===document&&Fe==="grid"||(z&&z.id!==Ce.group.id?Ce.api.moveTo({group:z,position:"center"}):Ce.api.moveTo({position:"center"}))}const ee=K.activePanel;ee&&(ee.group.model.openPanel(ee),ee.api.setActive()),yn(document)},[]),be=o.useCallback(()=>{var H,z;const K=j.current;if(K)for(const V of K.groups){const ee=(H=V.element)==null?void 0:H.ownerDocument;if(!ee||ee===document)continue;const ve=ee.getElementById("dv-popout-window");if(!(ve instanceof HTMLElement))continue;let Ce=null,Ne=ee.title||"ADHDev",Fe="Popout workspace";const We=V.activePanel;if(We)if(Ce=We.id,zt(We.id)){const ze=((z=We.params)==null?void 0:z.routeId)||We.id.slice(7),_=Bt([...we.values()],ze);Ne=gi(_),Fe=_!=null&&_.machineName?`Remote view · ${_.machineName}`:"Remote view"}else{const ze=we.get(We.id);Ne=ze?it(ze):We.title||We.id,Fe=ze?ts(ze):"Dockview panel"}ee.title=`${Ne} — ADHDev`;let je=ee.getElementById("adhdev-popout-header");je instanceof HTMLElement||(je=ee.createElement("div"),je.id="adhdev-popout-header",ee.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
+ <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
46
+ <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
47
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${yo(Ne)}</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;">${yo(Fe)}</div>
49
+ </div>
50
+ <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
51
+ <button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
52
+ <button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
53
+ </div>
54
+ `,ve.style.top="52px",ve.style.height="calc(100% - 52px)";const Q=je.querySelector("[data-adhdev-popout-focus]");Q&&(Q.onclick=()=>{window.focus()});const Ee=je.querySelector("[data-adhdev-popout-dock]");Ee&&(Ee.disabled=!Ce,Ee.style.opacity=Ce?"1":"0.5",Ee.style.cursor=Ce?"pointer":"default",Ee.onclick=()=>{var ze;Ce&&oe(Ce),(ze=ee.defaultView)==null||ze.focus()})}},[we,oe]),me=o.useCallback(K=>{var V;const H=j.current,z=H==null?void 0:H.getPanel(K);if(!(!H||!z)){z.group.model.openPanel(z),z.api.setActive();try{const ee=z.group.model.location;ee.type==="popout"?ee.getWindow().focus():yn((V=z.group.element)==null?void 0:V.ownerDocument)}catch{}}},[]),E=o.useCallback(K=>{const H=j.current,z=H==null?void 0:H.activePanel,V=(H==null?void 0:H.activeGroup)||(z==null?void 0:z.group);if(!H||!z||!V)return;const ee=V.panels||[];if(ee.length<=1)return;const ve=ee.findIndex(Fe=>Fe.id===z.id);if(ve<0)return;const Ce=(ve+K+ee.length)%ee.length,Ne=ee[Ce];Ne&&(Ne.group.model.openPanel(Ne),Ne.api.setActive())},[]),ye=o.useCallback(K=>{var Ee;const H=j.current,z=(H==null?void 0:H.activeGroup)||((Ee=H==null?void 0:H.activePanel)==null?void 0:Ee.group);if(!H||!z)return;const V=H.groups||[],ee=V.find(ze=>ze.id===z.id);if(!ee)return;const ve=ee.element.getBoundingClientRect(),Ce=ve.left+ve.width/2,Ne=ve.top+ve.height/2,Fe=(ze,_,Y,re)=>Math.max(0,Math.min(_,re)-Math.max(ze,Y)),We=ze=>{const _=ze.element.getBoundingClientRect(),Y=_.left+_.width/2,re=_.top+_.height/2;let _e=0,Me=0,Pe=0,$e=!1;if(K==="left"?($e=Y<Ce,_e=Math.max(0,ve.left-_.right),Me=Math.abs(re-Ne),Pe=Fe(ve.top,ve.bottom,_.top,_.bottom)):K==="right"?($e=Y>Ce,_e=Math.max(0,_.left-ve.right),Me=Math.abs(re-Ne),Pe=Fe(ve.top,ve.bottom,_.top,_.bottom)):K==="above"?($e=re<Ne,_e=Math.max(0,ve.top-_.bottom),Me=Math.abs(Y-Ce),Pe=Fe(ve.left,ve.right,_.left,_.right)):($e=re>Ne,_e=Math.max(0,_.top-ve.bottom),Me=Math.abs(Y-Ce),Pe=Fe(ve.left,ve.right,_.left,_.right)),!$e)return Number.POSITIVE_INFINITY;const Be=Pe>0?0:120;return _e*3+Me+Be};let je=null,Q=Number.POSITIVE_INFINITY;for(const ze of V){if(ze.id===ee.id)continue;const _=We(ze);Number.isFinite(_)&&(_>=Q||(Q=_,je=ze))}return je||void 0},[]),he=o.useCallback(K=>{var V;const H=ye(K);if(!H)return;const z=H.activePanel||H.panels[0];z&&(H.model.openPanel(z),z.api.setActive(),yn((V=H.element)==null?void 0:V.ownerDocument))},[ye]),ke=o.useCallback((K,H)=>{const z=j.current,V=z==null?void 0:z.activePanel,ee=(z==null?void 0:z.activeGroup)||(V==null?void 0:V.group);if(!z||!V||!ee)return;let ve=ye(K);!ve&&(H!=null&&H.createGroupIfMissing)&&(ve=z.addGroup({referenceGroup:ee,direction:K})),ve&&(V.api.moveTo({group:ve,position:"center"}),V.group.model.openPanel(V),V.api.setActive())},[ye]),{isMac:J,tabShortcuts:Se,shortcutListening:Ue,setShortcutListening:De,saveShortcuts:Ge}=tc({sortedTabKeys:e.map(K=>K.tabKey),onFocus:Ie,onSelectTab:me}),Qe=o.useCallback(()=>{var z;const K=j.current;if(!K)return;const H=K.activePanel;if(H){if(zt(H.id)){const V=((z=H.params)==null?void 0:z.routeId)||H.id.slice(7),ee=Bt(e,V);ee!=null&&ee.tabKey&&De(ee.tabKey);return}we.has(H.id)&&De(H.id)}},[we,me,De,e]),Ze=o.useCallback(K=>{const H=[];return K.metaKey&&H.push(J?"⌘":"Meta"),K.ctrlKey&&H.push("Ctrl"),K.altKey&&H.push(J?"⌥":"Alt"),K.shiftKey&&K.key.length!==1&&H.push(J?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(K.key)?null:(H.push(ac(K.key)),H.join("+"))},[J]),ut=o.useCallback(K=>{var H,z;switch(K){case"splitActiveTabRight":ke("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":ke("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const V=Z();V&&se(V);return}case"popoutActiveTab":{const V=Z();V&&ge(V);return}case"dockActiveTab":{const V=Z();if(!V)return;F(V)?oe(V):pe(V)&&le(V);return}case"focusLeftPane":he("left");return;case"focusRightPane":he("right");return;case"focusUpPane":he("above");return;case"focusDownPane":he("below");return;case"moveActiveTabToLeftPane":ke("left");return;case"moveActiveTabToRightPane":ke("right");return;case"moveActiveTabToUpPane":ke("above");return;case"moveActiveTabToDownPane":ke("below");return;case"selectPreviousGroupTab":E(-1);return;case"selectNextGroupTab":E(1);return;case"setActiveTabShortcut":Qe();return;case"hideCurrentTab":{const V=(z=(H=j.current)==null?void 0:H.activePanel)==null?void 0:z.id;V&&!zt(V)&&xe(V);return}default:return}},[E,le,he,se,Z,xe,pe,F,oe,ke,ge,Qe]);o.useEffect(()=>{if(!L)return;const K=L.sourceDocument,H=K.defaultView??window,z=V=>{const ee=K.querySelector("[data-dockview-tab-context-menu]");ee&&ee.contains(V.target)||O(null)};return H.addEventListener("mousedown",z,!0),H!==window&&window.addEventListener("mousedown",()=>O(null),!0),()=>{H.removeEventListener("mousedown",z,!0),H!==window&&window.removeEventListener("mousedown",()=>O(null),!0)}},[L]);const qe=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:we,hasDetachedConversationPanels:ie,ides:r,isStandalone:l,hasRegisteredMachines:u,liveSessionInboxState:Le,notificationStateBySessionId:C,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:xe,userName:m,scrollToBottomRequest:h,tabShortcuts:Se,openTabContextMenu:({x:K,y:H,tabKey:z,sourceDocument:V})=>O({x:K,y:H,tabKey:z,sourceDocument:V??document}),popoutTab:ge,moveTabBackToMain:oe,isTabInPopout:F,floatTab:se,isTabFloating:pe}),[n,s,we,ie,r,l,u,Le,C,a,c,i,xe,m,h,Se,ge,oe,F,se,pe]),ht=L?Jp({isTabInPopout:F(L.tabKey),isTabFloating:pe(L.tabKey),tabShortcut:Se[L.tabKey],actionShortcuts:w}):[],mt=o.useCallback(K=>{var V;const H=j.current;if((((V=H==null?void 0:H.activePanel)==null?void 0:V.id)??null)===K.id){K.group.model.openPanel(K);return}K.group.model.openPanel(K),K.api.setActive()},[]),tt=o.useCallback(K=>{if(!K)return!1;const H=j.current;if(!H)return!1;const z=H.getPanel(K);return z?(mt(z),y==null||y(),!0):!1},[mt,y]),xt=o.useCallback(()=>{if($.current)return!1;const K=tt(A.current);return K&&($.current=!0),K},[tt]),pt=o.useCallback(()=>{var H;const K=j.current;K&&Om(W,{activeTabId:((H=K.activePanel)==null?void 0:H.id)??null,layout:K.toJSON()})},[W]),ce=o.useCallback(()=>{Um(W,X.current)},[W]),Ve=o.useCallback(K=>{var V,ee,ve,Ce;const H=j.current;if(!H)return{kind:"grid"};const z=H.toJSON();for(const Ne of z.floatingGroups||[])if((ee=(V=Ne.data)==null?void 0:V.views)!=null&&ee.includes(K)&&Ne.position)return{kind:"floating",position:Ne.position};for(const Ne of z.popoutGroups||[])if((Ce=(ve=Ne.data)==null?void 0:ve.views)!=null&&Ce.includes(K))return{kind:"popout",position:Ne.position,popoutUrl:Ne.url};return{kind:"grid"}},[]),ct=o.useCallback(K=>{const H=j.current;if(!H)return;const z=H.getPanel(K),V=X.current[K];if(!z||!V||V.kind==="grid")return;if(z.group.model.location.type===V.kind){delete X.current[K],ce();return}if(V.kind==="floating"){H.addFloatingGroup(z,{x:V.position.left??24,y:V.position.top??24,width:V.position.width,height:V.position.height}),delete X.current[K],ce();return}delete X.current[K],ce()},[ce]);o.useEffect(()=>(S==null||S({setShortcutForActiveTab:Qe,restoreHiddenTabToSavedLocation:ct,activateConversationTab:me,resetAllPanelsToMain:ne,activatePreviousTabInGroup:()=>E(-1),activateNextTabInGroup:()=>E(1),floatActiveTab:()=>{const K=Z();K&&se(K)},popoutActiveTab:()=>{const K=Z();K&&ge(K)},dockActiveTab:()=>{const K=Z();K&&(F(K)?oe(K):pe(K)&&le(K))},splitActiveTabRight:()=>ke("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>ke("below",{createGroupIfMissing:!0}),focusLeftPane:()=>he("left"),focusRightPane:()=>he("right"),focusUpPane:()=>he("above"),focusDownPane:()=>he("below"),moveActiveTabToLeftPane:()=>ke("left"),moveActiveTabToRightPane:()=>ke("right"),moveActiveTabToUpPane:()=>ke("above"),moveActiveTabToDownPane:()=>ke("below")}),()=>S==null?void 0:S(null)),[E,le,se,he,Z,pe,F,ke,oe,ge,S,ne,ct,me,Qe]);const Je=o.useCallback(()=>{const K=k.current;if(!K)return;const H=K.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const z of H)z.setAttribute("data-adhdev-force-hidden","true")},[]),bt=o.useCallback(()=>{const K=k.current;if(!K)return;const H=K.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const z of H)z.removeAttribute("data-adhdev-force-hidden")},[]),jt=o.useCallback(()=>{const K=k.current;if(!K)return;const H=K.querySelectorAll(".dv-drop-target-container");for(const ee of H)ee.remove();const z=K.querySelectorAll(".dv-drop-target-dropzone");for(const ee of z)ee.remove();const V=K.querySelectorAll(".dv-drop-target");for(const ee of V)ee.classList.remove("dv-drop-target")},[]),kt=o.useCallback(()=>{N(!1),G(!1),bt(),Je(),jt(),!(typeof window>"u")&&(D.current!=null&&window.clearTimeout(D.current),window.requestAnimationFrame(()=>{Je(),jt()}),D.current=window.setTimeout(()=>{Je(),jt(),D.current=null},80))},[bt,Je,jt]),Nt=o.useCallback(K=>{var z;j.current=K.api;const H=Wm(W);if(A.current=(H==null?void 0:H.activeTabId)??null,H!=null&&H.layout&&K.api.fromJSON(H.layout,{reuseExistingPanels:!1}),x.current=go({hasStoredLayout:!!(H!=null&&H.layout),initialDataLoaded:p,visibleConversationCount:e.length,ides:r}),x.current||(wo(K.api,e),jo(K.api,e,b)),K.api.totalPanels===0&&e.length>0){const V=sf(K.api,e,d);if(V){const ee=K.api.getPanel(V);ee&&mt(ee)}}else!x.current&&!tt(d)&&xt();g.current=!0,K.api.onDidActivePanelChange(V=>{var ve;if(A.current=(V==null?void 0:V.id)??null,$.current=!0,be(),V&&zt(V.id)){const Ce=((ve=V.params)==null?void 0:ve.routeId)||V.id.slice(7),Ne=Bt(e,Ce);T((Ne==null?void 0:Ne.tabKey)??null),pt();return}if(T((V==null?void 0:V.id)??null),pt(),!V)return;const ee=we.get(V.id);(ee==null?void 0:ee.streamSource)==="agent-stream"&&ee.agentType&&v(ee.routeId,Gi(),{agentType:ee.agentType,...ee.sessionId&&{targetSessionId:ee.sessionId}}).catch(()=>{})}),K.api.onDidLayoutChange(()=>{pt(),be(),B(V=>V+1)}),K.api.onWillDragPanel(()=>{N(!0),G(!1),Je()}),K.api.onWillDragGroup(()=>{N(!0),G(!1),Je()}),K.api.onWillShowOverlay(()=>{bt(),G(!0)}),K.api.onDidMovePanel(kt),K.api.onDidDrop(kt),K.api.onDidAddGroup(V=>{requestAnimationFrame(()=>{var ee,ve;try{const Ce=(ee=V.element)==null?void 0:ee.ownerDocument;if(!Ce||Ce===document)return;(ve=Ce.getElementById("dv-popout-window"))==null||ve.classList.add("adhdev-dockview");const Ne=document.documentElement.getAttribute("data-theme");Ne&&Ce.documentElement.setAttribute("data-theme",Ne),Ce.body.className=document.body.className;const Fe=document.documentElement.getAttribute("style");Fe&&Ce.documentElement.setAttribute("style",Fe)}catch{}be(),B(Ce=>Ce+1)})}),T(((z=K.api.activePanel)==null?void 0:z.id)??null)},[mt,tt,kt,bt,we,r,p,W,Je,T,pt,d,b,v,be,e]);o.useLayoutEffect(()=>{const K=j.current;if(!K||!g.current||x.current&&go({hasStoredLayout:!0,initialDataLoaded:p,visibleConversationCount:e.length,ides:r}))return;x.current&&(x.current=!1);const H=M.current,z=new Set(H),V=e.map(We=>We.tabKey),ee=new Set(V);let ve=!1;for(const We of H)ee.has(We)||(X.current[We]=Ve(We),ve=!0);ve&&ce(),wo(K,e),jo(K,e,b);const Ce=V.filter(We=>!z.has(We));let Ne=!1;for(const We of Ce){const je=K.getPanel(We),Q=X.current[We];if(!je||!Q||Q.kind==="grid")continue;if(je.group.model.location.type===Q.kind){delete X.current[We],Ne=!0;continue}if(Q.kind==="floating"){K.addFloatingGroup(je,{x:Q.position.left??24,y:Q.position.top??24,width:Q.position.width,height:Q.position.height}),delete X.current[We],Ne=!0;continue}}if(Ne&&ce(),M.current=V,d&&tt(d))return;!K.activePanel&&K.panels[0]&&mt(K.panels[0]),!!(K.activePanel&&K.getPanel(K.activePanel.id))||xt()},[mt,tt,xt,r,p,ce,Ve,d,b,e]),o.useEffect(()=>{g.current&&tt(d)},[tt,d]),o.useEffect(()=>{if(!R||typeof window>"u")return;const K=()=>kt();return window.addEventListener("pointerup",K),window.addEventListener("mouseup",K),window.addEventListener("dragend",K),()=>{window.removeEventListener("pointerup",K),window.removeEventListener("mouseup",K),window.removeEventListener("dragend",K)}},[kt,R]),o.useEffect(()=>()=>{typeof window>"u"||D.current!=null&&window.clearTimeout(D.current)},[]),o.useEffect(()=>{const K=z=>{const V=z.target;if(!V)return;const ee=V.querySelector("[data-tab-key]")||V.closest("[data-tab-key]");if(ee){const ve=ee.getAttribute("data-tab-key");if(ve&&z.dataTransfer){const Ce=V.closest(".dv-tab")||ee.closest(".dv-tab")||ee;z.dataTransfer.effectAllowed="move",z.dataTransfer.setData("text/tab-key",ve),Ce instanceof HTMLElement&&z.dataTransfer.setDragImage(Ce,Math.max(12,Math.round(Ce.clientWidth/2)),Math.max(10,Math.round(Ce.clientHeight/2)))}}};window.addEventListener("dragstart",K);const H=vo(j.current);for(const z of H)z.addEventListener("dragstart",K);return()=>{window.removeEventListener("dragstart",K);for(const z of H)z.removeEventListener("dragstart",K)}},[I]),o.useEffect(()=>{var H;const K=(H=k.current)==null?void 0:H.querySelector(".adhdev-dockview");K instanceof HTMLElement&&yr(K,P),de(),be(),ae()},[be,ae,de,P]),o.useEffect(()=>{be(),ae()},[be,ae]),o.useEffect(()=>{const K=H=>{if(H.defaultPrevented||Ue)return;const z=Ze(H);if(!z)return;const V=H.metaKey||H.ctrlKey||H.altKey;Un(H.target)&&!V||Kr(J).setActiveTabShortcut!==z||(H.preventDefault(),H.stopPropagation(),Qe())};return window.addEventListener("keydown",K,!0),()=>window.removeEventListener("keydown",K,!0)},[Ze,J,Ue,Qe]),o.useEffect(()=>{const K=k.current;if(!K)return;const H=z=>{var Ne,Fe;if(!z.isTrusted)return;const V=(Fe=(Ne=z.target)==null?void 0:Ne.closest)==null?void 0:Fe.call(Ne,".dv-scrollable");if(!V)return;z.preventDefault(),z.stopPropagation();const ee=Math.abs(z.deltaX),ve=Math.abs(z.deltaY),Ce=ee>ve?z.deltaX:z.deltaY;V.dispatchEvent(new WheelEvent("wheel",{deltaY:Ce,deltaMode:z.deltaMode,bubbles:!1,cancelable:!0}))};return K.addEventListener("wheel",H,{passive:!1,capture:!0}),()=>K.removeEventListener("wheel",H,{capture:!0})},[]),o.useEffect(()=>{const K=vo(j.current);if(K.length===0)return;const H=K.map(z=>{let V=[],ee=null;const ve=()=>{ee!=null&&z.clearTimeout(ee),ee=null,V=[]},Ce=()=>{ee!=null&&z.clearTimeout(ee),ee=z.setTimeout(()=>{ee=null,V=[]},1200)},Ne=We=>{if(!We.ctrlKey&&!We.metaKey&&!We.altKey)return;const je=Ze(We);if(!je)return;const Q=ec();for(const[Ee,ze]of Object.entries(Q))if(e.some(_=>_.tabKey===Ee)&&ze===je){We.preventDefault(),me(Ee);return}},Fe=We=>{if(We.defaultPrevented||Ue)return;const je=Ze(We);if(!je)return;const Q=We.metaKey||We.ctrlKey||We.altKey;if(Un(We.target)&&!Q)return;const Ee=Kr(J),ze=Object.entries(Ee).filter(([Be,st])=>!!st&&(Be==="splitActiveTabRight"||Be==="splitActiveTabDown"||Be==="floatActiveTab"||Be==="popoutActiveTab"||Be==="dockActiveTab"||Be==="focusLeftPane"||Be==="focusRightPane"||Be==="focusUpPane"||Be==="focusDownPane"||Be==="moveActiveTabToLeftPane"||Be==="moveActiveTabToRightPane"||Be==="moveActiveTabToUpPane"||Be==="moveActiveTabToDownPane"||Be==="selectPreviousGroupTab"||Be==="selectNextGroupTab"||Be==="setActiveTabShortcut"||Be==="hideCurrentTab")),_=Q?[je]:[...V.slice(-1),je].slice(-2),Y=_.join(" "),re=_[_.length-1],_e=ze.find(([,Be])=>Be===Y);if(_e){We.preventDefault(),ve(),ut(_e[0]);return}if(ze.some(([,Be])=>Be.startsWith(`${Y} `))){We.preventDefault(),V=_,Ce();return}const Pe=ze.find(([,Be])=>Be===re);if(Pe){We.preventDefault(),ve(),ut(Pe[0]);return}if(ze.some(([,Be])=>Be.startsWith(`${re} `))){We.preventDefault(),V=[re],Ce();return}ve()};return z.addEventListener("keydown",Ne),z.addEventListener("keydown",Fe),()=>{ve(),z.removeEventListener("keydown",Ne),z.removeEventListener("keydown",Fe)}});return()=>{for(const z of H)z()}},[Ze,J,I,me,Ue,ut,e]);const Mt=P==="light"?Tn:Mn,q=((ft=(Re=(Ke=j.current)==null?void 0:Ke.activePanel)==null?void 0:Re.group.element)==null?void 0:ft.ownerDocument)??document;return t.jsxs(oc.Provider,{value:qe,children:[t.jsx("div",{ref:k,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(Oc,{className:`h-full min-h-0 min-w-0 adhdev-dockview${R?" is-dragging-dockview":""}${U?" is-showing-dockview-overlay":""}`,components:{conversation:rf,remote:nf},defaultTabComponent:of,watermarkComponent:af,onReady:Nt,singleTabMode:"default",tabAnimation:"smooth",theme:Mt,popoutUrl:"/popout.html"})}),L&&qs.createPortal(t.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:L.x,top:L.y},children:ht.map(K=>{if(K.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},K.id);let H=t.jsx(Sl,{size:13,className:"shrink-0 opacity-70"}),z=()=>{};switch(K.id){case"dockInWindow":case"dockBackToGrid":H=t.jsx(Cl,{size:13,className:"shrink-0 opacity-70"}),z=()=>{le(L.tabKey),O(null)};break;case"moveBackToMain":H=t.jsx(kl,{size:13,className:"shrink-0 opacity-70"}),z=()=>{oe(L.tabKey),O(null)};break;case"floatAsPanel":H=t.jsx(Nl,{size:13,className:"shrink-0 opacity-70"}),z=()=>{se(L.tabKey),O(null)};break;case"openInNewWindow":H=t.jsx(jl,{size:13,className:"shrink-0 opacity-70"}),z=()=>{ge(L.tabKey),O(null)};break;case"setShortcut":z=V=>{V.stopPropagation(),De(L.tabKey),O(null)};break;case"removeShortcut":H=t.jsx(St,{size:13,className:"shrink-0 opacity-70"}),z=()=>{const V={...Se};delete V[L.tabKey],Ge(V),O(null)};break;case"hideTab":H=t.jsx(Fo,{size:13,className:"shrink-0 opacity-70"}),z=()=>{xe(L.tabKey),O(null)};break}return t.jsxs("button",{className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${K.tone==="muted"?"text-text-muted":""}`,onClick:z,children:[H,t.jsx("span",{className:"flex-1 min-w-0",children:K.label}),K.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:K.shortcut}):null]},K.id)})}),L.sourceDocument.body),Ue&&qs.createPortal(t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>De(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:K=>K.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",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"})]})}),q.body)]})}const ic="adhdev-recent-launch-args-v1",lf=8;function df(e){return String(e||"").trim().replace(/\s+/g," ")}function cc(e,s){return`${e.trim()}::${s.trim()}`}function lc(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(ic)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function uf(e){if(!(typeof window>"u"))try{window.localStorage.setItem(ic,JSON.stringify(e))}catch{}}function dc(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=lc().byKey[cc(r,n)])==null?void 0:i.items)||[]}function uc(e,s,r){var m;const n=String(e||"").trim(),a=String(s||"").trim(),i=df(r);if(!n||!a||!i)return;const c=lc(),l=cc(n,a),u=((m=c.byKey[l])==null?void 0:m.items)||[],p=[i,...u.filter(f=>f!==i)].slice(0,lf);c.byKey[l]={items:p},uf(c)}function mf(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 va(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 mc(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=va((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 pc(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function js(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 vn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function pf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function ko(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function So(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 ff(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function hf(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 xf(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 bf({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:a,onOpenConversation:i,onClose:c}){var G;const[l,u]=o.useState(n||((G=e[0])==null?void 0:G.id)||null),[p,m]=o.useState(""),[f,w]=o.useState(null),[S,T]=o.useState(!1);o.useEffect(()=>{var I;u(n||((I=e[0])==null?void 0:I.id)||null)},[n,e]);const d=o.useMemo(()=>e.find(I=>I.id===l)||e[0]||null,[l,e]),b=o.useMemo(()=>r.filter(I=>{if(I.type==="adhdev-daemon"||I.transport!=="pty")return!1;const B=pf(I.daemonId||I.id);return!!(d!=null&&d.id)&&B===d.id}),[d==null?void 0:d.id,r]),y=$i(d==null?void 0:d.id,{enabled:!!(d!=null&&d.id),includeSessions:!0,limit:6,intervalMs:1e4}),h=y.diagnostics,C=y.loading,P=y.applyDiagnostics,v=o.useMemo(()=>{const I=new Map;for(const B of b){const D=s.find(W=>W.sessionId===B.sessionId||W.routeId===B.id);B.sessionId&&D&&I.set(B.sessionId,D)}return I},[b,s]),j=o.useCallback(async()=>{if(d!=null&&d.id){T(!0);try{const I=await a(d.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),B=vn(I);if(!(B!=null&&B.success))throw new Error((B==null?void 0:B.error)||"Could not load hosted runtime diagnostics");P(B.diagnostics||B.result||null),m("")}catch(I){const B=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";m(B)}finally{T(!1)}}},[d==null?void 0:d.id,P,a]);o.useEffect(()=>{!(d!=null&&d.id)||h||C||S||j()},[d==null?void 0:d.id,h,C,j,S]);const k=o.useCallback(async(I,B)=>{if(!(d!=null&&d.id)||I==="session_host_stop_session"&&!window.confirm(`Stop ${B.displayName}?
55
+ This will terminate the hosted runtime.`))return;const D=`${I}:${B.sessionId}`;w(D);try{const W=await a(d.id,I,{sessionId:B.sessionId}),X=vn(W);if(!(X!=null&&X.success))throw new Error((X==null?void 0:X.error)||"Session host action failed");const we=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";ot.showToast(`Session host ${we}: ${B.displayName}`,"success"),await j()}catch(W){const X=W instanceof Error?W.message:"Session host action failed";m(X),ot.showToast(X,"warning")}finally{w(W=>W===D?null:W)}},[d==null?void 0:d.id,j,a]),g=o.useCallback(async()=>{if(!(!(d!=null&&d.id)||!window.confirm(`Prune duplicate hosted runtimes?
56
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){w("session_host_prune_duplicate_sessions");try{const B=await a(d.id,"session_host_prune_duplicate_sessions",{}),D=vn(B);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Duplicate prune failed");const W=D.result||{},X=Array.isArray(W.prunedSessionIds)?W.prunedSessionIds.length:0,we=typeof W.duplicateGroupCount=="number"?W.duplicateGroupCount:0;ot.showToast(`Pruned ${X} duplicate runtime(s) across ${we} group(s)`,"success"),await j()}catch(B){const D=B instanceof Error?B.message:"Duplicate prune failed";m(D),ot.showToast(D,"warning")}finally{w(B=>B==="session_host_prune_duplicate_sessions"?null:B)}}},[d==null?void 0:d.id,j,a]),x=o.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((I,B)=>(B.lastActivityAt||0)-(I.lastActivityAt||0)),[h==null?void 0:h.sessions]),$=o.useMemo(()=>h!=null&&h.liveRuntimes||h!=null&&h.recoverySnapshots||h!=null&&h.inactiveRecords?{liveRuntimes:(h==null?void 0:h.liveRuntimes)||[],recoverySnapshots:(h==null?void 0:h.recoverySnapshots)||[],inactiveRecords:(h==null?void 0:h.inactiveRecords)||[]}:mc(x),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,x]),A=$.liveRuntimes,M=$.recoverySnapshots,L=$.inactiveRecords,O=o.useMemo(()=>xf(A),[A]),R=o.useMemo(()=>[...(h==null?void 0:h.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[h==null?void 0:h.recentLogs]),N=o.useMemo(()=>[...(h==null?void 0:h.recentTransitions)||[]].slice(-3).reverse(),[h==null?void 0:h.recentTransitions]),U=(I,B)=>{var ae,ge;const D=v.get(I.sessionId),W=b.find(oe=>oe.sessionId===I.sessionId),X=f===`session_host_resume_session:${I.sessionId}`,we=f===`session_host_restart_session:${I.sessionId}`,Le=f===`session_host_stop_session:${I.sessionId}`,ie=va(I.meta),Ie=typeof((ae=I.meta)==null?void 0:ae.runtimeRecoveryError)=="string"?String(I.meta.runtimeRecoveryError):"",te=B==="recovery"?"Recover":"Resume",de=pc(B);return t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-3.5",children:[t.jsx("div",{className:"flex items-start justify-between gap-3",children:t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("div",{className:"text-[14px] font-bold text-text-primary",children:I.displayName||(W==null?void 0:W.runtimeDisplayName)||(W==null?void 0:W.cliName)||I.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${hf(I.lifecycle)}`,children:I.lifecycle}),ie&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:ie})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:I.workspaceLabel||(W==null?void 0:W.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),t.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:((ge=I.writeOwner)==null?void 0:ge.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:ff(I.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(Yn,{size:11})," ",I.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",So(I.lastActivityAt),I.osPid?` · pid ${I.osPid}`:"",` · Next: ${de}`]}),Ie&&t.jsx("div",{className:"mt-2 rounded-xl border border-red-500/[0.18] bg-red-500/[0.07] px-3 py-2 text-[11px] text-red-200",children:Ie})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[D&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(D),c()},children:"Open chat"}),B==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!f,onClick:()=>{k("session_host_resume_session",I)},children:X?`${te}ing…`:te}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!f,onClick:()=>{k("session_host_restart_session",I)},children:we?"Restarting…":"Restart"}),B==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn border-red-500/20 px-2.5 py-1 text-[11px] text-red-300 hover:text-red-200",disabled:!!f,onClick:()=>{k("session_host_stop_session",I)},children:Le?"Stopping…":"Stop"})]})]},I.sessionId)};return t.jsx("div",{className:"fixed inset-0 z-[115] flex items-end justify-center bg-black/55 backdrop-blur-[2px] md:items-center md:p-4",onClick:c,children:t.jsxs("div",{className:"w-full max-h-[88vh] overflow-hidden rounded-t-[28px] border border-border-subtle bg-bg-primary shadow-[0_-20px_60px_rgba(0,0,0,0.35)] md:max-w-3xl md:rounded-[28px] md:shadow-[0_20px_60px_rgba(0,0,0,0.35)]",onClick:I=>I.stopPropagation(),children:[t.jsx("div",{className:"mx-auto mt-3 h-1.5 w-12 rounded-full bg-border-subtle"}),t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 pt-4 pb-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Ot,{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:()=>{j()},disabled:C||S,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(_s,{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(St,{size:16})})]})]}),e.length>1&&t.jsx("div",{className:"flex gap-2 overflow-x-auto px-5 pb-3 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.map(I=>t.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${I.id===(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(I.id),children:I.label},I.id))}),t.jsxs("div",{className:"flex max-h-[calc(88vh-122px)] flex-col gap-3 overflow-y-auto px-5 pb-[calc(18px+env(safe-area-inset-bottom,0px))]",children:[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(ls,{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:So(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:ko(h.hostStartedAt)})]})]}),R&&t.jsxs("div",{className:"rounded-2xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-4 py-3",children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200",children:[t.jsx(ls,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:R.message})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Hr,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[O>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:f==="session_host_prune_duplicate_sessions",onClick:()=>{g()},children:f==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${O}`}),t.jsxs("div",{className:"text-[11px] text-text-secondary",children:[b.length," dashboard session",b.length===1?"":"s"]})]})]}),t.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:js("live")}),A.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:A.map(I=>U(I,"live"))}),t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recovery snapshots"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:js("recovery")}),M.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No recovery snapshots need attention."}):t.jsx("div",{className:"space-y-2",children:M.map(I=>U(I,"recovery"))})]}),L.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Inactive records"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:js("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:L.map(I=>U(I,"inactive"))})]}),N.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recent activity"}),t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary divide-y divide-border-subtle",children:N.map(I=>{const B=x.find(D=>D.sessionId===I.sessionId);return t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-2.5",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[12px] font-semibold text-text-primary",children:(B==null?void 0:B.displayName)||I.sessionId}),t.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:ko(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]})]})]})]})})}function Hs({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 fc({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?Xi(n):null;return t.jsxs(Hs,{title:"Saved history",description:ia(),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:ku()})]}),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 wn(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 vr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function gf({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:u,sendDaemonCommand:p,onOpenConversation:m}){var Nt,Mt;const f=tr(),w=o.useMemo(()=>[...e].sort(ea),[e]),[S,T]=o.useState(((Nt=w[0])==null?void 0:Nt.id)||""),d=o.useMemo(()=>w.find(q=>q.id===S)||w[0],[S,w]),b=o.useMemo(()=>((d==null?void 0:d.workspaces)||[]).map(q=>({id:q.id,path:q.path,label:q.label})),[d]),y=(d==null?void 0:d.defaultWorkspaceId)||null,[h,C]=o.useState(""),[P,v]=o.useState(""),[j,k]=o.useState(wn(w[0])),[g,x]=o.useState(""),[$,A]=o.useState(""),[M,L]=o.useState([]),[O,R]=o.useState(""),[N,U]=o.useState([]),[G,I]=o.useState(!1),[B,D]=o.useState(""),[W,X]=o.useState(!1),[we,Le]=o.useState(()=>gt()),[ie,Ie]=o.useState(!1),[te,de]=o.useState(null),[ae,ge]=o.useState(!1),[oe,F]=o.useState(""),[xe,se]=o.useState(!1),[pe,Z]=o.useState(""),[le,ne]=o.useState([]),[be,me]=o.useState(!1),[E,ye]=o.useState(""),[he,ke]=o.useState(!1),J=o.useRef(null),Se=o.useRef(0);o.useEffect(()=>{var q;!S&&((q=w[0])!=null&&q.id)&&T(w[0].id)},[S,w]),o.useEffect(()=>{!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||f(d.id,{minFreshMs:3e4}).catch(()=>{})},[f,d]);const Ue=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(q=>q.category==="cli"&&q.installed!==!1),[d]),De=o.useMemo(()=>((d==null?void 0:d.availableProviders)||[]).filter(q=>q.category==="acp"&&q.installed!==!1),[d]),Ge=o.useMemo(()=>((d==null?void 0:d.detectedIdes)||[]).map(q=>({id:q.type,label:q.name||q.type,meta:q.running?"Detected locally":"Available to open"})),[d]),Qe=o.useMemo(()=>j==="cli"?Ue.map(q=>({id:q.type,label:q.displayName||q.type,meta:"CLI provider"})):j==="acp"?De.map(q=>({id:q.type,label:q.displayName||q.type,meta:"ACP provider"})):Ge,[De,j,Ue,Ge]);o.useEffect(()=>{var Ke;if(!d)return;if(J.current!==d.id){J.current=d.id,C(y||((Ke=b[0])==null?void 0:Ke.id)||"__home__"),v(""),k(wn(d)),x(""),A(""),R(""),U([]),D(""),Le(gt()),F("");return}C(Re=>{var ft;return Re==="__custom__"||Re==="__home__"||b.some(K=>K.id===Re)?Re:y||((ft=b[0])==null?void 0:ft.id)||"__home__"}),k(Re=>Re==="ide"&&Ge.length>0||Re==="cli"&&Ue.length>0||Re==="acp"&&De.length>0?Re:wn(d))},[De.length,Ue.length,y,Ge.length,d,b]),o.useEffect(()=>{var q;j&&(Qe.some(Ke=>Ke.id===g)||x(((q=Qe[0])==null?void 0:q.id)||""))},[j,Qe,g]);const Ze=o.useCallback(async(q,Ke)=>{const Re=Se.current+1;return Se.current=Re,I(!0),D(""),u(q,Ke).then(ft=>{Se.current===Re&&U(ft)}).catch(ft=>{Se.current===Re&&(U([]),D(ft instanceof Error?ft.message:"Could not load saved sessions"))}).finally(()=>{Se.current===Re&&I(!1)})},[u]),ut=o.useCallback((q,Ke)=>{L(dc(q,Ke))},[]);o.useEffect(()=>{if(R(""),Le(gt()),!d||!g||j==="ide"?L([]):ut(d.id,g),j!=="cli"){U([]),D(""),I(!1);return}if(!d||!g){U([]),D(""),I(!1);return}Ze(d.id,g)},[j,ut,Ze,d,g]),o.useEffect(()=>{if(!O)return;const q=N.find(Ke=>Ke.providerSessionId===O);q!=null&&q.canResume||R("")},[N,O]);const qe=h==="__custom__"?P.trim():h==="__home__"?"":((Mt=b.find(q=>q.id===h))==null?void 0:Mt.path)||"",ht=o.useMemo(()=>d?r.filter(q=>q.id!==d.id&&q.daemonId===d.id).map(q=>q.workspace):[],[r,d]),mt=o.useMemo(()=>((d==null?void 0:d.recentLaunches)||[]).map(q=>q.workspace),[d]),tt=o.useCallback(q=>{const Ke=String(q.workspace||"").trim();if(!Ke)return;const Re=b.find(ft=>vr(ft.path)===vr(Ke));if(Re){C(Re.id),v("");return}C("__custom__"),v(Ke)},[b]),xt=o.useCallback(q=>{const Ke=String(q.workspace||"").trim();if(!Ke)return{workspaceId:null,workspacePath:null};const Re=b.find(ft=>vr(ft.path)===vr(Ke));return Re?{workspaceId:Re.id,workspacePath:null}:{workspaceId:null,workspacePath:Ke}},[b]),pt=o.useMemo(()=>N.find(q=>q.providerSessionId===O)||null,[N,O]),ce=o.useMemo(()=>{var Ke;if(j!=="cli"||!d||!g)return null;const q=((Ke=Ue.find(Re=>Re.type===g))==null?void 0:Ke.displayName)||g;return{routeId:d.id,daemonId:d.id,providerSessionId:O||void 0,transport:"pty",mode:"chat",agentName:q,agentType:g,status:"idle",title:q,messages:[],ideType:g,workspaceName:qe,displayPrimary:q,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${d.id}:${g}`,machineName:It(d,{fallbackId:d.id})}},[j,Ue,qe,d,O,g]),Ve=o.useCallback(()=>{var Ke;if(!d)return;C("__custom__"),se(!0),ye("");const q=Yr(d.platform,qr(P.trim(),qe,ht,mt,d.defaultWorkspacePath,(Ke=b.find(Re=>Re.id===y))==null?void 0:Ke.path,b.map(Re=>Re.path)));me(!0),a(d.id,q).then(Re=>{Z(Re.path),v(Re.path),ne(Re.directories)}).catch(Re=>{ye(Re instanceof Error?Re.message:"Could not load folder")}).finally(()=>me(!1))},[P,y,mt,ht,a,qe,d,b]),ct=o.useCallback(q=>{d&&(me(!0),ye(""),a(d.id,q).then(Ke=>{Z(Ke.path),v(Ke.path),ne(Ke.directories)}).catch(Ke=>{ye(Ke instanceof Error?Ke.message:"Could not load folder")}).finally(()=>me(!1)))},[a,d]),Je=o.useCallback(async()=>{if(!d||!qe)return;ke(!0),F("");const q=await i(d.id,qe);if(ke(!1),!q.ok){F(q.error||"Could not save workspace");return}F("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,qe,d]),bt=o.useCallback(async()=>{if(!d||!j||!g)return;ge(!0),F("");const q=$.trim()?$.trim().split(/\s+/).filter(Boolean):[],Ke=j==="ide"?await c(d.id,g,{workspacePath:qe||null}):await l(d.id,j,g,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&qe||null,resumeSessionId:j==="cli"&&O?O:null,cliArgs:q});if(ge(!1),!Ke.ok){F(Ke.error||"Could not start session");return}j!=="ide"&&$.trim()&&(uc(d.id,g,$),ut(d.id,g)),n()},[j,$,ut,n,c,l,qe,d,O,g,h]),jt=j?vi(j,j==="cli"&&!!O):"Start",kt=j?wi(j,j==="cli"&&!!O):"Starting…";return d?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:t.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start or recover session"}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh, resume saved history, or recover a hosted runtime."})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:n,"aria-label":"Close new session dialog",children:t.jsx(St,{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(Hs,{title:"Machine",children:t.jsx("select",{value:d.id,onChange:q=>T(q.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ae,children:w.map(q=>t.jsx("option",{value:q.id,children:It(q,{fallbackId:q.id})},q.id))})}),j==="cli"&&t.jsx(Hs,{title:"Hosted runtimes",description:"Review live runtimes, recovery snapshots, and recover or restart options without leaving this launch flow.",action:t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:ae||!d,onClick:()=>Ie(!0),children:[t.jsx(Ot,{size:14}),wu()]})}),t.jsxs(Hs,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ve,disabled:ae,children:"Browse…"}),children:[t.jsxs("select",{value:h,onChange:q=>{const Ke=q.target.value;C(Ke),Ke==="__custom__"?Ve():F("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ae,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),b.map(q=>t.jsxs("option",{value:q.id,children:[q.id===y?"⭐ ":"",Vr(q.path,q.label)||q.path]},q.id)),t.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h==="__home__"?"Launch without a workspace.":qe||"Select a workspace folder."}),h==="__custom__"&&qe&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ve,disabled:ae,children:[t.jsx(Ss,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Je,disabled:ae||he,children:he?"Saving…":"Save workspace"})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:Ue.length>0},{id:"ide",label:"IDE",enabled:Ge.length>0},{id:"acp",label:"ACP",enabled:De.length>0}].map(q=>t.jsx("button",{type:"button",className:`btn btn-sm ${j===q.id?"btn-primary":"btn-secondary"}`,onClick:()=>k(q.id),disabled:!q.enabled||ae,children:q.label},q.id))})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:j==="ide"?"Choose IDE":j==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Qe.map(q=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${g===q.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>x(q.id),disabled:ae,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:q.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:q.meta})]},q.id)),Qe.length===0&&t.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),j!=="ide"&&t.jsxs(Hs,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:$,onChange:q=>A(q.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:ae}),M.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:M.map(q=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>A(q),disabled:ae,title:q,children:q},q))})]}),j==="cli"&&t.jsx(fc,{busy:ae,savedSessionsLoading:G,savedSessionsError:B,selectedSession:pt,onRefresh:()=>{!d||!g||Ze(d.id,g)},onOpenHistory:()=>{!d||!g||(X(!0),Ze(d.id,g))},onClearSelection:()=>R("")}),oe&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${oe.includes("saved")||oe.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:oe})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:n,disabled:ae,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:bt,disabled:ae||!j||!g||h==="__custom__"&&!qe,children:[t.jsx(Qn,{size:14}),ae?kt:jt]})]})]})}),xe&&t.jsx(Qr,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:pe,directories:le,busy:be,error:E,onClose:()=>se(!1),onNavigate:ct,onConfirm:q=>{v(q),Z(q),C("__custom__"),se(!1)}}),W&&ce&&t.jsx(da,{activeConv:ce,ides:[],isCreatingChat:!1,isRefreshingHistory:G,savedSessions:N,isSavedSessionsLoading:G,isResumingSavedSessionId:te,savedHistoryFilters:we,onSavedHistoryFiltersChange:Le,onClose:()=>X(!1),onNewChat:()=>{R(""),X(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!d||!g||Ze(d.id,g)},onResumeSavedSession:q=>{if(!d||!g||te||!q.canResume)return;const Ke=xt(q);R(q.providerSessionId),tt(q),de(q.providerSessionId),X(!1),ge(!0),F(""),l(d.id,"cli",g,{workspaceId:Ke.workspaceId,workspacePath:Ke.workspacePath,resumeSessionId:q.providerSessionId}).then(Re=>{if(!Re.ok){F(Re.error||"Could not resume session");return}n()}).finally(()=>{ge(!1),de(Re=>Re===q.providerSessionId?null:Re)})}}),ie&&d&&t.jsx(bf,{machineCards:[{id:d.id,label:It(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",Ji(d)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:d.id,sendDaemonCommand:p,onOpenConversation:q=>{Ie(!1),n(),m(q)},onClose:()=>Ie(!1)})]}):null}function yf(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 vf(e){return e instanceof Error?e.message:String(e||"")}function wf(e){const s=vf(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function jf({showMobileChatMode:e,isMobile:s,activeConv:r,chatIdes:n,wsStatus:a,isConnected:i,onOpenHistory:c,onOpenRemote:l,onStopCli:u,activeCliViewMode:p,onSetActiveCliViewMode:m,mobileChatConversations:f,hiddenConversations:w,ides:S,actionLogs:T,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,initialDataLoaded:C,userName:P,requestedMobileTabKey:v,onRequestedMobileTabConsumed:j,requestedMachineId:k,onRequestedMachineConsumed:g,requestedMobileSection:x,onRequestedMobileSectionConsumed:$,containerRef:A,isSplitMode:M,numGroups:L,groupSizes:O,groupedConvs:R,clearedTabs:N,focusedGroup:U,setFocusedGroup:G,moveTabToGroup:I,splitTabRelative:B,closeGroup:D,handleResizeStart:W,groupActiveTabIds:X,setGroupActiveTabIds:we,groupTabOrders:Le,setGroupTabOrders:ie,toggleHiddenTab:Ie,visibleConversations:te,requestedDesktopTabKey:de,onRequestedDesktopTabConsumed:ae,onDesktopActiveTabChange:ge,onHideConversation:oe,onShowHiddenConversation:F,onShowAllHiddenConversations:xe,scrollToBottomRequest:se,machineEntries:pe,onBrowseMachineDirectory:Z,onSaveMachineWorkspace:le,onLaunchMachineIde:ne,onLaunchMachineProvider:be,onListMachineSavedSessions:me,notifications:E,notificationUnreadCount:ye,notificationStateBySessionId:he,onMarkNotificationRead:ke,onMarkNotificationUnread:J,onDeleteNotification:Se,onMarkNotificationTargetRead:Ue}){const De=nt.useRef(null),[Ge,Qe]=nt.useState(!1),[Ze,ut]=nt.useState(!1),[qe,ht]=nt.useState(!1),[mt,tt]=nt.useState(!1),xt=nt.useCallback(Q=>{var Ee;qs.flushSync(()=>{F(Q)}),(Ee=De.current)==null||Ee.restoreHiddenTabToSavedLocation(Q.tabKey)},[F]),pt=nt.useCallback(Q=>{var ze;const Ee=f.find(_=>Q.sessionId&&_.sessionId===Q.sessionId?!0:!!Q.tabKey&&_.tabKey===Q.tabKey)||w.find(_=>Q.sessionId&&_.sessionId===Q.sessionId?!0:!!Q.tabKey&&_.tabKey===Q.tabKey);Ee&&(w.some(_=>_.tabKey===Ee.tabKey)&&xt(Ee),ge(Ee.tabKey),(ze=De.current)==null||ze.activateConversationTab(Ee.tabKey)),ke(Q.id),(Q.sessionId||Q.providerSessionId||Q.tabKey)&&Ue({sessionId:Q.sessionId,providerSessionId:Q.providerSessionId,tabKey:Q.tabKey}),Qe(!1)},[xt,w,f,ge,ke,Ue]),[ce,Ve]=nt.useState(!1),[ct,Je]=nt.useState("quickstart"),[bt,jt]=nt.useState("workspace"),kt=!e&&!s,Nt=nt.useCallback(Q=>{Qe(Q),Q&&ut(!1)},[]),Mt=nt.useCallback(Q=>{ut(Q),Q&&Qe(!1)},[]),q=nt.useCallback(()=>{var Ee;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Ee=De.current)==null||Ee.resetAllPanelsToMain(),ut(!1))},[]),Ke=nt.useCallback(()=>{Je(te.length===0?"quickstart":"shortcuts"),jt("workspace"),ht(!0),Qe(!1),ut(!1)},[te.length]),Re=nt.useCallback(async Q=>{var re;if(!r)return;const Ee=(re=r.modalButtons)==null?void 0:re[Q];if(!Ee)return;const ze=Js(r);if(!ze)return;const _=Ee.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Y=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(_);try{await d(ze,"resolve_action",{button:Ee,action:Y?"approve":"reject",buttonIndex:Q,...ws(r)})}catch(_e){wf(_e)||console.error("[Shortcut approval] Failed:",_e)}},[r,d]),{isMac:ft,actionDefinitions:K,actionShortcuts:H,shortcutListening:z,shortcutListeningDraft:V,setShortcutListening:ee,setShortcutListeningDraft:ve,saveShortcuts:Ce}=Qp({enabled:kt&&!qe,onTrigger:Q=>{var Ee,ze,_,Y,re,_e,Me,Pe,$e,Be,st,Ft,Yt,rr,Xt,nr;if(Q==="openShortcutHelp"){Ke();return}if(Q==="hideCurrentTab"){r&&oe(r);return}if(Q==="toggleHiddenTabs"){Mt(!Ze);return}if(Q==="openHistoryForActiveTab"){r&&!Xe(r)&&c(r);return}if(Q==="openRemoteForActiveTab"){r&&!et(r)&&!Xe(r)&&l(r);return}if(Q==="splitActiveTabRight"){(Ee=De.current)==null||Ee.splitActiveTabRight();return}if(Q==="splitActiveTabDown"){(ze=De.current)==null||ze.splitActiveTabDown();return}if(Q==="floatActiveTab"){(_=De.current)==null||_.floatActiveTab();return}if(Q==="popoutActiveTab"){(Y=De.current)==null||Y.popoutActiveTab();return}if(Q==="dockActiveTab"){(re=De.current)==null||re.dockActiveTab();return}if(Q==="focusLeftPane"){(_e=De.current)==null||_e.focusLeftPane();return}if(Q==="focusRightPane"){(Me=De.current)==null||Me.focusRightPane();return}if(Q==="focusUpPane"){(Pe=De.current)==null||Pe.focusUpPane();return}if(Q==="focusDownPane"){($e=De.current)==null||$e.focusDownPane();return}if(Q==="moveActiveTabToLeftPane"){(Be=De.current)==null||Be.moveActiveTabToLeftPane();return}if(Q==="moveActiveTabToRightPane"){(st=De.current)==null||st.moveActiveTabToRightPane();return}if(Q==="moveActiveTabToUpPane"){(Ft=De.current)==null||Ft.moveActiveTabToUpPane();return}if(Q==="moveActiveTabToDownPane"){(Yt=De.current)==null||Yt.moveActiveTabToDownPane();return}if(Q==="triggerPrimaryApprovalAction"){Re(0);return}if(Q==="triggerSecondaryApprovalAction"){Re(1);return}if(Q==="triggerTertiaryApprovalAction"){Re(2);return}if(Q==="setActiveTabShortcut"){(rr=De.current)==null||rr.setShortcutForActiveTab();return}if(Q==="selectPreviousGroupTab"){(Xt=De.current)==null||Xt.activatePreviousTabInGroup();return}if(Q==="selectNextGroupTab"){(nr=De.current)==null||nr.activateNextTabInGroup();return}!r||!et(r)||Xe(r)||Q==="toggleCliView"&&m(p==="chat"?"terminal":"chat")}}),Ne=nt.useCallback(()=>{ht(!1),ee(null),ve([])},[ee,ve]),Fe=nt.useMemo(()=>bt==="all"?K:K.filter(Q=>yf(Q)===bt),[K,bt]),We=nt.useCallback(()=>{const Q=Object.fromEntries(K.map(Ee=>[Ee.id,""]));Ce(Q)},[K,Ce]),je=nt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Q=Object.fromEntries(K.map(Ee=>[Ee.id,Ee.defaultShortcut]));Ce(Q)},[K,Ce]);return nt.useEffect(()=>{const Q=Ee=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Ee.metaKey&&Ee.key.toLowerCase()==="w":Ee.ctrlKey&&Ee.key.toLowerCase()==="w")&&(Ee.preventDefault(),r&&oe&&oe(r))};return window.addEventListener("keydown",Q),()=>window.removeEventListener("keydown",Q)},[r,oe]),nt.useEffect(()=>{if(!qe||z)return;const Q=Ee=>{Ee.key==="Escape"&&(Ee.preventDefault(),Ne())};return window.addEventListener("keydown",Q,!0),()=>window.removeEventListener("keydown",Q,!0)},[Ne,qe,z]),nt.useEffect(()=>{if(!kt){Ve(!1);return}Ve(!0);const Q=window.setTimeout(()=>{Ve(!1)},1e4);return()=>window.clearTimeout(Q)},[kt]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(xu,{activeConv:r,agentCount:n.length,wsStatus:a,isConnected:i,conversations:te,hiddenConversations:w,onOpenHistory:c,onHideConversation:oe,onShowConversation:xt,onShowAllHidden:xe,onResetPanelsToMain:q,notifications:E,notificationUnreadCount:ye,onOpenNotification:pt,onMarkNotificationRead:ke,onMarkNotificationUnread:J,onDeleteNotification:Se,inboxOpen:Ge,onInboxOpenChange:Nt,hiddenOpen:Ze,onHiddenOpenChange:Mt,onOpenNewSession:s?void 0:()=>tt(!0),actionShortcuts:H,onOpenRemote:()=>{!r||et(r)||Xe(r)||l(r)},onStopCli:u,activeCliViewMode:p,onSetCliViewMode:m}),e?t.jsx(Kp,{conversations:f,hiddenConversations:w,ides:S,actionLogs:T,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,userName:P,requestedActiveTabKey:v,onRequestedActiveTabConsumed:j,requestedMachineId:k,onRequestedMachineConsumed:g,requestedMobileSection:x,onRequestedMobileSectionConsumed:$,onOpenHistory:c,onOpenRemote:l,onStopCli:u,wsStatus:a,isConnected:i,onShowHiddenConversation:xt,onShowAllHiddenConversations:xe,onOpenNewSession:()=>tt(!0),notificationStateBySessionId:he,onMarkNotificationTargetRead:Ue}):s?t.jsx(Gp,{containerRef:A,isSplitMode:M,numGroups:L,groupSizes:O,groupedConvs:R,clearedTabs:N,ides:S,actionLogs:T,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,hasRegisteredMachines:pe.length>0,userName:P,focusedGroup:U,setFocusedGroup:G,moveTabToGroup:I,splitTabRelative:B,closeGroup:D,handleResizeStart:W,groupActiveTabIds:X,setGroupActiveTabIds:we,groupTabOrders:Le,setGroupTabOrders:ie,toggleHiddenTab:Ie,allowTabShortcuts:!1}):t.jsx(cf,{visibleConversations:te,clearedTabs:N,ides:S,actionLogs:T,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,hasRegisteredMachines:pe.length>0,initialDataLoaded:C,userName:P,toggleHiddenTab:Ie,actionShortcuts:H,registerActionHandlers:Q=>{De.current=Q},notificationStateBySessionId:he,onActiveTabChange:ge,requestedActiveTabKey:de,onRequestedActiveTabConsumed:ae,scrollToBottomRequest:se}),mt&&t.jsx(gf,{machines:pe,conversations:f,ides:S,onClose:()=>tt(!1),onBrowseDirectory:Z,onSaveWorkspace:le,onLaunchIde:ne,onLaunchProvider:be,onListSavedSessions:me,sendDaemonCommand:d,onOpenConversation:Q=>{tt(!1),F(Q),ge(Q.tabKey)}}),qe&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:Ne,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:Q=>Q.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:Ne,"aria-label":"Close dashboard guide",children:t.jsx(St,{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(Q=>t.jsx("button",{type:"button",className:`btn btn-sm ${ct===Q.id?"btn-primary":"btn-secondary"}`,onClick:()=>Je(Q.id),children:Q.label},Q.id))}),ct==="overview"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",ft?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ct==="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."]})]})]})]}),ct==="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(Q=>t.jsx("button",{type:"button",className:`btn btn-sm ${bt===Q.id?"btn-primary":"btn-secondary"}`,onClick:()=>jt(Q.id),children:Q.label},Q.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:We,children:"Disable all"}),t.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:je,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:Fe.map(Q=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${z===Q.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:Q.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Q.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:Q.defaultShortcut})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:z===Q.id?V.length>0?`${V.join(" ")} ...`:"Listening...":H[Q.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{ee(Q.id),ve([])},children:z===Q.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Ee={...H};Ee[Q.id]="",Ce(Ee)},children:"Disable"})]})]})},Q.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",ft?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:Ke,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 ${ce?"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:"?"}),ce&&t.jsx("span",{children:"Guide"})]})]})}const jn=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Monitor and control your AI coding agents from anywhere — web, mobile, or CLI.",visual:"🎉"},{icon:"💬",title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:"📱"},{icon:"🖥️",title:"Remote desktop",desc:"View and control your IDE screen via P2P connection. Click, type, scroll — just like being there.",visual:"🖱️"},{icon:"🚀",title:"Get started",desc:"Install the daemon and link it to your dashboard. It connects automatically.",code:"npm install -g @adhdev/daemon-standalone && adhdev-standalone"}];function kf({onClose:e}){const[s,r]=o.useState(0),n=jn[s],a=s===jn.length-1;return t.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.target===i.currentTarget&&e()},children:[t.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[t.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:t.jsx(St,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:jn.map((i,c)=>t.jsx("div",{style:{width:c===s?24:8,height:8,borderRadius:4,background:c===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),t.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),t.jsxs("div",{style:{textAlign:"center"},children:[t.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[t.jsx("span",{children:n.icon})," ",n.title]}),t.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&t.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[t.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),t.jsxs("div",{className:"flex justify-between items-center mt-6",children:[t.jsx("button",{onClick:e,className:"btn btn-secondary border-none",children:"Skip"}),t.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})]})]}),t.jsx("style",{children:`
57
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
58
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
59
+ `})]})}function Sf({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 Nf({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),u=o.useMemo(()=>ki(s),[s]),p=o.useMemo(()=>e?ua(e,n,{machineNames:u,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,u,r]),m=o.useMemo(()=>p.find(b=>b.streamSource==="native"),[p]),f=o.useMemo(()=>p.filter(b=>b.streamSource==="agent-stream"),[p]),w=o.useMemo(()=>e?Bt(p,e.id):null,[p,e]);o.useEffect(()=>{i&&l(i)},[i]),o.useEffect(()=>{if(i||!w)return;const b=w.streamSource==="native"?"native":w.tabKey;!b||c===b||c==="native"&&l(b)},[c,w,i]),o.useEffect(()=>{var b;c!=="native"&&(f.some(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 S=o.useMemo(()=>c==="native"&&m?m:f.find(b=>b.tabKey===c)||w||m||f[0],[c,m,w,f]),T=o.useMemo(()=>f.map(b=>({tabKey:b.tabKey,title:bi(b)||a,status:b.status})),[f,a]),d=o.useCallback(b=>{if(b)return p.find(y=>y.sessionId===b||y.routeId===b||y.tabKey===b)},[p]);return{activeChatTab:c,setActiveChatTab:l,activeConv:S,conversations:p,extensionTabs:T,hasExtensions:T.length>0,resolveConversationByTarget:d}}function Cf({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:u,isStandalone:p,userName:m,onOpenHistory:f,onConversationChange:w,onClose:S}){const[T,d]=o.useState("split"),[b,y]=o.useState(()=>Vt(e)?"native":e.tabKey),h=o.useRef(null),C=o.useMemo(()=>s||r.find(I=>I.id===e.routeId),[e.routeId,s,r]),P=o.useMemo(()=>at((C==null?void 0:C.type)||""),[C==null?void 0:C.type]),{conversations:v,extensionTabs:j,hasExtensions:k}=Nf({ideData:C,allIdes:r,connectionStates:n,localUserMessages:i,ideName:P||"IDE",preferredTabKey:Vt(e)?void 0:e.tabKey}),g=o.useMemo(()=>C?Bt(v,C.id):null,[C,v]);o.useEffect(()=>{const I=h.current,B={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=B,!(I&&I.routeId===B.routeId&&I.tabKey===B.tabKey&&I.streamSource===B.streamSource)){if(Vt(e)){y("native");return}y(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(b==="native"){if(v.some(I=>I.streamSource==="native"))return;(g==null?void 0:g.streamSource)==="agent-stream"&&y(g.tabKey);return}if(!v.some(I=>I.tabKey===b)){if((g==null?void 0:g.streamSource)==="agent-stream"){y(g.tabKey);return}y("native")}},[v,b,g]);const x=o.useMemo(()=>b==="native"?v.find(I=>I.streamSource==="native")||e:v.find(I=>I.tabKey===b)||e,[e,v,b]),$=Bi(x),A=o.useMemo(()=>$.status||$.modalMessage||$.modalButtons?{...x,...$.status?{status:$.status}:{},...$.modalMessage!==void 0?{modalMessage:$.modalMessage}:{},...$.modalButtons!==void 0?{modalButtons:$.modalButtons}:{}}:x,[x,$]),M=er(A),L=Gr({sendDaemonCommand:c,activeConv:A,setLocalUserMessages:l,setActionLogs:u,isStandalone:p}),{connScreenshot:O,screenshotUsage:R,handleRemoteAction:N}=sc({doId:M,targetSessionId:ra(A),connState:A.connectionState||"new",viewMode:T}),U=o.useMemo(()=>a.filter(I=>I.routeId===A.tabKey),[a,A.tabKey]);o.useEffect(()=>{w==null||w(A)},[A,w]),o.useEffect(()=>{const I=B=>{B.key==="Escape"&&S()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[S]);const G=o.useCallback(I=>{I.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:S,children:t.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:G,children:[t.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[t.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[t.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(At,{size:16})}),t.jsx("span",{className:"truncate",children:sa(x)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:S,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(I=>{const B=T===I;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${B?"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(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?t.jsx(ll,{size:15}):t.jsx(At,{size:15})},I)})}),t.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),t.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>f(x),title:"Chat History",children:[t.jsx(Xn,{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:S,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${T==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[T!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${T==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(Sf,{hasExtensions:k,ideName:P||"IDE",activeChatTab:b,extensionTabs:j,onSelectTab:y}),t.jsx(Qo,{activeConv:A,onModalButton:L.handleModalButton}),t.jsx(En,{activeConv:A,ideEntry:C,showMetaChips:!1,handleSendChat:L.handleSendChat,isSendingChat:L.isSendingChat,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:U,userName:m})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${T==="split"?"order-1 md:order-2":""}`,children:t.jsx(Yo,{addLog:()=>{},connState:A.connectionState||"new",connScreenshot:O,screenshotUsage:R,transportType:A.transport,onAction:N})})]})]})})}function If({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=mu(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 Af({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:a,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:u,onNewHistoryChat:p,onSwitchHistorySession:m,onRefreshHistory:f,onResumeSavedHistorySession:w,remoteDialogConv:S,remoteDialogIdeEntry:T,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:h,setLocalUserMessages:C,setActionLogs:P,isStandalone:v,userName:j,onOpenRemoteHistory:k,onRemoteConversationChange:g,onCloseRemoteDialog:x,cliStopDialogOpen:$,cliStopTargetConv:A,onCancelCliStop:M,onStopCliNow:L,onSaveCliAndStop:O,toasts:R,onDismissToast:N,onClickToast:U,showOnboarding:G,onCloseOnboarding:I}){var W;const[B,D]=nt.useState(()=>gt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(da,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:B,onSavedHistoryFiltersChange:D,onClose:u,onNewChat:p,onSwitchSession:m,onRefreshHistory:f,onResumeSavedSession:w}),S&&t.jsx(Cf,{activeConv:S,ideEntry:T,ides:r,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:h,setLocalUserMessages:C,setActionLogs:P,isStandalone:v,userName:j,onOpenHistory:k,onConversationChange:g,onClose:x}),$&&A&&(et(A)||Xe(A))&&t.jsx(If,{activeConv:A,canSaveAndStop:et(A)&&!Xe(A)&&!!((W=A.resume)!=null&&W.supported),onCancel:M,onStopNow:L,onSaveAndStop:O}),t.jsx(ji,{toasts:R,onDismiss:N,onClickToast:U}),G&&t.jsx(kf,{onClose:I})]})}function Tf({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(_s,{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=It(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(St,{size:16})})]})}function Mf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function No(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Lf(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function _f(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function Rf(){var Na,Ca,Ia,Aa,Ta;const{sendCommand:e}=Tt(),s=tr(),r=Gn(),n=Ls(),[a,i]=Hc(),c=a.get("activeTab"),l=((Na=r.state)==null?void 0:Na.openRemoteForTabKey)||null,u=((Ca=r.state)==null?void 0:Ca.openMachineId)||null,p=((Ia=r.state)==null?void 0:Ia.mobileSection)||null,m=pi(),f=m.ides||[],w=m.initialLoaded??!0,{updateRouteChats:S,setToasts:T}=m,[d,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=m.toasts||[],h=m.wsStatus||"connected",C=m.isConnected??!0,P=m.connectionStates||{},v=m.showReconnected||!1,{groupAssignments:j,setGroupAssignments:k,focusedGroup:g,setFocusedGroup:x,groupActiveTabIds:$,setGroupActiveTabIds:A,groupTabOrders:M,setGroupTabOrders:L,groupSizes:O,setGroupSizes:R,isMobile:N,hasHydratedStoredLayout:U,hydrateStoredLayout:G}=zm(),[I,B]=o.useState(!1),[D,W]=o.useState(!1),[X,we]=o.useState(null),[Le,ie]=o.useState([]),[Ie,te]=o.useState(!1),[de,ae]=o.useState(null),[ge]=o.useState(()=>Ei()),[oe,F]=o.useState([]),[xe,se]=o.useState({}),[pe,Z]=o.useState({}),[le,ne]=o.useState({}),[be,me]=o.useState(null),[E,ye]=o.useState(null),[he,ke]=o.useState(null),J=o.useRef(null);Zs("Dashboard",{ideCount:f.length,toastCount:y.length,focusedGroup:g,groupCount:Object.keys(j).length,localMessageTabs:Object.keys(xe).length,actionLogCount:oe.length});const Se=f.find(fe=>fe.type==="adhdev-daemon"),Ue=o.useMemo(()=>f.filter(fe=>fe.type==="adhdev-daemon").sort(ea),[f]),De=!!Se;o.useEffect(()=>{!Se||!(!Se.detectedIdes||!Se.availableProviders||!Se.recentLaunches||!Se.workspaces)||s(Se.id,{minFreshMs:3e4}).catch(()=>{})},[Se,s]);const Ge=(Se==null?void 0:Se.terminalBackend)||null,Qe=Se?It(Se,{fallbackId:Se.id}):null,Ze=(Se==null?void 0:Se.id)||null,ut=o.useMemo(()=>gm(f,pe),[f,pe]),{hiddenTabs:qe,hideTab:ht,toggleTab:mt,showTab:tt,showAllTabs:xt}=bm(),{chatIdes:pt,conversations:ce,visibleConversations:Ve,visibleTabKeys:ct,resolveConversationBySessionId:Je,resolveConversationByTarget:bt}=_m({ides:ut,connectionStates:P,localUserMessages:xe,clearedTabs:le,hiddenTabs:qe});su(ce),o.useEffect(()=>{Object.keys(pe).length!==0&&Z(fe=>ym(fe,f))},[f,pe]);const jt=o.useMemo(()=>zr(f),[f]),{notifications:kt,unreadCount:Nt,notificationStateBySessionId:Mt,markRead:q,markUnread:Ke,markTargetRead:Re,deleteNotification:ft}=fp({conversations:ce,liveSessionInboxState:jt}),K=o.useRef(null),{containerRef:H,normalizedGroupAssignments:z,numGroups:V,isSplitMode:ee,groupedConvs:ve,moveTabToGroup:Ce,closeGroup:Ne,handleResizeStart:Fe,splitTabRelative:We}=Zm({groupAssignments:j,setGroupAssignments:k,setFocusedGroup:x,setGroupActiveTabIds:A,setGroupTabOrders:L,groupSizes:O,setGroupSizes:R,isMobile:N,visibleConversations:Ve,visibleTabKeys:ct}),je=o.useMemo(()=>{var Ae,Te;if(!N){if(be){const ue=ce.find(Oe=>Oe.tabKey===be);if(ue)return ue}return Ve[0]}const fe=$[g];if(fe){const ue=ce.find(Oe=>Oe.tabKey===fe);if(ue)return ue}return((Ae=ve[g])==null?void 0:Ae[0])||((Te=ve[0])==null?void 0:Te[0])},[be,N,$,g,ce,ve,Ve]);o.useEffect(()=>{if(N){K.current=null;return}if(!(je!=null&&je.sessionId)){K.current=null;return}const fe=_r(je,jt),Ae=[je.tabKey,je.providerSessionId||je.sessionId,je.lastMessageHash||"",String(je.lastMessageAt||0),fe.inboxBucket,fe.unread?"1":"0"].join(":");if(K.current===Ae)return;const Te=()=>{if(document.visibilityState!=="visible"||K.current===Ae)return;K.current=Ae;const ue=Math.max(Date.now(),os(je),fe.lastUpdated||0);Re({sessionId:je.sessionId,providerSessionId:je.providerSessionId,tabKey:je.tabKey},ue),e(je.daemonId||je.routeId,"mark_session_seen",{sessionId:je.sessionId,seenAt:ue}).catch(()=>{})};if(document.visibilityState==="visible"){const ue=setTimeout(Te,1500),Oe=()=>{document.visibilityState!=="visible"&&clearTimeout(ue)};return document.addEventListener("visibilitychange",Oe),()=>{clearTimeout(ue),document.removeEventListener("visibilitychange",Oe)}}else{const ue=()=>{document.visibilityState==="visible"&&(setTimeout(Te,800),document.removeEventListener("visibilitychange",ue))};return document.addEventListener("visibilitychange",ue),()=>{document.removeEventListener("visibilitychange",ue)}}},[je,N,jt,Re,e]);const{requestedDesktopTabKey:Q,requestedMobileTabKey:Ee,consumeRequestedActiveTab:ze}=Rm({isMobile:N,urlActiveTab:c,resolveConversationBySessionId:Je,setSearchParams:i}),{remoteDialogConv:_,remoteDialogIdeEntry:Y,remoteDialogActiveConv:re,setRemoteDialogActiveConv:_e,openRemoteDialog:Me,closeRemoteDialog:Pe}=qm({isMobile:N,location:r,navigate:n,requestedRemoteTabTarget:l,requestedDesktopTabKey:Q,conversations:ce,ides:f,resolveConversationByTarget:bt}),$e=re||_||je,Be=!!$e&&et($e)&&!Xe($e),st=o.useMemo(()=>{if(!$e||!Be)return null;const fe=$e.daemonId||$e.routeId||"",Ae=Dt($e);return`${fe}:${Ae}`},[$e,Be]),Ft=o.useMemo(()=>Ve,[Ve]),Yt=N&&ge==="chat",rr=o.useMemo(()=>ce.filter(fe=>qe.has(fe.tabKey)),[ce,qe]),Xt=o.useCallback(fe=>{const Ae=new URLSearchParams(a);Ae.set("activeTab",fe),i(Ae,{replace:!0})},[a,i]),nr=o.useCallback(async(fe,Ae)=>Xr(e,fe,Ae),[e]),hc=o.useCallback(async(fe,Ae)=>{if(!Ae.trim())return{ok:!1,error:"Choose a workspace path first."};try{const Te=await e(fe,"workspace_add",{path:Ae.trim()});return Te!=null&&Te.success?{ok:!0}:{ok:!1,error:(Te==null?void 0:Te.error)||"Could not save workspace"}}catch(Te){return{ok:!1,error:Te instanceof Error?Te.message:"Could not save workspace"}}},[e]),xc=o.useCallback(async(fe,Ae,Te)=>{var ue;try{const Oe={ideType:Ae,enableCdp:!0};(ue=Te==null?void 0:Te.workspacePath)!=null&&ue.trim()&&(Oe.workspace=Te.workspacePath.trim());const lt=await e(fe,"launch_ide",Oe);return!(lt!=null&&lt.success)&&(lt==null?void 0:lt.success)!==void 0?{ok:!1,error:(lt==null?void 0:lt.error)||"Could not launch IDE"}:(ke({machineId:fe,kind:"ide",providerType:Ae,workspacePath:(Te==null?void 0:Te.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Oe){return{ok:!1,error:Oe instanceof Error?Oe.message:"Could not launch IDE"}}},[e]),bc=o.useCallback(async(fe,Ae,Te,ue)=>{var lt,Ps,fs;const Oe=Date.now();try{const Rt={cliType:Te};(lt=ue==null?void 0:ue.workspacePath)!=null&&lt.trim()?Rt.dir=ue.workspacePath.trim():ue!=null&&ue.workspaceId&&(Rt.workspaceId=ue.workspaceId),(Ps=ue==null?void 0:ue.resumeSessionId)!=null&&Ps.trim()&&(Rt.resumeSessionId=ue.resumeSessionId.trim()),Array.isArray(ue==null?void 0:ue.cliArgs)&&ue.cliArgs.length>0&&(Rt.cliArgs=ue.cliArgs),(fs=ue==null?void 0:ue.initialModel)!=null&&fs.trim()&&(Rt.initialModel=ue.initialModel.trim());const yt=await e(fe,"launch_cli",Rt),Ct=(yt==null?void 0:yt.result)||yt,Ds=(Ct==null?void 0:Ct.sessionId)||(Ct==null?void 0:Ct.id);return yt!=null&&yt.success&&Ds?(Xt(Ds),{ok:!0}):yt!=null&&yt.success?(ke({machineId:fe,kind:Ae,providerType:Te,workspacePath:(ue==null?void 0:ue.workspacePath)||null,resumeSessionId:(ue==null?void 0:ue.resumeSessionId)||null,startedAt:Oe}),{ok:!0}):{ok:!1,error:(yt==null?void 0:yt.error)||(Ct==null?void 0:Ct.error)||`Could not launch ${Ae.toUpperCase()} session`}}catch(Rt){return Lf(Rt)?(ke({machineId:fe,kind:Ae,providerType:Te,workspacePath:(ue==null?void 0:ue.workspacePath)||null,resumeSessionId:(ue==null?void 0:ue.resumeSessionId)||null,startedAt:Oe}),{ok:!0}):{ok:!1,error:Rt instanceof Error?Rt.message:`Could not launch ${Ae.toUpperCase()} session`}}},[Xt,e]),gc=o.useCallback(async(fe,Ae)=>{if(!fe||!Ae)return[];try{const Te=await e(fe,"list_saved_sessions",{providerType:Ae,kind:"cli",limit:30}),ue=(Te==null?void 0:Te.result)??Te;return Array.isArray(ue==null?void 0:ue.sessions)?ue.sessions:[]}catch(Te){return console.error("List saved sessions failed",Te),[]}},[e]);o.useEffect(()=>{var ue;if(!he)return;const fe=No(he.workspacePath),Ae=f.find(Oe=>{var yt,Ct,Ds,Ma;if(!Oe||Oe.type==="adhdev-daemon"||Mf(Oe.daemonId||Oe.id)!==he.machineId||(Xs(Oe)?"cli":vs(Oe)?"acp":"ide")!==he.kind||String(Oe.agentType||Oe.type||"")!==he.providerType)return!1;if(he.resumeSessionId)return String(Oe.providerSessionId||"")===he.resumeSessionId;if(fe){const en=No(Oe.workspace||Oe.runtimeWorkspaceLabel);return en?en===fe:!1}return Number(Oe.lastUpdated||Oe._lastUpdate||Oe.timestamp||((Ma=(Ds=(Ct=(yt=Oe.activeChat)==null?void 0:yt.messages)==null?void 0:Ct.at)==null?void 0:Ds.call(Ct,-1))==null?void 0:Ma.timestamp)||0)>=he.startedAt-5e3});if(!Ae)return;const Te=typeof Ae.sessionId=="string"&&Ae.sessionId?Ae.sessionId:typeof Ae.instanceId=="string"&&Ae.instanceId?Ae.instanceId:(ue=ce.find(Oe=>Oe.routeId===Ae.id))==null?void 0:ue.sessionId;Te&&(ke(null),Xt(Te))},[ce,Xt,f,he]),o.useEffect(()=>{if(!he)return;const fe=window.setTimeout(()=>{ke(Ae=>!Ae||Ae.startedAt!==he.startedAt?Ae:null)},45e3);return()=>window.clearTimeout(fe)},[he]),vm({visibleConversations:Ve,clearedTabs:le,setClearedTabs:ne,setActionLogs:F}),Pm({ides:f,sendDaemonCommand:e,setToasts:T,setLocalUserMessages:se,resolveConversationByTarget:bt});const{isRefreshingHistory:yc,handleRefreshHistory:vc}=oo({sendDaemonCommand:e,activeConv:je,chats:(Aa=f.find(fe=>fe.id===(je==null?void 0:je.routeId)))==null?void 0:Aa.chats,updateRouteChats:S,setToasts:T,setLocalUserMessages:se,setClearedTabs:ne}),{isCreatingChat:wc,isRefreshingHistory:jc,handleSwitchSession:kc,handleNewChat:Sc,handleRefreshHistory:Nc}=oo({sendDaemonCommand:e,activeConv:$e,chats:(Ta=f.find(fe=>fe.id===($e==null?void 0:$e.routeId)))==null?void 0:Ta.chats,updateRouteChats:S,setToasts:T,setLocalUserMessages:se,setClearedTabs:ne}),Zr=o.useCallback(async()=>{if(!(!$e||!Be||Ie)){te(!0);try{const fe=$e.daemonId||$e.routeId,Ae=Dt($e),Te=await e(fe,"list_saved_sessions",{agentType:Ae,providerType:Ae,kind:"cli",limit:50}),ue=(Te==null?void 0:Te.result)??Te;ie(Array.isArray(ue==null?void 0:ue.sessions)?ue.sessions:[])}catch(fe){console.error("Refresh saved sessions failed",fe),ie([])}finally{te(!1)}}},[$e,Ie,Be,e]);o.useEffect(()=>{if(!I){J.current=null;return}if(!Be){J.current=null,ie([]),te(!1);return}!st||Ie||J.current!==st&&(J.current=st,Zr())},[Zr,I,Ie,Be,st]);const Cc=o.useCallback(async fe=>{if(!$e||!Be||!fe.providerSessionId||!fe.workspace)return;const Ae=$e.daemonId||$e.routeId,Te=Dt($e);try{ae(fe.providerSessionId);const ue=await e(Ae,"launch_cli",{cliType:Te,dir:fe.workspace,resumeSessionId:fe.providerSessionId,initialModel:ti(fe.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Oe=(ue==null?void 0:ue.result)??ue,lt=typeof(Oe==null?void 0:Oe.sessionId)=="string"?Oe.sessionId:typeof(Oe==null?void 0:Oe.id)=="string"?Oe.id:"";lt&&i(Ps=>{const fs=new URLSearchParams(Ps);return fs.set("activeTab",lt),fs},{replace:!0}),B(!1)}catch(ue){console.error("Resume saved session failed",ue)}finally{ae(null)}},[$e,Be,e,i]);Gm({urlActiveTab:N&&!Yt?c:null,conversations:ce,resolveConversationBySessionId:Je,normalizedGroupAssignments:z,hasHydratedStoredLayout:N&&!Yt?U:!0,hydrateStoredLayout:N&&!Yt?G:()=>{},setGroupActiveTabIds:A,setFocusedGroup:x,setSearchParams:i,historyModalOpen:I,activeConv:je,isRefreshingHistory:yc,ides:f,handleRefreshHistory:vc});const wa=o.useCallback(async(fe,Ae)=>{const Te=Ae||X||je;if(!Te||!et(Te)&&!Xe(Te))return;const ue=Dt(Te),Oe=Te.routeId||Te.daemonId||"";try{await e(Oe,"stop_cli",{cliType:ue,targetSessionId:Te.sessionId,mode:fe})}catch(lt){console.error("Stop CLI failed:",lt)}},[je,X,e]),Ic=o.useCallback(async fe=>{const Ae=fe||je;!Ae||!et(Ae)&&!Xe(Ae)||(we(Ae),W(!0))},[je]),Ac=o.useMemo(()=>!je||!et(je)||Xe(je)?null:Is(je),[je]),Tc=o.useCallback(async fe=>{if(!je||!et(je)||Xe(je))return;const Ae=Is(je);if(Ae===fe)return;const Te=je.sessionId;Te&&Z(ue=>({...ue,[Te]:fe}));try{await e(qt(je)||je.routeId,"set_cli_view_mode",{targetSessionId:je.sessionId,cliType:Dt(je),mode:fe})}catch(ue){Te&&Z(Oe=>{const lt={...Oe};return Ae===Wi(f,Te)?delete lt[Te]:lt[Te]=Ae,lt}),_f(ue)?console.warn("Skipped CLI view mode switch:",ue instanceof Error?ue.message:String(ue)):console.error("Failed to switch CLI view mode:",ue)}},[je,f,e]),{versionMismatchDaemons:Mc,hasRequiredVersionDaemons:ja,appVersion:Lc,versionBannerDismissed:_c,setVersionBannerDismissed:Rc,upgradingDaemons:Pc,handleBannerUpgrade:Dc}=ep({ides:f,sendDaemonCommand:e}),ka=o.useCallback(fe=>{me(fe.tabKey),i(Ae=>{const Te=new URLSearchParams(Ae),ue=Md(fe);return ue?Te.set("activeTab",ue):Te.delete("activeTab"),Te},{replace:!0})},[i]),Sa=o.useCallback(fe=>{tt(fe.tabKey),ka(fe)},[ka,tt]),Ec=o.useCallback(fe=>{ht(fe.tabKey)},[ht]);return t.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[t.jsx(fu,{wsStatus:h,showReconnected:v}),t.jsx(hu,{terminalBackend:Ge,isStandalone:De,machineLabel:Qe,machineKey:Ze}),(!_c||ja)&&t.jsx(Tf,{daemons:Mc,targetVersion:Lc,required:ja,upgradingDaemons:Pc,onUpgrade:Dc,onDismiss:()=>Rc(!0)}),t.jsx(jf,{showMobileChatMode:Yt,isMobile:N,activeConv:je,chatIdes:pt,wsStatus:h,isConnected:C,onOpenHistory:fe=>{fe&&_e(fe),B(!0)},onOpenRemote:Me,onStopCli:Ic,activeCliViewMode:Ac,onSetActiveCliViewMode:Tc,mobileChatConversations:Ft,ides:f,actionLogs:oe,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:F,isStandalone:De,initialDataLoaded:w,userName:m.userName,requestedMobileTabKey:Ee,onRequestedMobileTabConsumed:ze,requestedMachineId:u,onRequestedMachineConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:p,onRequestedMobileSectionConsumed:()=>{n(r.pathname+r.search,{replace:!0,state:null})},containerRef:H,isSplitMode:ee,numGroups:V,groupSizes:O,groupedConvs:ve,clearedTabs:le,focusedGroup:g,setFocusedGroup:x,moveTabToGroup:Ce,splitTabRelative:We,closeGroup:Ne,handleResizeStart:Fe,groupActiveTabIds:$,setGroupActiveTabIds:A,groupTabOrders:M,setGroupTabOrders:L,toggleHiddenTab:mt,visibleConversations:Ve,hiddenConversations:rr,requestedDesktopTabKey:Q,onRequestedDesktopTabConsumed:ze,onDesktopActiveTabChange:me,onHideConversation:Ec,onShowHiddenConversation:Sa,onShowAllHiddenConversations:xt,scrollToBottomRequest:E,machineEntries:Ue,onBrowseMachineDirectory:nr,onSaveMachineWorkspace:hc,onLaunchMachineIde:xc,onLaunchMachineProvider:bc,onListMachineSavedSessions:gc,notifications:kt,notificationUnreadCount:Nt,notificationStateBySessionId:Mt,onMarkNotificationRead:q,onMarkNotificationUnread:Ke,onDeleteNotification:ft,onMarkNotificationTargetRead:Re}),t.jsx("style",{children:`
60
+ body { overflow: hidden; overscroll-behavior: none; }
61
+ `}),t.jsx(Af,{historyModalOpen:I,historyTargetConv:$e,ides:f,isHistoryCreatingChat:wc,isHistoryRefreshingHistory:Be?!1:jc,savedHistorySessions:Le,isSavedHistoryLoading:Ie,isResumingSavedHistorySessionId:de,onCloseHistory:()=>B(!1),onNewHistoryChat:Sc,onSwitchHistorySession:kc,onRefreshHistory:Be?Zr:Nc,onResumeSavedHistorySession:Cc,remoteDialogConv:_,remoteDialogIdeEntry:Y,connectionStates:P,actionLogs:oe,localUserMessages:xe,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:F,isStandalone:De,userName:m.userName,onOpenRemoteHistory:fe=>{fe&&_e(fe),B(!0)},onRemoteConversationChange:_e,onCloseRemoteDialog:Pe,cliStopDialogOpen:D,cliStopTargetConv:X,onCancelCliStop:()=>{W(!1),we(null)},onStopCliNow:async()=>{W(!1),await wa("hard",X),we(null)},onSaveCliAndStop:async()=>{W(!1),await wa("save",X),we(null)},toasts:y,onDismissToast:fe=>T(Ae=>Ae.filter(Te=>Te.id!==fe)),onClickToast:fe=>{if(fe.targetKey){const Ae=bt(fe.targetKey);Ae&&(x(z.get(Ae.tabKey)??0),Sa(Ae),ye({tabKey:Ae.tabKey,nonce:Date.now()}))}},showOnboarding:d,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function Pf({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[p,m]=o.useState(null),[f,w]=o.useState(!1),[S,T]=o.useState(null),[d,b]=o.useState(!1),[y,h]=o.useState(""),C=o.useRef(null),P=o.useCallback(I=>{C.current=I},[]),v=o.useCallback((I,B,D=!1)=>{c(W=>[...W.slice(-100),{timestamp:Date.now(),level:I,message:B}]),setTimeout(()=>{var W;return(W=a.current)==null?void 0:W.scrollIntoView({behavior:"smooth"})},100),D&&ot.showToast(B,I==="error"||I==="warn"?"warning":"success")},[a]),j=o.useCallback(I=>{const B=I instanceof Error?I.message:String(I||"");return B.includes("P2P command timeout")||B.includes("P2P not connected")||B.includes("P2P not available")},[]),k=o.useCallback(async(I,B)=>{var D;if(!e||l)return!1;u(I),v("info",`Launching ${at(I)}${B!=null&&B.workspace?` in ${B.workspace}`:""}...`);try{const W={ideType:I,enableCdp:!0};(D=B==null?void 0:B.workspace)!=null&&D.trim()?W.workspace=B.workspace.trim():B!=null&&B.useDefaultWorkspace&&(W.useDefaultWorkspace=!0);const X=await r(e,"launch_ide",W);return v(X!=null&&X.success?"info":"error",X!=null&&X.success?`${at(I)} launched`:`Failed: ${X==null?void 0:X.error}`,!0),!!(X!=null&&X.success)}catch(W){return v("error",`Launch error: ${W.message}`,!0),!1}finally{u(null)}},[e,l,v,r]),g=o.useCallback(async I=>{if(!e)return{success:!1};const{cliType:B,dir:D,workspaceId:W,useDefaultWorkspace:X,useHome:we,argsStr:Le,model:ie,resumeSessionId:Ie}=I;if(!B)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const te=Le?Le.split(/\s+/).filter(Boolean):void 0,de=(D==null?void 0:D.trim())||(W?"(saved id)":X?"(default workspace)":we?"(home)":"");v("info",`Launching ${B}${de?` in ${de}`:""}${ie?` (model: ${ie})`:""}...`),m(B);try{const ae={cliType:B,cliArgs:te,initialModel:ie||void 0};D!=null&&D.trim()?ae.dir=D.trim():W?ae.workspaceId=W:X?ae.useDefaultWorkspace=!0:we&&(ae.useHome=!0),Ie&&(ae.resumeSessionId=Ie);const ge=await r(e,"launch_cli",ae),oe=(ge==null?void 0:ge.result)||ge;return ge!=null&&ge.success?(v("info",`${B} launched`,!0),(oe==null?void 0:oe.launchSource)==="home"?v("info","📂 Running in home directory (explicit choice)"):(oe==null?void 0:oe.launchSource)==="defaultWorkspace"&&v("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:oe==null?void 0:oe.sessionId}):(v("error",`Failed: ${(ge==null?void 0:ge.error)||(oe==null?void 0:oe.error)}`,!0),(ge==null?void 0:ge.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&T({cliType:B,argsStr:Le,model:ie}),{success:!1,sessionId:oe==null?void 0:oe.sessionId})}catch(ae){return j(ae)?(v("warn",`${B} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(v("error",`Launch error: ${ae.message}`,!0),{success:!1})}finally{m(null)}},[e,v,j,r]),x=o.useCallback(async(I,B,D,W)=>e?I?B.trim()?g({cliType:I,dir:B,argsStr:D,model:W}):(T({cliType:I,argsStr:D,model:W}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,g]),$=o.useCallback(async(I,B,D)=>{if(e&&window.confirm(`Stop ${I}?
62
+ This will terminate the process.`))try{const W=await r(e,"stop_cli",{cliType:I,dir:B,targetSessionId:D});W!=null&&W.success?v("info",`${I} stopped`,!0):v("error",`Stop failed: ${(W==null?void 0:W.error)||"Unknown error"}`,!0)}catch(W){v("error",`Stop failed: ${W.message}`,!0)}},[e,v,r]),A=o.useCallback(async I=>{try{await r(I.daemonId,"restart_ide",{ideType:I.type}),v("info",`${at(I.type)} restart initiated`,!0)}catch(B){v("error",`Restart failed: ${B.message}`,!0)}},[v,r]),M=o.useCallback(async I=>{if(window.confirm(`Stop ${at(I.type)}?
63
+ This will disconnect CDP and optionally kill the process.`))try{const B=await r(I.daemonId,"stop_ide",{ideType:I.type,killProcess:!0});B!=null&&B.success?v("info",`${at(I.type)} stopped`,!0):v("error",`Stop failed: ${(B==null?void 0:B.error)||"Unknown error"}`,!0)}catch(B){v("error",`Stop failed: ${B.message}`,!0)}},[v,r]),L=o.useCallback(async()=>{if(e)try{const I=await r(e,"detect_ides",{});v("info",`Found ${((I==null?void 0:I.result)||[]).length} IDE(s)`,!0)}catch(I){v("error",`Detection failed: ${I.message}`,!0)}},[e,v,r]),O=o.useCallback(async I=>{if(!e||!I.trim())return!1;w(!0);try{const B=await r(e,"workspace_add",{path:I.trim()});return B!=null&&B.success?(v("info",`Workspace added: ${I.trim()}`),!0):(v("error",(B==null?void 0:B.error)||"workspace_add failed"),!1)}catch(B){return v("error",B.message),!1}finally{w(!1)}},[e,v,r]),R=o.useCallback(async I=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){w(!0);try{const B=await r(e,"workspace_remove",{id:I});B!=null&&B.success?v("info","Workspace removed",!0):v("error",(B==null?void 0:B.error)||"workspace_remove failed",!0)}catch(B){v("error",B.message,!0)}finally{w(!1)}}},[e,v,r]),N=o.useCallback(async I=>{var B;if(e){w(!0);try{const D=await r(e,"workspace_set_default",I===null?{clear:!0}:{id:I});if(D!=null&&D.success){v("info",I?"Default workspace updated":"Default workspace cleared",!0);const W=typeof D.defaultWorkspacePath=="string"?D.defaultWorkspacePath:"";W&&((B=C.current)==null||B.call(C,W))}else v("error",(D==null?void 0:D.error)||"workspace_set_default failed",!0)}catch(D){v("error",D.message,!0)}finally{w(!1)}}},[e,v,r]),U=o.useCallback(async I=>{var D;if(!e||!I.trim())return;const B=I.trim();w(!0);try{const W=await r(e,"workspace_set_default",{path:B});W!=null&&W.success?(v("info","Default workspace set from history"),(D=C.current)==null||D.call(C,B)):v("error",(W==null?void 0:W.error)||"Could not set default (path missing on disk?)")}catch(W){v("error",W.message)}finally{w(!1)}},[e,v,r]),G=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(I){v("warn",`Live nickname updated, but account sync failed: ${I.message}`)}v("info",`Nickname set to "${y||"(cleared)"}"`),b(!1)}catch(I){v("error",`Failed: ${I.message}`)}},[e,y,s,v,n,r]);return{logs:i,launchingIde:l,launchingAgentType:p,workspaceBusy:f,launchPick:S,setLaunchPick:T,editingNickname:d,setEditingNickname:b,nicknameInput:y,setNicknameInput:h,addLog:v,handleLaunchIde:k,runLaunchCliCore:g,handleLaunchCli:x,handleStopCli:$,handleRestartIde:A,handleStopIde:M,handleDetectIdes:L,handleWorkspaceAdd:O,handleWorkspaceRemove:R,handleWorkspaceSetDefault:N,handleWorkspaceResumePath:U,handleSaveNickname:G,setOnDefaultWorkspaceChanged:P}}function Df({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var A;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:m}=i,[f,w]=o.useState(!1),[S,T]=o.useState(""),[d,b]=o.useState([]),[y,h]=o.useState(!1),[C,P]=o.useState(""),v=o.useCallback(async M=>{h(!0),P("");try{const L=await Xr(c,e,M);T(L.path),b(L.directories)}catch(L){P(L instanceof Error?L.message:"Could not load folder")}finally{h(!1)}},[e,c]),j=o.useCallback(()=>{w(!0);const M=[...r.map(O=>O.workspace),...n.map(O=>O.workspace),...a.map(O=>O.workspace)],L=Yr(s.platform,qr(M,s.defaultWorkspacePath,(s.workspaces||[]).map(O=>O.path)));v(L)},[a,n,r,v,s.defaultWorkspacePath,s.platform,s.workspaces]),k=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,g=s.availableMem??s.freeMem??s.totalMem,x=k&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-g)/s.totalMem*100))):0,$=((A=s.loadavg)==null?void 0:A[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(cr,{icon:t.jsx(zo,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?zl(s.uptime):"Waiting…"}),t.jsx(cr,{icon:t.jsx(At,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(cr,{icon:t.jsx(Hr,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(cr,{icon:t.jsx(ml,{size:16}),label:"ACPs",value:`${a.length}`})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),t.jsxs("div",{className:"flex gap-6",children:[t.jsx(Ba,{value:k?Math.min(Math.round($/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:k?`${$.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(Ba,{value:x,max:100,label:"Memory",color:"#3b82f6",detail:k?`${nn(s.totalMem-g)} / ${nn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${nn(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(Ss,{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:j,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:Vr(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(Qr,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:S,directories:d,busy:y,error:C,confirmLabel:"Add workspace",onClose:()=>w(!1),onNavigate:M=>{v(M)},onConfirm:M=>{(async()=>{if(!M)return;await u(M)&&w(!1)})()}})]})}function Ef(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 $f(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 kn(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 Co(e){if(!e||typeof e!="object")return null;if(kn(e))return e;const s=e,r=s.result;return kn(r)?r:kn(s.sourceConfig)?s.sourceConfig:null}function Bf(e){const s=e.trim();return s||null}const Io=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Kf=[{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 Wf({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,p]=o.useState([]),[m,f]=o.useState(""),[w,S]=o.useState([]),[T,d]=o.useState(""),b=o.useRef(null),y=o.useRef(null),h=g=>{p(x=>x.includes(g)?x.filter($=>$!==g):[...x,g])},C=()=>p([...Io]),P=()=>p([]);o.useEffect(()=>{var g;(g=b.current)==null||g.scrollIntoView({behavior:"smooth"})},[w]),o.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const v=o.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const g=await r(e,"provider_auto_fix_status",{providerType:s.type});(g==null?void 0:g.running)===!1&&a==="running"&&(i("done"),S(x=>[...x,`
64
+ ✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,s.type,r,a]),j=async()=>{if(u.length!==0){i("running"),S(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,m?`💬 Comment: ${m}`:"",""]),d("");try{const g=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...m?{comment:m}:{}});g!=null&&g.success&&(g!=null&&g.started||g!=null&&g.running)?(S(x=>[...x,"✅ Agent started. Monitoring progress..."]),v()):(i("error"),d((g==null?void 0:g.error)||"Failed to start auto-fix"))}catch(g){i("error"),d((g==null?void 0:g.message)||"Connection failed")}}},k=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),S(g=>[...g,`
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:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:Kf.map(g=>t.jsxs("button",{onClick:()=>l(g.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===g.value?g.color+"66":"var(--border-subtle)",background:c===g.value?g.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===g.value?g.color:"var(--text-primary)"},children:g.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:g.desc})]},g.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:C,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:P,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Io.map(g=>t.jsxs("button",{onClick:()=>h(g),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(g)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(g)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(g)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(g)?"☑ ":"☐ ",g]},g))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:m,onChange:g=>f(g.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[w.map((g,x)=>t.jsx("div",{className:g.startsWith("✅")?"text-green-400":"",style:g.startsWith("❌")||g.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:g},x)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:b})]}),T&&t.jsx("div",{className:"mt-2 px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:T})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.jsxs("div",{className:"text-[10px] text-text-muted",children:[a==="config"&&u.length>0&&`${u.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[a==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:j,disabled:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&t.jsx("button",{onClick:k,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),S([]),d("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Of({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var v;const i=s.filter(j=>j.category==="ide"),[c,l]=o.useState(((v=i[0])==null?void 0:v.type)||""),[u,p]=o.useState(""),[m,f]=o.useState(""),[w,S]=o.useState(!1),[T,d]=o.useState(""),[b,y]=o.useState(!1),h=j=>{const k=j.toLowerCase().replace(/[^a-z0-9-]/g,"");p(k),(!m||m===C(u))&&f(C(k))},C=j=>j.split("-").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(" "),P=async()=>{if(!(!u||!m||!c)){S(!0),d("");try{const j=await r(e,"provider_clone",{type:u,name:m,category:"ide",location:"user",cloneFrom:c});j!=null&&j.success||j!=null&&j.created?(y(!0),a==null||a(u)):d((j==null?void 0:j.error)||"Failed to create provider")}catch(j){d((j==null?void 0:j.message)||"Connection failed")}S(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:j=>j.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(j=>t.jsxs("button",{onClick:()=>l(j.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===j.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===j.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:j.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===j.type?"#a78bfa":"var(--text-secondary)"},children:j.displayName})]},j.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:j=>h(j.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:j=>f(j.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),T&&t.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:T})]})}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:b?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:P,disabled:!u||!m||w,className:"machine-btn",style:{background:u&&m?"rgba(34,197,94,0.12)":void 0,borderColor:u&&m?"rgba(34,197,94,0.3)":void 0,color:u&&m?"#86efac":void 0,opacity:!u||!m||w?.4:1},children:w?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Hf({machineId:e,providers:s,sendDaemonCommand:r}){var A;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[p,m]=o.useState("all"),[f,w]=o.useState(null),[S,T]=o.useState(!1),[d,b]=o.useState(null),[y,h]=o.useState("normal"),[C,P]=o.useState(""),[v,j]=o.useState(!1),k=o.useCallback(async()=>{if(e)try{const M=await r(e,"get_provider_source_config",{}),L=Co(M);L&&(b(L),h(L.sourceMode),P(L.explicitProviderDir||""))}catch{}},[e,r]),g=o.useCallback(async()=>{if(e){c(!0);try{const M=await r(e,"get_provider_settings",{}),L=Ef(M);if(L){const O=$f(L,s);O.sort((R,N)=>R.category.localeCompare(N.category)||R.displayName.localeCompare(N.displayName)),a(O)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&g(),d||k()},[]);const x=async(M,L,O)=>{u(`${M}.${L}`),a(R=>R.map(N=>N.type===M?{...N,values:{...N.values,[L]:O}}:N));try{const R=await r(e,"set_provider_setting",{providerType:M,key:L,value:O});R!=null&&R.success||g()}catch{g()}u(null)},$=async()=>{j(!0);try{const M=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Bf(C)}),L=Co(M);L?(b(L),h(L.sourceMode),P(L.explicitProviderDir||"")):await k(),await g()}catch{await k()}j(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(M=>t.jsx("button",{onClick:()=>m(M),className:`machine-btn text-[10px] px-2 py-0.5 ${p===M?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:M.toUpperCase()},M))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>T(!0),className:"machine-btn text-[10px] bg-green-500/[0.06] border-green-500/20 text-green-400 hover:bg-green-500/[0.12]",children:"✨ Create Provider"}),t.jsx("button",{onClick:g,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick:k,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value: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:C,onChange:M=>P(M.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void $(),disabled:v,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:v?"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:"})," ",((A=d==null?void 0:d.providerRoots)==null?void 0:A.join(" → "))||"loading…"]})]})]}),p!=="all"&&n.filter(M=>M.category===p).length>1&&(()=>{const M=n.filter(N=>N.category===p),L=new Map;for(const N of M)for(const U of N.schema){if(U.type!=="boolean")continue;const G=L.get(U.key),I=!!(N.values[U.key]??U.default);G?(G.onCount+=I?1:0,G.total+=1):L.set(U.key,{label:U.label||U.key,onCount:I?1:0,total:1})}const O=[...L.entries()].filter(([,N])=>N.total===M.length);if(O.length===0)return null;const R=async(N,U)=>{for(const G of M)await x(G.type,N,U)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",p.toUpperCase()," providers (",M.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:O.map(([N,U])=>{const G=U.onCount===U.total,I=U.onCount===0;return t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:"text-text-secondary font-medium",children:U.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",U.onCount,"/",U.total,")"]}),t.jsx("button",{onClick:()=>void R(N,!0),disabled:G,className:`machine-btn text-[9px] px-1.5 py-px ${G?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void R(N,!1),disabled:I,className:`machine-btn text-[9px] px-1.5 py-px ${I?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},N)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(M=>p==="all"||M.category===p).map(M=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:M.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:M.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:M.category==="acp"?"rgba(139,92,246,0.08)":M.category==="cli"?"rgba(59,130,246,0.08)":M.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:M.category==="acp"?"#a78bfa":M.category==="cli"?"#60a5fa":M.category==="ide"?"#86efac":"var(--status-warning)"},children:M.category}),M.category==="ide"&&t.jsx("button",{onClick:()=>w(s.find(L=>L.type===M.type)||{type:M.type,name:M.displayName,displayName:M.displayName,icon:M.icon,category:M.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),t.jsx("div",{className:"flex flex-col gap-2",children:M.schema.map(L=>t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[L.label||L.key,l===`${M.type}.${L.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),L.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:L.description})]}),t.jsx("div",{className:"shrink-0",children:L.type==="boolean"?t.jsx("button",{onClick:()=>x(M.type,L.key,!(M.values[L.key]??L.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:M.values[L.key]??L.default?"#8b5cf6":"var(--border-subtle)"},children:t.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:M.values[L.key]??L.default?21:3}})}):L.type==="number"?t.jsx("input",{type:"number",value:Number(M.values[L.key]??L.default??0)||0,min:L.min,max:L.max,onChange:O=>{const R=parseInt(O.target.value)||0;L.min!==void 0&&R<L.min||L.max!==void 0&&R>L.max||x(M.type,L.key,R)},className:"machine-input w-20 text-center text-[11px]"}):L.type==="select"&&L.options?t.jsx("select",{value:String(M.values[L.key]??L.default??""),onChange:O=>x(M.type,L.key,O.target.value),className:"machine-input text-[11px]",children:L.options.map(O=>t.jsx("option",{value:O,children:O},O))}):t.jsx("input",{type:"text",value:String(M.values[L.key]??L.default??""),onBlur:O=>x(M.type,L.key,O.target.value),className:"machine-input w-[120px] text-[11px]"})})]},L.key))})]},M.type))}),f&&t.jsx(Wf,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>w(null)}),S&&t.jsx(Of,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>T(!1),onCreated:()=>{T(!1),g()}})]})}const Uf=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Ff({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function zf(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Ao(e){if(!e||Object.keys(e).length===0)return"";try{const s=JSON.stringify(e);return s.length>220?`${s.slice(0,220)}…`:s}catch{return"[unserializable payload]"}}function Vf({machineId:e,sendDaemonCommand:s}){const[r,n]=o.useState([]),[a,i]=o.useState([]),[c,l]=o.useState([]),[u,p]=o.useState(0),[m,f]=o.useState(0),[w,S]=o.useState(!0),[T,d]=o.useState("debug"),[b,y]=o.useState("all"),h=o.useRef(null),C=o.useRef(!1),P=zf(a,b);return o.useEffect(()=>{if(!e||!w)return;const v=async()=>{try{const[k,g]=await Promise.all([s(e,"get_logs",{count:200,minLevel:T,since:u}),s(e,"get_debug_trace",Ff({count:120,since:m,category:b}))]),x=(k==null?void 0:k.result)||k;if(k!=null&&k.success&&Array.isArray(x==null?void 0:x.logs)&&x.logs.length>0){n(M=>[...M,...x.logs.map(O=>({timestamp:O.ts,level:O.level,message:`[${O.category}] ${O.message}`}))].slice(-300));const A=Math.max(...x.logs.map(M=>M.ts));p(A)}const $=(g==null?void 0:g.result)||g;if(g!=null&&g.success&&Array.isArray($==null?void 0:$.trace)){i($.trace.slice(-120));const A=$.trace.reduce((M,L)=>Math.max(M,Number(L.ts||0)),m);A>m&&f(A)}}catch{}l(ks.list({limit:120}))};v();const j=setInterval(v,3e3);return()=>clearInterval(j)},[e,w,u,m,T,b,s]),o.useEffect(()=>{if(w&&(r.length>0||a.length>0||c.length>0)){const v=C.current?"smooth":"instant";setTimeout(()=>{var j;(j=h.current)==null||j.scrollIntoView({behavior:v}),C.current=!0},50)}},[r.length,a.length,c.length,w]),o.useEffect(()=>{i([]),f(0)},[b]),t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-3",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Level"}),["debug","info","warn","error"].map(v=>t.jsx("button",{onClick:()=>{d(v),n([]),p(0)},className:`machine-btn text-[10px] px-2 py-0.5 ${T===v?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:v.toUpperCase()},v))]}),t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsxs("span",{className:"text-[10px] text-text-muted",children:["logs=",r.length," trace=",P.length," web=",c.length]}),t.jsx("button",{onClick:()=>S(!w),className:`machine-btn ${w?"text-green-500 border-green-500/30":""}`,children:w?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>{n([]),i([]),l([]),p(0),f(0),ks.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),r.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs..."}),r.map((v,j)=>t.jsxs("div",{className:"flex gap-2 py-px",style:{color:v.level==="error"?"#ef4444":v.level==="warn"?"var(--status-warning)":v.level==="debug"?"#64748b":"#94a3b8"},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",{children:v.message})]},`log-${j}`))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[180px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsxs("div",{className:"mb-2 flex flex-wrap items-center justify-between gap-2",children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",b==="session_host"?" · session_host only":""]}),t.jsx("div",{className:"flex gap-1 items-center",children:Uf.map(v=>t.jsx("button",{onClick:()=>y(v.value),className:`machine-btn text-[10px] px-2 py-0.5 ${b===v.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:v.label},v.value))})]}),P.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:b==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),P.map(v=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(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",{children:Ao(v.payload)})]},v.id))]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl p-3 min-h-[160px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[t.jsx("div",{className:"mb-2 text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),c.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No browser debug events captured yet."}),c.map(v=>t.jsxs("div",{className:"py-1 border-b border-white/5 last:border-b-0",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted",children:[t.jsx("span",{children:new Date(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",{children:Ao(v.payload)})]},v.id))]})]}),t.jsx("div",{ref:h})]})}function Sn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Nn(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function To(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 Gf(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function qf(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 Yf(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 Xf({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),p=$i(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),m=p.diagnostics,f=p.loading,w=p.applyDiagnostics,S=o.useMemo(()=>mf({diagnostics:m,loading:f,refreshing:l,error:n}),[m,f,l,n]),T=o.useMemo(()=>new Map(s.map(A=>[A.sessionId||A.id,A])),[s]),d=o.useCallback(async()=>{if(e){u(!0);try{const A=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),M=Sn(A);if(!(M!=null&&M.success))throw new Error((M==null?void 0:M.error)||"Could not load hosted runtime diagnostics");w(M.diagnostics||M.result||null),a("")}catch(A){const M=A instanceof Error?A.message:"Could not load hosted runtime diagnostics";a(M)}finally{u(!1)}}},[w,e,r]);o.useEffect(()=>{!e||m||f||l||d()},[m,f,e,d,l]);const b=o.useCallback(async(A,M)=>{const L=`${A}:${M.sessionId}`;if(!(A==="session_host_stop_session"&&!window.confirm(`Stop ${M.displayName}?
66
+ This will terminate the hosted runtime.`))){c(L);try{const O=await r(e,A,{sessionId:M.sessionId}),R=Sn(O);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Session host action failed");const N=A==="session_host_resume_session"?"resumed":A==="session_host_restart_session"?"restarted":"stopped";ot.showToast(`Session host ${N}: ${M.displayName}`,"success"),await d()}catch(O){const R=O instanceof Error?O.message:"Session host action failed";ot.showToast(R,"warning"),a(R)}finally{c(O=>O===L?null:O)}}},[e,d,r]),y=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
67
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const M=await r(e,"session_host_prune_duplicate_sessions",{}),L=Sn(M);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Duplicate prune failed");const O=L.result||{},R=Array.isArray(O.prunedSessionIds)?O.prunedSessionIds.length:0,N=typeof O.duplicateGroupCount=="number"?O.duplicateGroupCount:0;ot.showToast(`Pruned ${R} duplicate runtime(s) across ${N} group(s)`,"success"),await d()}catch(M){const L=M instanceof Error?M.message:"Duplicate prune failed";ot.showToast(L,"warning"),a(L)}finally{c(M=>M==="session_host_prune_duplicate_sessions"?null:M)}}},[e,d,r]),h=o.useMemo(()=>[...(m==null?void 0:m.sessions)||[]].sort((A,M)=>(M.lastActivityAt||0)-(A.lastActivityAt||0)),[m==null?void 0:m.sessions]),C=o.useMemo(()=>m!=null&&m.liveRuntimes||m!=null&&m.recoverySnapshots||m!=null&&m.inactiveRecords?{liveRuntimes:(m==null?void 0:m.liveRuntimes)||[],recoverySnapshots:(m==null?void 0:m.recoverySnapshots)||[],inactiveRecords:(m==null?void 0:m.inactiveRecords)||[]}:mc(h),[m==null?void 0:m.inactiveRecords,m==null?void 0:m.liveRuntimes,m==null?void 0:m.recoverySnapshots,h]),P=C.liveRuntimes,v=C.recoverySnapshots,j=C.inactiveRecords,k=o.useMemo(()=>Yf(P),[P]),g=o.useMemo(()=>[...(m==null?void 0:m.recentTransitions)||[]].slice(-6).reverse(),[m==null?void 0:m.recentTransitions]),x=o.useMemo(()=>[...(m==null?void 0:m.recentLogs)||[]].reverse().find(A=>A.level==="warn"||A.level==="error")||null,[m==null?void 0:m.recentLogs]),$=(A,M)=>{var D;const L=i===`session_host_resume_session:${A.sessionId}`,O=i===`session_host_restart_session:${A.sessionId}`,R=i===`session_host_stop_session:${A.sessionId}`,N=va(A.meta),U=T.get(A.sessionId),G=A.attachedClients.length===1?"1 client":`${A.attachedClients.length} clients`,I=M==="recovery"?"Recover":"Resume",B=pc(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:A.displayName||(U==null?void 0:U.cliName)||A.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${qf(A.lifecycle)}`,children:A.lifecycle}),N&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:N})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:A.workspaceLabel||(U==null?void 0:U.runtimeWorkspaceLabel)||A.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:A.runtimeKey}),A.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",A.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((D=A.writeOwner)==null?void 0:D.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Gf(A.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(Yn,{size:11})," ",G]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",To(A.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",B]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[M==="recovery"&&(A.lifecycle==="interrupted"||A.lifecycle==="failed"||A.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_resume_session",A)},children:L?`${I}ing…`:I}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{b("session_host_restart_session",A)},children:O?"Restarting…":"Restart"}),M==="live"&&(A.lifecycle==="running"||A.lifecycle==="starting"||A.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",A)},children:R?"Stopping…":"Stop"})]})]})},A.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(Ot,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:ju()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[k>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 (${k})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${S.toneClass}`,children:S.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{d()},disabled:f||l,children:[t.jsx(_s,{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(ls,{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:v.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:To(m.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Nn(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(ls,{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:[Nn(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(Hr,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:js("live")}),P.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:P.map(A=>$(A,"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(Ot,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:js("recovery")}),v.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:v.map(A=>$(A,"recovery"))})]}),j.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:js("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:j.map(A=>$(A,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),g.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:g.map(A=>{var L;const M=h.find(O=>O.sessionId===A.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(M==null?void 0:M.displayName)||((L=T.get(A.sessionId))==null?void 0:L.cliName)||A.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[A.action,A.lifecycle?` · ${A.lifecycle}`:"",A.detail?` · ${A.detail}`:"",A.error?` · ${A.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${A.success===!1?"text-red-300":"text-text-secondary"}`,children:Nn(A.timestamp)})]},`${A.sessionId}:${A.timestamp}:${A.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 Qf({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 Cn({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 In({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 Jf({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),m=zs(e,"0.8.70");return t.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[l.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Cn,{icon:t.jsx(Ht,{size:13}),children:"Current Chats"}),t.jsx(In,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const w=Wn(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:it(f)}),w>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Fr(w)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ms(f)})]},f.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Cn,{icon:t.jsx(zo,{size:13}),children:"Recent Launches"}),t.jsx(In,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const{metaText:w,updatedLabel:S}=Qi(f);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>i(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),S&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:S})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:w})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Cn,{icon:t.jsx(ls,{size:13}),children:"Daemon Update"}),t.jsx(In,{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(_s,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function Zf(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function eh(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const th={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 wr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function sh(e){const s=e instanceof Error?e.message:String(e||"");return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("CLI session not found")||s.includes("CLI_SESSION_NOT_FOUND")}function An({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:p}){const m=Ls(),{handleLaunchIde:f,handleStopCli:w,handleRestartIde:S,handleStopIde:T,handleDetectIdes:d,launchingIde:b,launchingAgentType:y,addLog:h}=c,[C,P]=o.useState(null),v=o.useCallback(_=>{_&&m(Zf(_))},[m]),j=th[e],k=e==="ide",g=e==="acp",x=o.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),$=o.useMemo(()=>new Map(x.map(_=>[_.type,_.displayName||_.type])),[x]),[A,M]=o.useState(""),[L,O]=o.useState(""),[R,N]=o.useState([]),[U,G]=o.useState(""),[I,B]=o.useState(""),[D,W]=o.useState([]),[X,we]=o.useState(!1),[Le,ie]=o.useState(""),[Ie,te]=o.useState(!1),[de,ae]=o.useState(()=>gt()),[ge,oe]=o.useState(null),[F,xe]=o.useState(p?"__custom__":u||s.defaultWorkspaceId||""),[se,pe]=o.useState(p||""),[Z,le]=o.useState([]),[ne,be]=o.useState(!1),[me,E]=o.useState(""),[ye,he]=o.useState([]),[ke,J]=o.useState(!1),[Se,Ue]=o.useState(""),De=o.useRef(null),[Ge,Qe]=o.useState(null),Ze=o.useRef("__home__"),[ut,qe]=o.useState("__home__"),[ht,mt]=o.useState(!1),tt=o.useRef(0),xt=Z.filter(_=>!a.some(Y=>Y.type===_&&wt(Y.status)!=="stopped")),pt=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!F&&xe(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){xe("__custom__"),pe(p);return}u&&(xe(u),pe(""))},[u,p]),o.useEffect(()=>{k||A&&(x.some(_=>_.type===A)||(M(""),B("")))},[x,k,A]);const ce=(()=>{if(F==="__custom__")return se.trim();if(!F)return"";const _=(s.workspaces||[]).find(Y=>Y.id===F);return(_==null?void 0:_.path)||""})(),Ve=o.useCallback(_=>{const Y=pt.current[_];Y&&(clearTimeout(Y),delete pt.current[_]),le(re=>re.includes(_)?re.filter(_e=>_e!==_):re)},[]),ct=o.useRef(new Set),Je=o.useCallback(async _=>{if(l){J(!0),Ue("");try{const Y=await Xr(l,r,_);E(Y.path),pe(Y.path),he(Y.directories)}catch(Y){Ue(Y instanceof Error?Y.message:"Could not load folder")}finally{J(!1)}}},[r,l]),bt=o.useCallback(()=>{if(!l)return;xe("__custom__"),be(!0);const _=a.map(re=>re.workspace),Y=Yr(s.platform,qr(se.trim(),ce,p,_,s.defaultWorkspacePath,(s.workspaces||[]).map(re=>re.path)));Je(Y)},[se,p,Je,s.defaultWorkspacePath,s.platform,s.workspaces,a,ce,l]),jt=o.useCallback(_=>{const Y=String(_.workspace||"").trim();if(!Y)return;const re=(s.workspaces||[]).find(_e=>wr(_e.path)===wr(Y));if(re){xe(re.id),pe("");return}xe("__custom__"),pe(Y)},[s.workspaces]),kt=o.useCallback(_=>{const Y=String(_.workspace||"").trim();if(!Y)return{workspaceId:null,workspacePath:"",useHome:!0};const re=(s.workspaces||[]).find(_e=>wr(_e.path)===wr(Y));return re?{workspaceId:re.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Y,useHome:!1}},[s.workspaces]),Nt=o.useCallback(async _=>{if(!l||!_||e!=="cli"){W([]),we(!1),ie("");return}const Y=tt.current+1;tt.current=Y,we(!0),ie("");try{const re=await l(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(tt.current!==Y)return;const _e=(re==null?void 0:re.result)??re;W(Array.isArray(_e==null?void 0:_e.sessions)?_e.sessions:[])}catch(re){if(tt.current!==Y)return;W([]),ie(re instanceof Error?re.message:"Could not load saved sessions")}finally{tt.current===Y&&we(!1)}},[e,r,l]),Mt=o.useMemo(()=>{if(e!=="cli"||!A)return null;const _=$.get(A)||A;return{routeId:r,daemonId:r,providerSessionId:I||void 0,transport:"pty",mode:"chat",agentName:_,agentType:A,status:"idle",title:_,messages:[],ideType:A,workspaceName:ce,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${A}`}},[e,r,$,ce,I,A]),q=o.useCallback(_=>{if(e==="ide"||!_){N([]);return}N(dc(r,_))},[e,r]);o.useEffect(()=>{if(B(""),q(A),e!=="cli"||!A){W([]),ie(""),we(!1);return}Nt(A)},[e,q,Nt,A]);const Ke=o.useMemo(()=>D.find(_=>_.providerSessionId===I)||null,[D,I]);o.useEffect(()=>{if(!I)return;const _=D.find(Y=>Y.providerSessionId===I);_!=null&&_.canResume||B("")},[D,I]);const Re=o.useCallback((_,Y)=>{De.current=Y,Ze.current=_.selectedWorkspaceKey||"__home__",qe(_.selectedWorkspaceKey||"__home__"),Qe(_)},[]),ft=o.useCallback(()=>{De.current&&(mt(!0),De.current().finally(()=>{De.current=null,mt(!1),Qe(null)}))},[]),K=o.useCallback(_=>{if(!_)return;le(re=>re.includes(_)?re:[...re,_]);const Y=pt.current[_];Y&&clearTimeout(Y),pt.current[_]=setTimeout(()=>{le(re=>re.includes(_)?re.filter(_e=>_e!==_):re),delete pt.current[_]},2e4)},[]);o.useEffect(()=>{for(const Y of a)wt(Y.status)!=="stopped"&&(Z.includes(Y.type)&&!ct.current.has(Y.type)&&(ct.current.add(Y.type),h("info",`${$.get(Y.type)||Y.type} launched`,!0)),Ve(Y.type));const _=new Set(a.filter(Y=>wt(Y.status)!=="stopped").map(Y=>Y.type));ct.current.forEach(Y=>{!Z.includes(Y)&&!_.has(Y)&&ct.current.delete(Y)})},[h,Ve,a,Z,$]),o.useEffect(()=>()=>{Object.values(pt.current).forEach(clearTimeout),pt.current={}},[]);const[H,z]=o.useState({}),[V,ee]=o.useState(null);o.useEffect(()=>{if(!k||!r||!l)return;(async()=>{try{const Y=await l(r,"get_ide_extensions",{}),re=(Y==null?void 0:Y.result)||Y;re!=null&&re.success&&(re!=null&&re.ideExtensions)&&z(re.ideExtensions)}catch{}})()},[k,r,l]);const ve=_=>k?at(_.type):e==="cli"?_.cliName:_.acpName,Ce=k?s.detectedIdes||[]:[],Ne=o.useCallback(async _=>{const Y=(_==null?void 0:_.type)||A,re=(_==null?void 0:_.workspacePath)??ce;if(k){await f(Y,re?{workspace:re}:void 0)&&K(Y);return}const _e=await c.runLaunchCliCore({cliType:Y,dir:_!=null&&_.workspaceId?void 0:re||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!re,argsStr:(_==null?void 0:_.argsStr)??(L||void 0),model:(_==null?void 0:_.model)??(g&&U||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!g&&e==="cli"&&Y===A&&I||void 0});if(_e.success||_e.pending){const Me=(_==null?void 0:_.argsStr)??L;!k&&(Me!=null&&Me.trim())&&(uc(r,Y,Me),q(Y)),K(Y),_e.success&&_e.sessionId&&v(_e.sessionId)}},[c,f,g,k,L,U,q,K,r,v,ce,I,A]),Fe=vi(k?"ide":g?"acp":"cli",!k&&!g&&!!I),We=wi(k?"ide":g?"acp":"cli",!k&&!g&&!!I),je=()=>{var Me;const _=k?at(A):$.get(A)||A,Y=!k&&!g&&!!I,{options:re,selectedKey:_e}=is({machine:s,currentWorkspaceId:F&&F!=="__custom__"?F:null,currentWorkspacePath:ce});Re({title:Y?ca(_):ss("start-fresh",_),description:Y?la():rs("start-fresh"),confirmLabel:Fe,busyLabel:We,workspaceOptions:re,selectedWorkspaceKey:_e,details:[{label:"Mode",value:j.label},{label:"Provider",value:_},...!k&&e==="cli"&&I?[{label:"Resume",value:((Me=D.find(Pe=>Pe.providerSessionId===I))==null?void 0:Me.title)||I}]:[],...!k&&L.trim()?[{label:"Arguments",value:L.trim()}]:[],...g&&U.trim()?[{label:"Model",value:U.trim()}]:[]]},async()=>{const Pe=re.find($e=>$e.key===Ze.current);Pe!=null&&Pe.workspaceId?(xe(Pe.workspaceId),pe("")):Pe!=null&&Pe.workspacePath?(xe("__custom__"),pe(Pe.workspacePath)):(xe(""),pe("")),await Ne({workspaceId:(Pe==null?void 0:Pe.workspaceId)??null,workspacePath:(Pe==null?void 0:Pe.workspacePath)??"",useHome:!(Pe!=null&&Pe.workspaceId)&&!(Pe!=null&&Pe.workspacePath)})})},Q=_=>{k?T(_):w(_.type,_.workspace,_.id)},Ee=o.useCallback(async(_,Y,re=!1)=>{if(_.mode===Y){re&&_.sessionId&&v(_.sessionId);return}if(!l||!_.sessionId){re&&_.sessionId&&v(_.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:Y}),re&&v(_.sessionId)}catch(_e){sh(_e)?console.warn("Skipped CLI view mode switch:",_e instanceof Error?_e.message:String(_e)):console.error("Failed to switch CLI view mode:",_e)}},[r,v,l]),ze=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:F,onChange:_=>{const Y=_.target.value;if(xe(Y),Y==="__custom__"&&l){bt();return}Y!=="__custom__"&&pe("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(_=>t.jsxs("option",{value:_.id,children:[_.id===s.defaultWorkspaceId?"⭐ ":"",Vr(_.path,_.label)]},_.id)),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),F==="__custom__"&&(l?t.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:bt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:se,onChange:_=>pe(_.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:F==="__custom__"?ce?t.jsx("span",{className:"font-mono truncate block",title:ce,children:ce}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":ce?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:F===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:ce,children:ce})]}):"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 ${j.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 ",j.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?Ce.length>0?Ce.map(_=>{const Y=a.find($e=>($e.type||"").toLowerCase()===(_.type||"").toLowerCase()&&wt($e.status)!=="stopped"),re=_.running||!!Y,_e=!!Y&&Y.cdpConnected,Me=Z.includes(_.type||_.id||""),Pe=A===(_.type||"");return t.jsxs("button",{onClick:()=>{if(_e&&Y){const $e=Y.sessionId;$e?m(`/dashboard?activeTab=${encodeURIComponent($e)}`,{state:{openRemoteForTabKey:$e}}):m("/dashboard",{state:{openRemoteForTabKey:Y.id}});return}Me||M($e=>$e===(_.type||"")?"":_.type||"")},disabled:!!b||Me,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${_e?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Pe?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:b&&b!==_.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(_.type)}),re&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${_e?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.name||at(_.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${_e?"text-green-400":Me?"text-orange-400":Pe?"text-accent-primary":"text-text-muted"}`,children:_e?"Open Session":Me?"Starting...":Pe?"Configure":"Select"})]})]},_.type)}):t.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",t.jsxs("button",{onClick:d,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[t.jsx(il,{size:14})," Scan System"]})]}):x.length>0?x.map(_=>{const Y=A===_.type,re=Z.includes(_.type),Me=!!a.find(Pe=>Pe.type===_.type&&wt(Pe.status)!=="stopped");return t.jsxs("button",{onClick:()=>M(Pe=>Pe===_.type?"":_.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Y?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:_.icon}),Me&&t.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${re?"text-orange-400":Y?"text-accent-primary":"text-text-muted"}`,children:re?"Starting...":Y?"Configure":"Select"})]})]},_.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),A&&(k?Ce.find(_=>_.type===A):x.find(_=>_.type===A))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:k?at(A):$.get(A)||A})]}),ze,!k&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!g&&e==="cli"&&t.jsx(fc,{busy:!!y||!!b||Z.includes(A),savedSessionsLoading:X,savedSessionsError:Le,selectedSession:Ke,onRefresh:()=>void Nt(A),onOpenHistory:()=>{A&&(te(!0),Nt(A))},onClearSelection:()=>B("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[g&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:U,onChange:_=>G(_.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:L,onChange:_=>O(_.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),R.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:R.map(_=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>O(_),title:_,children:_},_))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:je,disabled:!!y||!!b||Z.includes(A),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===A||b===A?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+Z.filter(_=>!a.some(Y=>Y.type===_&&wt(Y.status)!=="stopped")).length,")"]}),a.length===0&&xt.length===0?t.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",j.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[xt.map(_=>t.jsx("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary",style:{border:"1px solid color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(_)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?at(_):$.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 Y=k?_:null,re=!k&&!g?_:null,_e=wt(_.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:i(_.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[ve(_),(Y==null?void 0:Y.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Y.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:_.workspace||"—"}),(re==null?void 0:re.mode)&&t.jsx("span",{className:re.mode==="chat"?"text-violet-400":"text-text-secondary",children:re.mode==="chat"?"Chat view":"Terminal view"})]}),re&&(re.runtimeKey||re.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[re.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",re.runtimeKey]}),t.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Me;(Me=navigator.clipboard)==null||Me.writeText(`adhdev attach ${re.runtimeKey}`),P(re.runtimeKey||null),window.setTimeout(()=>{P(Pe=>Pe===re.runtimeKey?null:Pe)},1200)},children:C===re.runtimeKey?"Copied":"Copy"})]}),re.runtimeWriteOwner&&t.jsx("span",{style:{color:re.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:re.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:eh(re.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${_e==="stopped"?"bg-red-500/[0.08] text-red-500":_e==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:_e}),k&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Me=_.sessionId;if(Me){m(`/dashboard?activeTab=${encodeURIComponent(Me)}`,{state:{openRemoteForTabKey:Me}});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(At,{size:13})}),t.jsx("button",{onClick:()=>{const Me=_.workspace||"",{options:Pe,selectedKey:$e}=is({machine:s,currentWorkspacePath:Me});Re({title:ss("restart-ide",at(_.type)),description:rs("restart-ide"),confirmLabel:Ts("restart-ide"),busyLabel:Ms("restart-ide"),workspaceOptions:Pe,selectedWorkspaceKey:$e,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:at(_.type)}]},async()=>{const Be=Pe.find(Ft=>Ft.key===Ze.current),st=(Be==null?void 0:Be.workspacePath)??"";if(st&&st!==Me){await Ne({type:_.type,workspacePath:st});return}await S(_)})},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(_s,{size:14})})]}),g&&t.jsx("button",{onClick:()=>{const Me=_.sessionId;Me&&v(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!_.sessionId,children:t.jsx(Ht,{size:14})}),re&&_e!=="stopped"&&t.jsxs(t.Fragment,{children:[re.mode&&t.jsx(aa,{mode:re.mode,onChange:Me=>void Ee(re,Me,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Me=_.sessionId;Me&&v(Me)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!_.sessionId,children:re.mode==="chat"?t.jsx(Ht,{size:14}):t.jsx(At,{size:13})})]}),_e==="stopped"?t.jsx("button",{onClick:()=>{const Me=_.workspace||"",Pe=k?at(_.type):ve(_),{options:$e,selectedKey:Be}=is({machine:s,currentWorkspacePath:Me});Re({title:ss("restart-stopped",Pe),description:rs("restart-stopped"),confirmLabel:Ts("restart-stopped"),busyLabel:Ms("restart-stopped"),workspaceOptions:$e,selectedWorkspaceKey:Be,details:[{label:"Mode",value:j.label},{label:"Provider",value:Pe}]},async()=>{const st=$e.find(Ft=>Ft.key===Ze.current);await Ne({type:_.type,workspaceId:(st==null?void 0:st.workspaceId)??null,workspacePath:(st==null?void 0:st.workspacePath)??"",useHome:!(st!=null&&st.workspaceId)&&!(st!=null&&st.workspacePath)})})},disabled:Z.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:Z.includes(_.type)?"⏳":t.jsx(Qn,{size:14})}):t.jsx("button",{onClick:()=>Q(_),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(St,{size:14})})]})]}),Y&&Y.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Y.aiAgents.map(Me=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Jo(Me.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Me.name," · ",wt(Me.status)]},Me.id))}),Y&&(H[Y.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(H[Y.type]||[]).map(Me=>t.jsxs("button",{disabled:V===`${Y.type}.${Me.type}`,onClick:async()=>{const Pe=`${Y.type}.${Me.type}`;ee(Pe);try{await l(r,"set_ide_extension",{ideType:Y.type,extensionType:Me.type,enabled:!Me.enabled}),z($e=>({...$e,[Y.type]:($e[Y.type]||[]).map(Be=>Be.type===Me.type?{...Be,enabled:!Be.enabled}:Be)}))}catch($e){console.error("Extension toggle failed:",$e)}finally{ee(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Me.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Me.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Me.name,t.jsx("span",{className:"text-[9px] font-normal",children:Me.enabled?"ON":"OFF"})]},Me.type))})]})]},_.id)})]}),ne&&l&&t.jsx(Qr,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:me,directories:ye,busy:ke,error:Se,confirmLabel:"Use this folder",onClose:()=>be(!1),onNavigate:_=>{Je(_)},onConfirm:_=>{pe(_),xe("__custom__"),be(!1)}}),Ge&&t.jsx(ga,{title:Ge.title,description:Ge.description,details:Ge.details,workspaceOptions:Ge.workspaceOptions,selectedWorkspaceKey:ut,onWorkspaceChange:_=>{Ze.current=_,qe(_)},confirmLabel:Ge.confirmLabel,busyLabel:Ge.busyLabel,busy:ht,onConfirm:ft,onCancel:()=>{De.current=null,Qe(null)}}),Ie&&Mt&&t.jsx(da,{activeConv:Mt,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:D,isSavedSessionsLoading:X,isResumingSavedSessionId:ge,savedHistoryFilters:de,onSavedHistoryFiltersChange:ae,onClose:()=>te(!1),onNewChat:()=>{B(""),te(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Nt(A)},onResumeSavedSession:_=>{if(!_.canResume||ge)return;const Y=kt(_);B(_.providerSessionId),jt(_),oe(_.providerSessionId),te(!1),Ne({type:_.providerType,workspaceId:Y.workspaceId,workspacePath:Y.workspacePath,useHome:Y.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{oe(re=>re===_.providerSessionId?null:re)})}})]})}const Mo=[{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 rh({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:p,initialWorkspacePath:m,sendDaemonCommand:f}){var d;const[w,S]=o.useState(u);o.useEffect(()=>{S(u)},[u]);const T=o.useMemo(()=>({ide:n.length,cli:a.length,acp:i.length}),[n.length,a.length,i.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Mo.map(b=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${w===b.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>S(b.id),children:[t.jsx("span",{children:b.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${w===b.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:T[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=Mo.find(b=>b.id===w))==null?void 0:d.helper})]}),w==="ide"&&t.jsx(An,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),w==="cli"&&t.jsx(An,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m}),w==="acp"&&t.jsx(An,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:m})]})}function nh({onNicknameSynced:e}={}){var F,xe,se,pe,Z,le,ne,be,me;const{id:s}=Uc(),r=Ls(),n=Gn(),{sendCommand:a}=Tt(),i=tr(),c=pi(),l=c.ides||[],u=c.initialLoaded??!0,p=l.find(E=>E.id===s&&E.type==="adhdev-daemon"),m=l.some(E=>E.type==="adhdev-daemon"),[f,w]=o.useState("workspace"),[S,T]=o.useState("ide"),d=o.useRef(null),[b,y]=o.useState(null),h=o.useRef("__home__"),[C,P]=o.useState("__home__"),[v,j]=o.useState(!1),k=o.useRef(null);o.useEffect(()=>{!s||!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,p,s]),pm(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:15e3});const g=()=>{if(m){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=Pf({machineId:s,registeredMachineId:(p==null?void 0:p.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:k});o.useEffect(()=>ot.onToast(ye=>{c.setToasts(ke=>{if(ke.some(Ue=>Ue.message===ye.message&&ye.timestamp-Ue.timestamp<3e3))return ke;const Se={id:ye.id,message:ye.message,type:ye.type,timestamp:ye.timestamp,targetKey:ye.targetKey,actions:ye.actions};return[...ke.slice(-4),Se]});const he=ye.duration||5e3;setTimeout(()=>c.setToasts(ke=>ke.filter(J=>J.id!==ye.id)),he)}),[c]);const $=(p==null?void 0:p.availableProviders)||[],A={};for(const E of $)A[E.type]=E.icon;const M=E=>A[E]||"",L=p?{id:p.id,hostname:Zo(p,{fallbackId:p.id}),platform:((F=p.machine)==null?void 0:F.platform)||"unknown",arch:((xe=p.machine)==null?void 0:xe.arch)||"",cpus:((se=p.machine)==null?void 0:se.cpus)||0,totalMem:((pe=p.machine)==null?void 0:pe.totalMem)||0,freeMem:(Z=p.machine)==null?void 0:Z.freeMem,availableMem:(le=p.machine)==null?void 0:le.availableMem,loadavg:(ne=p.machine)==null?void 0:ne.loadavg,uptime:(be=p.machine)==null?void 0:be.uptime,release:((me=p.machine)==null?void 0:me.release)||"",cdpConnected:!!p.cdpConnected,machineNickname:p.machineNickname||null,p2p:p.p2p?{screenshotActive:!1,...p.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:p.detectedIdes||[],workspaces:p.workspaces||[],defaultWorkspaceId:p.defaultWorkspaceId??p.activeWorkspaceId??null,defaultWorkspacePath:p.defaultWorkspacePath??p.activeWorkspacePath??null}:null,O=l.filter(E=>E.daemonId===s&&E.type!=="adhdev-daemon").filter(E=>!Xs(E)&&!vs(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,version:E.version||"",instanceId:E.instanceId||"",status:E.status,workspace:E.workspace||null,terminals:E.terminals||0,aiAgents:Jl(E.aiAgents||(E.agents||[]).map(ye=>({id:ye.name,name:ye.name,status:ye.status,version:ye.version}))),activeChat:E.activeChat||null,chats:E.chats||[],childSessions:E.childSessions||[],cdpConnected:E.cdpConnected||!1,daemonId:s})),R=l.filter(E=>E.daemonId===s&&Xs(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,cliName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,mode:E.mode,runtimeKey:E.runtimeKey,runtimeDisplayName:E.runtimeDisplayName,runtimeWorkspaceLabel:E.runtimeWorkspaceLabel,runtimeWriteOwner:E.runtimeWriteOwner||null,runtimeAttachedClients:E.runtimeAttachedClients||[],daemonId:s})),N=l.filter(E=>E.daemonId===s&&vs(E)).map(E=>({id:E.id,sessionId:E.sessionId,type:E.type,acpName:E.cliName||E.type,status:E.status,workspace:E.workspace||"",activeChat:E.activeChat||null,providerSessionId:E.providerSessionId,daemonId:s})),U=p?It(p,{fallbackId:s}):"",G="workspace",I=n.state,B=I==null?void 0:I.initialMachineTab,D=I==null?void 0:I.initialWorkspaceCategory,W=I==null?void 0:I.initialWorkspaceId,X=I==null?void 0:I.initialWorkspacePath,we=B==="ides"||B==="clis"||B==="acps"?"workspace":B||G,Le=B==="ides"?"ide":B==="clis"?"cli":B==="acps"?"acp":D,ie=[...O.map(E=>{var ye,he,ke,J,Se;return{id:`ide:${E.type}:${E.workspace||""}`,label:((ye=E.activeChat)==null?void 0:ye.title)||E.type,kind:"ide",providerType:E.type,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Se=(J=(ke=(he=E.activeChat)==null?void 0:he.messages)==null?void 0:ke.at)==null?void 0:J.call(ke,-1))==null?void 0:Se.timestamp)||0}}),...R.map(E=>{var ye,he,ke,J,Se;return{id:`cli:${E.type}:${E.workspace||""}`,label:((ye=E.activeChat)==null?void 0:ye.title)||E.cliName,kind:"cli",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Se=(J=(ke=(he=E.activeChat)==null?void 0:he.messages)==null?void 0:ke.at)==null?void 0:J.call(ke,-1))==null?void 0:Se.timestamp)||0}}),...N.map(E=>{var ye,he,ke,J,Se;return{id:`acp:${E.type}:${E.workspace||""}`,label:((ye=E.activeChat)==null?void 0:ye.title)||E.acpName,kind:"acp",providerType:E.type,providerSessionId:E.providerSessionId,subtitle:ds(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace||void 0,lastLaunchedAt:((Se=(J=(ke=(he=E.activeChat)==null?void 0:he.messages)==null?void 0:ke.at)==null?void 0:J.call(ke,-1))==null?void 0:Se.timestamp)||0}})].sort((E,ye)=>(ye.lastLaunchedAt||0)-(E.lastLaunchedAt||0)),Ie=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map(E=>({id:E.id,label:E.title||E.providerName||E.providerType,kind:E.kind,providerType:E.providerType,providerSessionId:E.providerSessionId,subtitle:ds(E.summaryMetadata)||E.workspace||void 0,workspace:E.workspace,summaryMetadata:E.summaryMetadata,lastLaunchedAt:E.lastLaunchedAt})):ie,te=o.useMemo(()=>{var ye;const E=((ye=c.connectionStates)==null?void 0:ye[s||""])||void 0;return l.filter(he=>he.daemonId===s&&he.type!=="adhdev-daemon").flatMap(he=>ua(he,{},{connectionStates:s&&E?{[s]:E}:void 0,defaultConnectionState:E})).filter(he=>!(he.transport==="pty"&&he.mode==="terminal")).sort((he,ke)=>Wn(ke)-Wn(he))},[l,c.connectionStates,s]),de=o.useCallback(E=>{const ye=E.sessionId||E.tabKey;ye&&r(`/dashboard?activeTab=${encodeURIComponent(ye)}`)},[r]),ae=o.useCallback(()=>{d.current&&(j(!0),d.current().finally(()=>{d.current=null,j(!1),y(null)}))},[]),ge=o.useCallback(E=>{if(!L)return;const{options:ye,selectedKey:he}=is({machine:L,currentWorkspacePath:E.workspace}),ke=async()=>{T(E.kind),w("workspace")};d.current=async()=>{const J=ye.find(De=>De.key===h.current),Se=(J==null?void 0:J.workspacePath)??null,Ue=(J==null?void 0:J.workspaceId)??null;if(E.kind==="ide"&&E.providerType){await x.handleLaunchIde(E.providerType,Se?{workspace:Se}:void 0);return}if((E.kind==="cli"||E.kind==="acp")&&E.providerType){await x.runLaunchCliCore({cliType:E.providerType,dir:Ue?void 0:Se||"",workspaceId:Ue||void 0,model:E.kind==="acp"&&ti(E.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:E.providerSessionId});return}await ke()},h.current=he,P(he),y({title:E.kind==="ide"?ss("restart-ide",E.label):E.providerSessionId?ca(E.label):ss("start-fresh",E.label),description:E.kind==="ide"?rs("restart-ide"):E.providerSessionId?la():rs("start-fresh"),confirmLabel:E.kind==="ide"?Ts("restart-ide"):E.providerSessionId?Dr(!0):Ts("start-fresh"),busyLabel:E.kind==="ide"?Ms("restart-ide"):E.providerSessionId?oa(!0):Ms("start-fresh"),workspaceOptions:ye,details:[{label:"Mode",value:E.kind.toUpperCase()},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]})},[x,L]);if(o.useEffect(()=>{w(we)},[G,we,s]),o.useEffect(()=>{Le&&T(Le)},[Le,s]),!L)return u?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:g,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const oe=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(At,{size:14})," Workspace"]}),count:O.length+R.length+N.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ot,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Or,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(cl,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(al,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:g,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[x.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:x.nicknameInput,onChange:E=>x.setNicknameInput(E.target.value),onKeyDown:E=>{E.key==="Enter"&&x.handleSaveNickname(),E.key==="Escape"&&x.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),t.jsx("button",{onClick:x.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),t.jsx("button",{onClick:()=>x.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):t.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{x.setEditingNickname(!0),x.setNicknameInput(L.machineNickname||"")},title:"Click to set nickname",children:U}),t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),t.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[L.platform," · ",L.arch]}),t.jsxs("span",{children:[L.cpus," cores"]}),(p==null?void 0:p.version)&&t.jsxs("span",{children:["v",p.version]}),L.p2p.available&&t.jsxs("span",{children:["P2P ",L.p2p.state==="connected"?"connected":L.p2p.state]}),L.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:L.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:oe.map(E=>t.jsxs("button",{onClick:()=>w(E.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===E.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[E.label,E.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===E.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:E.count})]},E.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[f==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Jf,{machineEntry:p,providers:$,recentLaunches:Ie,currentConversations:te,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:ge,onOpenConversation:de}),t.jsx(rh,{machine:L,machineId:s,providers:$,ideSessions:O,cliSessions:R,acpSessions:N,actions:x,getIcon:M,initialCategory:S,initialWorkspaceId:W,initialWorkspacePath:X,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(Hf,{machineId:s,providers:$,sendDaemonCommand:a}),f==="overview"&&t.jsx(Df,{machineId:s,machine:L,ideSessions:O,cliSessions:R,acpSessions:N,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(Xf,{machineId:s,cliSessions:R,sendDaemonCommand:a}),f==="logs"&&t.jsx(Vf,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&L&&t.jsx(Qf,{machine:L,launchPick:x.launchPick,actions:x}),b&&t.jsx(ga,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:E=>{h.current=E,P(E)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:v,onConfirm:ae,onCancel:()=>{d.current=null,y(null)}}),t.jsx(ji,{toasts:c.toasts||[],onDismiss:E=>c.setToasts(ye=>ye.filter(he=>he.id!==E)),onClickToast:E=>{E.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent(E.targetKey)}`)}}),t.jsx("style",{children:`
68
+ @keyframes toast-in {
69
+ from { opacity: 0; transform: translateX(40px); }
70
+ to { opacity: 1; transform: translateX(0); }
71
+ }
72
+ `})]})}class ah{constructor(){Ye(this,"adapters",new Map);Ye(this,"states",new Map);Ye(this,"runtimeListeners",new Map);Ye(this,"screenshotCallbacks",new Map);Ye(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}sendPtyResize(s,r,n,a){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const a=this.runtimeListeners.get(s);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return;const n=await fetch(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const a=await n.json();this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof a.seq=="number"?a.seq:0,text:typeof a.text=="string"?a.text:"",truncated:!!a.truncated,cols:typeof a.cols=="number"?a.cols:void 0,rows:typeof a.rows=="number"?a.rows:void 0})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Kt=new ah;function oh(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=new URLSearchParams(window.location.search).get("token");return n?`${s}?token=${encodeURIComponent(n)}`:s}const jr=oh(),Lo=3e3,ih=3e4;let $t=null,ch=0;const Wr=new Map;let Zt=null,Gs=null;function _o(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Os(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function lh(e){return e==="connected"?"connected":e}async function Tr(e,s,r){const n=Pu(e,r||{}),a=$t;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++ch}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{Wr.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Wr.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 Fn(e,s){const r=$t;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class dh{constructor(s){Ye(this,"daemonId");Ye(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return($t==null?void 0:$t.readyState)===WebSocket.OPEN}get connectionState(){return($t==null?void 0:$t.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return Tr(this.daemonId,s,r)}async sendInput(s,r){return Tr(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,Zt&&(clearInterval(Zt),Zt=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await Tr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(i=>i.blob());Kt.emitScreenshot(this.daemonId,a)}}catch{}};r(),Zt=setInterval(r,2e3)}stopScreenshots(s){Zt&&(clearInterval(Zt),Zt=null)}}let _t=null;function uh(e){return(!_t||_t.daemonId!==e)&&(_t=new dh(e)),_t}function mh({children:e}){const s=o.useRef(Lr()),r=Lr();s.current=r;const{setUserName:n}=cs(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((d,b)=>{l(d),Gs==null||Gs(d,b)},[]),p=o.useRef(null),m=o.useRef(),f=o.useRef(Lo),w=o.useRef(!0),S=o.useRef(!1),T=o.useRef("initial_connect");return o.useEffect(()=>{w.current=!0,S.current=!1;function d(){var h,C;if(!w.current||((h=p.current)==null?void 0:h.readyState)===WebSocket.OPEN||((C=p.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${jr}...`),Os("connect_attempt",{url:jr,reason:T.current,delayMs:f.current});let y;try{y=new WebSocket(jr)}catch(P){console.error("[Standalone WS] Failed to create WebSocket:",P),b();return}p.current=y,y.onopen=()=>{if(!w.current){y.close();return}u("connected"),f.current=Lo,Os("open",{url:jr,reason:T.current}),Gt.resubscribeAll({sendData:Fn}),console.log("[Standalone WS] Connected")},$t=y,y.onmessage=P=>{var v,j;try{const k=JSON.parse(P.data);if((k.type==="command_result"||k.type==="error")&&k.requestId){const g=Wr.get(k.requestId);g&&(Wr.delete(k.requestId),k.type==="error"?g.reject(new Error(((v=k.data)==null?void 0:v.message)||"Command failed")):g.resolve(k.data));return}if(k.type==="session_output"){const g=k.sessionId||k.cliId||k.cliType;g&&Kt.emitSessionOutput(g,typeof k.data=="string"?k.data:"",typeof k.seq=="number"?k.seq:void 0);return}if(k.type==="runtime_snapshot"){Kt.emitRuntimeSnapshot(k.sessionId,typeof k.text=="string"?k.text:"",typeof k.seq=="number"?k.seq:0,!!k.truncated);return}if(k.type==="topic_update"){const g=k.update;g&&Gt.publish(g);return}if(k.type==="status"||k.type==="initial_state"){const g=k.data;if(!g)return;const{injectEntries:x,markLoaded:$,getIdes:A}=s.current,M=g.instanceId||"standalone",L=A().find(N=>N.id===M),O=uh(M);Kt.register(M,O),Kt.setState(M,"connected"),u("connected",M),Kt.emitStatus(M,g);const R=Pr(g,{daemonId:M,existingDaemon:L,existingEntries:A()});_o("ws_status",{type:k.type,daemonId:M,sessions:(g.sessions||[]).map(N=>({id:N.id,parentId:N.parentId,providerType:N.providerType,kind:N.kind,transport:N.transport,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,title:N.title})),recentLaunches:(g.recentLaunches||[]).map(N=>({id:N.id,providerType:N.providerType,kind:N.kind,workspace:N.workspace,lastLaunchedAt:N.lastLaunchedAt}))}),_o("entries",{daemonId:M,entries:R.filter(N=>N.type!=="adhdev-daemon").map(N=>({id:N.id,type:N.type,unread:N.unread,inboxBucket:N.inboxBucket,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,sessionId:N.sessionId}))}),R.length>0&&x(R,{authoritativeDaemonIds:[M]}),$(),c.current!==M&&((j=i.current)==null||j.call(i),c.current=M,i.current=Gt.subscribe({sendData:Fn},M,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${M}`,params:{includeSessions:!0}},N=>{if(N.topic!=="daemon.metadata")return;const U=s.current.getIdes(),G=U.find(B=>B.id===M),I=Pr(N.status,{daemonId:M,existingDaemon:G,existingEntries:U,timestamp:N.timestamp});I.length>0&&s.current.injectEntries(I),N.userName&&a.current&&a.current(N.userName)}))}}catch(k){console.error("[Standalone WS] Parse error:",k)}},y.onclose=P=>{w.current&&(_t==null||_t.stopScreenshots(),_t&&Kt.setState(_t.daemonId,"disconnected"),u("disconnected"),p.current=null,T.current=`close:${P.code}${P.wasClean?":clean":":unclean"}`,Os("close",{code:P.code,reason:P.reason||"",wasClean:P.wasClean}),b())},y.onerror=P=>{S.current||!w.current||(T.current="error",Os("error",{message:P instanceof Event?"event":String(P),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",P))}}function b(){if(!w.current)return;clearTimeout(m.current);const y=f.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),Os("schedule_reconnect",{reason:T.current,delayMs:y}),m.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,ih),d()},y)}return d(),()=>{var y;w.current=!1,S.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,$t=null),_t&&(_t.stopScreenshots(),Kt.unregister(_t.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function ph({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(Gs=(c,l)=>{r(c),l&&a(l)},()=>{Gs=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=lh(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(Qc,{connectionOverrides:i,children:t.jsx(mh,{children:e})})}const fh=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Wo,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Ot,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Or,{}),label:"Settings"}];function hh({children:e}){const s=Ls(),r=Gn(),[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(St,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:fh.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(Oo,{})}),!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(Ho,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.70"]}),t.jsx(Gu,{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 xh=[{icon:t.jsx(Ot,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Ht,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Uo,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(At,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Ys,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Oo,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],bh=[{icon:t.jsx(ul,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Wo,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Ur,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(nl,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(Yn,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(ol,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],gh=[{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 yh(){return t.jsxs(Ai,{icon:t.jsx(Ho,{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.70"]}),children:[t.jsx(Pt,{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(Pt,{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:xh.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(Pt,{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:Ni.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Ii.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Ci.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(Pt,{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:bh.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(Pt,{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:gh.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(Ti,{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(wl,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function vh(){const{ides:e}=cs(),s=e.find(f=>f.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Tt(),{userName:a}=cs(),[i,c]=o.useState(a||"");o.useEffect(()=>{a!==void 0&&c(a)},[a]);const l=f=>{const w=f.target.value.trim();s!=null&&s.id&&w!==a&&n(s.id,"set_user_name",{userName:w}).catch(console.error)},[u,p]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),m=f=>{p(f);try{localStorage.setItem("adhdev_sound",f?"1":"0")}catch{}};return t.jsxs(Ai,{icon:t.jsx(Or,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Ou,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost."}),t.jsx(Pt,{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.70"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"WebSocket"}),t.jsx("span",{className:"font-mono text-xs",children:"ws://localhost:19222"}),t.jsx("span",{className:"text-text-muted",children:"HTTP"}),t.jsx("span",{className:"font-mono text-xs",children:"http://localhost:19280"})]})}),t.jsx(Pt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(f=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${f.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:f.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:f.type})]},f.type))})}),t.jsx(Pt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Qu,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Pt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode and theme.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(tm,{})]}),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(lm,{})]}),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(um,{})]})]})}),t.jsx(Pt,{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(qu,{}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(vl,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:u,onChange:m})]})}),t.jsx(Pt,{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(rl,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:i,onChange:f=>c(f.target.value),onBlur:l,onKeyDown:f=>{f.key==="Enter"&&f.currentTarget.blur()}})]})})})]})}Vu();im();const wh=Bo({baseUrl:""});function Ro(){const{ides:e,initialLoaded:s}=cs();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(Ln,{to:`/machines/${r.id}`,replace:!0}):t.jsx(Ln,{to:"/dashboard",replace:!0})}function jh(){const e=o.useMemo(()=>({sendCommand:Tr,sendData:Fn}),[]);return t.jsx(Fc,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(el,{client:wh,children:t.jsx(ph,{children:t.jsx(sl,{value:e,children:t.jsx(hh,{children:t.jsxs(zc,{children:[t.jsx(Qt,{path:"/dashboard",element:t.jsx(Rf,{})}),t.jsx(Qt,{path:"/machine",element:t.jsx(Ro,{})}),t.jsx(Qt,{path:"/machines/:id",element:t.jsx(nh,{})}),t.jsx(Qt,{path:"/machines",element:t.jsx(Ro,{})}),t.jsx(Qt,{path:"/about",element:t.jsx(yh,{})}),t.jsx(Qt,{path:"/settings",element:t.jsx(vh,{})}),t.jsx(Qt,{path:"*",element:t.jsx(Ln,{to:"/dashboard",replace:!0})})]})})})})})})}cu({connectionManager:Kt});Vc(document.getElementById("root")).render(t.jsx(jh,{}));