@adhdev/daemon-standalone 0.8.71 → 0.8.73
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +322 -188
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
- package/public/assets/index-DQz255j-.js +72 -0
- package/public/index.html +1 -1
- package/public/assets/index-DN14XOgk.js +0 -72
|
@@ -1,72 +0,0 @@
|
|
|
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 Kc=Object.defineProperty;var Wc=(e,s,r)=>s in e?Kc(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Ye=(e,s,r)=>Wc(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as Vn,a as Gn,b as Do,c as Eo,u as _s,R as nt,d as Ys,t as Oc,e as Hc,D as Uc,f as Tn,g as Ln,h as qn,i as Fc,k as zc,B as Vc,l as Gc,m as Qt,N as _n,n as qc}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 Yc(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 Ss=Yc();function _a(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 $o=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}),Bo=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ra(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 Pa(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 sn(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,m=s.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),m&&(n.versionUpdateReason=m),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 Lr(e){return Array.isArray(e)?e.map(Lr):!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,Lr(r)]))}function Xc(e,s){try{return JSON.stringify(Lr(e))===JSON.stringify(Lr(s))}catch{return!1}}function ar(e,s,r){return Xc(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function Qc(e,s,r){var m,p,u,f,w,S,M;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=Ra(d),h=Ra(b);if(y>h){const C=(m=d.chats)!=null&&m.length?d.chats:b.chats,P=Pa(b.childSessions,d.childSessions),v=sn(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&&!((u=b.chats)!=null&&u.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=sn(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=Pa(b.childSessions,d.childSessions),k=sn(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||((M=d.id)==null?void 0:M.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 Jc(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 Zc({children:e,connectionOverrides:s}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[m,p]=o.useState(void 0),u=o.useRef(r);o.useEffect(()=>{u.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:Qc(y,C,h),v=!Jc(C,P);return v&&Ss.record({kind:"dashboard.entries_applied",payload:{incoming:_a(y),next:_a(P)}}),v?P:C})},[]),S=o.useCallback(()=>i(!0),[]),M=o.useMemo(()=>({injectEntries:w,markLoaded:S,getIdes:()=>u.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:m,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,m]);return t.jsx(Bo.Provider,{value:M,children:t.jsx($o.Provider,{value:b,children:e})})}function ls(){return o.useContext($o)}function _r(){return o.useContext(Bo)}function Ko(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 m=r==null?void 0:r(),p=a(l),u=l.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return m&&u.searchParams.set("token",m),!l.startsWith("http")&&!s?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function c(l,m={}){const p={"Content-Type":"application/json",...m.headers||{}},u=r==null?void 0:r();u&&(p.Authorization=`Bearer ${u}`);const f=a(l),w=new AbortController,S=setTimeout(()=>w.abort(),15e3);try{const M=await fetch(f,{...m,headers:p,signal:w.signal});if(M.status===401)throw n==null||n(),new Error("Unauthorized");if(!M.ok){const d=await M.json().catch(()=>({error:M.statusText}));throw new Error(d.error||`API Error: ${M.status}`)}return M.json()}finally{clearTimeout(S)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,m,p={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:m,payload:p})}),execTerminal:(l,m,p)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:m,name:p})}),sendAgentMessage:(l,m,p)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:m,message:p})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,m,p)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:m,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,m,p={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:m,payload:p})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const el=Ko({baseUrl:"http://localhost:3847"}),tl=o.createContext(el);function sl({client:e,children:s}){return t.jsx(tl.Provider,{value:e,children:s})}const rl={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Wo=o.createContext(rl);function nl({value:e,children:s}){return t.jsx(Wo.Provider,{value:e,children:s})}function Mt(){return o.useContext(Wo)}const He={size:18};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("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 Yn({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 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:"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 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:"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 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:"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 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("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 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("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 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("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 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("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 cl({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 Qn({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 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("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ns({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 Rs({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 ds({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 Xs({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 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:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),t.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function zo({size:e=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 Vo({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 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:"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 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("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}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("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Jn({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 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("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 pl({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 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:"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 hl({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 xl({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 Fr({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"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 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("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 gl({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 yl({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 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("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 wl({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 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("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 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("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 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:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}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("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}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:"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 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("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 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("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 Da(e){return!!e&&typeof e=="object"&&"text"in e}function Zn(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:Da(i)?String(i.text||""):"").join(r):Da(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Cs(e){return Zn(e,{normalizeWhitespace:!0})}const rn=new Map;function Ea(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function Go(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Ml(e,s,r){return Number(e.receivedAt||r[vs(e,s)]||0)||0}function qo(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function Tl(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 nn(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 $a(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):qo(e)?t.jsx(Vn,{remarkPlugins:[Gn,Do,Eo],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:$a(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=nn(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=nn(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=nn(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}),$a(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 vs(e,s){const r=e,n=Zn(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 Ll=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(Vn,{remarkPlugins:[Gn],children:s.text}),t.jsx("span",{className:"action-time",children:Go(s.timestamp)})]})},(e,s)=>e.log===s.log),_l=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var j,k,g;const m=(s.role||"").toLowerCase(),p=m==="user"||m==="human",u=s.kind||(m==="tool"?"tool":"standard"),f=Tl(s.content)?s.content:null,w=!!(f!=null&&f.some(x=>x.type!=="text")),S=Zn(s.content,{joiner:`
|
|
4
|
-
`});if(u==="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(hl,{size:13}),t.jsx("span",{children:x})]}),t.jsx("div",{className:"chat-msg-body",children:S})]})}if(u==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),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(u==="terminal"){const x=(k=s.meta)!=null&&k.isRunning?"⏳":"✅",B=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:B})]}),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(u==="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 M=s.meta,b=(typeof(M==null?void 0:M.renderMode)=="string"?M.renderMode.trim():"")==="preformatted",y=S,h=!1,C=y,P=b,v=!P&&qo(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:Go(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(Vn,{remarkPlugins:[Gn,Do,Eo],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),Rl=o.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:m={},emptyState:p,onLoadMore:u,isLoadingMore:f,hasMoreHistory:w,hiddenLiveCount:S=0,loadError:M,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),B=o.useRef(!1),[A,T]=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(()=>{var oe;const te=y.current,de=(oe=window.getSelection)==null?void 0:oe.call(window);if(!te||!de||de.rangeCount===0||de.isCollapsed){B.current=!1;return}const ae=de.anchorNode,xe=de.focusNode;B.current=!!(ae&&xe&&te.contains(ae)&&te.contains(xe))},[]),G=s.length>0?`${s.length}:${(((Ie=s[s.length-1])==null?void 0:Ie.content)||"").length}`:"0:0",I=o.useCallback(()=>{const te=y.current;!te||!l||rn.set(l,{top:te.scrollTop,fromBottom:Math.max(0,te.scrollHeight-te.scrollTop-te.clientHeight),messageFingerprint:G})},[l,G]),D=o.useCallback((te="auto")=>{k.current!=null&&cancelAnimationFrame(k.current),k.current=requestAnimationFrame(()=>{k.current=null,N(te)})},[N]);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,!B.current){const xe=l?rn.get(l):null;xe&&Ea(xe,G)?requestAnimationFrame(()=>{const oe=y.current;if(!oe)return;const F=Math.max(0,oe.scrollHeight-oe.clientHeight-xe.fromBottom);oe.scrollTop=Number.isFinite(F)?F:xe.top,O.current=!0}):D("auto")}P.current=s.length;return}s.length>P.current?!L.current&&!B.current&&D("auto"):R()&&!L.current&&!B.current&&D("auto"),P.current=s.length},[G,l,c,s.length,D]),o.useEffect(()=>{d&&(L.current=!1,g.current=!0,O.current=!0,x.current!=null&&window.clearTimeout(x.current),x.current=window.setTimeout(()=>{g.current=!1,x.current=null},180),B.current||D("auto"))},[D,d]),o.useEffect(()=>()=>{I(),k.current!=null&&cancelAnimationFrame(k.current),x.current!=null&&window.clearTimeout(x.current)},[I]),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&&(B.current||(D("auto"),de()))});return ae.observe(te),()=>{ae.disconnect(),x.current!=null&&(window.clearTimeout(x.current),x.current=null)}},[D,l]),o.useImperativeHandle(b,()=>({scrollToBottom:(te="smooth")=>{N(te)}}),[N]),o.useEffect(()=>{const te=y.current;if(!te)return;let de;const ae=()=>{clearTimeout(de),de=setTimeout(()=>{L.current=!R(),I()},50)};return te.addEventListener("scroll",ae,{passive:!0}),()=>{te.removeEventListener("scroll",ae),clearTimeout(de)}},[I]),o.useEffect(()=>(document.addEventListener("selectionchange",U),()=>document.removeEventListener("selectionchange",U)),[U]);const E=o.useRef(0),W=o.useRef(!1);o.useEffect(()=>{const te=y.current;if(!te||!W.current||E.current===0)return;const de=te.scrollHeight-E.current;de>0&&(te.scrollTop=de),I(),E.current=0,W.current=!1},[s.length,I]),o.useEffect(()=>{if(O.current||!l)return;const te=rn.get(l),de=y.current;if(!te||!de)return;if(!Ea(te,G)){N("auto"),O.current=!0;return}const ae=Math.max(0,de.scrollHeight-de.clientHeight-te.fromBottom);de.scrollTop=Number.isFinite(ae)?ae:te.top,O.current=!0},[l,G,s.length,N]);const X=()=>{const te=y.current;te&&(E.current=te.scrollHeight),W.current=!0,u==null||u()},we=o.useMemo(()=>{const te=s.map((oe,F)=>({type:"message",data:oe,index:F,ts:Ml(oe,F,m)}));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 xe=0;for(const oe of te){for(;xe<de.length&&oe.ts>0&&de[xe].ts<oe.ts;)ae.push(de[xe++]);ae.push(oe)}for(;xe<de.length;)ae.push(de[xe++]);return ae},[s,r,m]),Le=S>0||!!w,ie=S>0?`↑ Show ${Math.min(S,80)} earlier messages${S>80?` (${S} hidden)`:""}`:M?`↻ ${M}`:"↑ 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 ${M&&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(Ll,{log:se},`action-${te.index}`)}const de=te.data,ae=te.index,xe=vs(de,ae),oe=de.receivedAt||m[xe],F=`${l}-${xe}`,be=A.has(F);return t.jsx(_l,{message:de,receivedAt:oe,agentName:n,userName:a,isCliMode:i,isTextExpanded:be,onToggleTextExpanded:()=>T(se=>{const pe=new Set(se);return be?pe.delete(F):pe.add(F),pe})},`msg-${xe}`)}),c&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:C})]})})}),Pl=o.memo(Rl,(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),Dl="modulepreload",El=function(e){return"/"+e},Ba={},$l=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(m=>{if(m=El(m),m in Ba)return;Ba[m]=!0;const p=m.endsWith(".css"),u=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${u}`))return;const f=document.createElement("link");if(f.rel=p?"stylesheet":Dl,p||(f.as="script"),f.crossOrigin="",f.href=m,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 ${m}`)))})}))}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 Ka=!1;const Yo=o.forwardRef(({onInput:e,onResize:s,fontSize:r=13,readOnly:n=!1},a)=>{const i=o.useRef(null),[c,l]=o.useState(null),m=o.useRef([]),p=o.useRef(!1),u=o.useRef(!1),f=o.useRef(!1),w=()=>{const S=i.current;if(S){p.current&&(S.clear(),p.current=!1);for(const M of m.current)S.write(M);m.current=[],u.current&&(S.fit(),u.current=!1),f.current&&(S.bumpResize(),f.current=!1)}};return o.useImperativeHandle(a,()=>({write:S=>{i.current?i.current.write(S):m.current.push(S)},clear:()=>{i.current?i.current.clear():(m.current=[],p.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(m.current=[],p.current=!0)},resize:(S,M)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(S,M)},fit:()=>{i.current?i.current.fit():u.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 $l(()=>import("./terminal-fZXg9GuG.js"),__vite__mapDeps([0,1,2])).then(M=>{Ka||(Ka=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),S||l(()=>M.GhosttyTerminalView)}).catch(M=>{console.error("[CliTerminal] failed to load terminal renderer",M)}),()=>{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"}})});Yo.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 Wa({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 Bl({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,m=c/l,p=a.width/a.height;let u,f,w,S;m>p?(u=a.width,f=a.width/m,w=0,S=(a.height-f)/2):(f=a.height,u=a.height*m,w=(a.width-u)/2,S=0);const M=a.left-i.left+w+u*e.nx,d=a.top-i.top+S+f*e.ny,b=Math.max(8,Math.min(i.width-8,M)),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 Kl({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:m,isConnActive:p,zoom:u,isMobile:f,mobileFillZoom:w,onZoomOut:S,onZoomReset:M,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=>{m(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"})]}),u>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*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: ",u<=(f?w:1)+.01?f?"FILL":"FIT":`${Math.round(u*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(),M()},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 Wl({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 Ol(){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 Oa(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(!Ol())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,Oa(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,Oa(s[c])]))}),r.current=s})}function Hl({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:m,setPanX:p,setPanY:u,setZoom:f,lastWheelTimeRef:w,onAction:S,setLastActionStatus:M,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),B=o.useRef(0),A=o.useRef(null),T=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,D=60,E=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 be=r.current.getBoundingClientRect();return!be.width||!be.height?null:{nx:Math.max(0,Math.min(1,(F.clientX-be.left)/be.width)),ny:Math.max(0,Math.min(1,(F.clientY-be.top)/be.height))}},te=(F,be)=>{if(!r.current)return{dnx:0,dny:0};const se=r.current,pe=se.getBoundingClientRect(),Z=se.naturalWidth||pe.width,le=se.naturalHeight||pe.height,ne=Z/le,ge=pe.width/pe.height;let me,$;return ne>ge?(me=pe.width,$=pe.width/ne):($=pe.height,me=pe.height*ne),{dnx:F/me,dny:be/$}},de=(F,be,se)=>{if(se<=1.05)return;const pe=-(F-.5)*100,Z=-(be-.5)*100,le=b(pe,Z,se);(Math.abs(le.x-l.current)>.1||Math.abs(le.y-m.current)>.1)&&(p(le.x),u(le.y),l.current=le.x,m.current=le.y)},ae=F=>{const be=s.current;if(be&&F.target instanceof Node&&be.contains(F.target))F.preventDefault();else return;if(F.touches.length===1){const se=F.touches[0];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};M("Right Click"),d(pe.nx,pe.ny,"right"),N.current("input_click",{...pe,button:"right"}).catch(()=>{})}else{const pe=Ie(se);pe&&(M("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),T.current=c.current,L.current={x:(F.touches[0].clientX+F.touches[1].clientX)/2,y:(F.touches[0].clientY+F.touches[1].clientY)/2}}},xe=F=>{const be=s.current;if(be&&F.target instanceof Node&&be.contains(F.target)&&F.preventDefault(),F.touches.length===1&&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},ge=Math.max(0,Math.min(1,ne.nx+le.dnx)),me=Math.max(0,Math.min(1,ne.ny+le.dny));v.current={nx:ge,ny:me},P({nx:ge,ny:me}),M(`Cursor: ${Math.round(ge*100)}%, ${Math.round(me*100)}%`),de(ge,me,c.current);const $=Date.now();$-w.current>=30&&(w.current=$,N.current("input_mouseMoved",{nx:ge,ny:me}).catch(()=>{}))}else if(c.current>1){const le=s.current;if(le){const ne=le.clientWidth,ge=le.clientHeight,me=l.current+pe/ne*100,$=m.current+Z/ge*100,ye=b(me,$,c.current);p(ye.x),u(ye.y),l.current=ye.x,m.current=ye.y}}else{const le=Ie(se);if(le){const ne=Date.now();ne-w.current>=40&&(w.current=ne,M("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,ge=(F.touches[0].clientY+F.touches[1].clientY)/2,me=ne-L.current.x,$=ge-L.current.y,ye=Math.abs(le-1)>.03;if(R.current==="mouse"){if(ye){const he=Math.max(i,Math.min(5,T.current*le));f(he),c.current=he}else if(Math.abs(me)>2||Math.abs($)>2){const he=v.current||{nx:.5,ny:.5},ke=Date.now();ke-w.current>=30&&(w.current=ke,M("Scroll"),N.current("input_wheel",{nx:he.nx,ny:he.ny,deltaX:Math.round(-me*3),deltaY:Math.round(-$*3)}).catch(()=>{}))}}else{const he=Math.max(i,Math.min(5,T.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=m.current+$/Se*100,Ge=b(Ue,De,he);p(Ge.x),u(Ge.y),l.current=Ge.x,m.current=Ge.y}}L.current={x:ne,y:ge}}},oe=F=>{var be;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-(((be=j.current)==null?void 0:be.time)||0),le=j.current?se.clientX-j.current.x:0,ne=j.current?se.clientY-j.current.y:0,ge=Math.sqrt(le*le+ne*ne);if(R.current==="mouse"){if(Z<U||Z>G||ge>I){g.current=!1;return}const me=v.current||Ie(se);me&&(M(`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<D||Z>E||ge>W){g.current=!1;return}const me=Ie(se);if(!me)return;pe-B.current<300?(M("Double tap"),d(me.nx,me.ny,"double"),N.current("input_click",{...me,clickCount:2}).catch(()=>{}),B.current=0):(M(`Tap: ${Math.round(me.nx*100)}%, ${Math.round(me.ny*100)}%`),d(me.nx,me.ny,"left"),N.current("input_click",{...me}).catch(()=>{}),B.current=pe)}}g.current=!1}};return ie.addEventListener("touchstart",ae,{passive:!1}),ie.addEventListener("touchmove",xe,{passive:!1}),ie.addEventListener("touchend",oe,{passive:!1}),()=>{ie.removeEventListener("touchstart",ae),ie.removeEventListener("touchmove",xe),ie.removeEventListener("touchend",oe),x.current&&clearTimeout(x.current)}},[e,s,r,i,c,l,m,p,u,f,w,M,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),u(0),l.current=0,m.current=0}}}function Xo({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),m=o.useRef(null),[p,u]=o.useState(null),[f,w]=o.useState(""),[,S]=o.useState(!1),[M,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),B=o.useRef(!1),[A,T]=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),D=o.useRef(R);o.useEffect(()=>{G.current=A},[A]),o.useEffect(()=>{I.current=L},[L]),o.useEffect(()=>{D.current=R},[R]),o.useEffect(()=>{var Z;(Z=c.current)==null||Z.focus()},[]);const E=r==="connected",W=n,X=E?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",we=E?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!v||B.current||!W)return;const Z=m.current,le=l.current;if(!Z||!le)return;const ne=()=>{const ge=le.clientWidth,me=le.clientHeight,$=Z.naturalWidth,ye=Z.naturalHeight;if(!$||!ye||!ge||!me)return;const he=Math.min(ge/$,me/ye),J=Math.max(ge/$,me/ye)/he;J>1.01&&(x(J),T(J),G.current=J),B.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 ge=(ne-1)/(2*ne)*100,me=(ne-1)/(2*ne)*100;return{x:Math.max(-ge,Math.min(ge,Z)),y:Math.max(-me,Math.min(me,le))}},Ie=(Z,le)=>{if(!m.current)return null;const ne=m.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 ge=l.current;if(!ge)return;const me=ge.getBoundingClientRect(),$=++b.current;d(ye=>[...ye,{id:$,x:Z-me.left,y:le-me.top,type:ne}]),setTimeout(()=>d(ye=>ye.filter(he=>he.id!==$)),600)},de=(Z,le,ne)=>{const ge=m.current,me=l.current;if(!ge||!me)return;const $=ge.getBoundingClientRect(),ye=me.getBoundingClientRect(),he=ge.naturalWidth||$.width,ke=ge.naturalHeight||$.height,J=he/ke,Se=$.width/$.height;let Ue,De,Ge,Qe;J>Se?(Ue=$.width,De=$.width/J,Ge=0,Qe=($.height-De)/2):(De=$.height,Ue=$.height*J,Ge=($.width-Ue)/2,Qe=0);const Ze=$.left-ye.left+Ge+Ue*Z,ut=$.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){u(`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 ge=await e("input_click",{nx:le.nx,ny:le.ny});ge!=null&&ge.success||s(`❌ Click failed: ${ge==null?void 0:ge.error}`)}catch(ge){s(`❌ Click error: ${ge.message||ge}`)}}},xe=async(Z,le,ne,ge=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:ge})}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),u(`Key: ${Z.key}`),await xe(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(""),u(`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 u("Key: Enter"),await xe("Enter","Enter",!1)}};o.useEffect(()=>{const Z=c.current;if(!Z)return;const le=ne=>{var ge;if((ge=m.current)!=null&&ge.contains(ne.target)){ne.preventDefault();const me=Date.now();if(me-U.current<40)return;U.current=me;const $=Ie(ne.clientX,ne.clientY);if(!$)return;u(`Scroll: ${Math.round(ne.deltaY)}`),e("input_wheel",{nx:$.nx,ny:$.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:be,handleToggleInputMode:se,handleZoomReset:pe}=Hl({containerRef:c,viewportRef:l,imgRef:m,inputMode:j,setInputMode:k,minZoom:Le,zoomRef:G,panXRef:I,panYRef:D,setPanX:O,setPanY:N,setZoom:T,lastWheelTimeRef:U,onAction:e,setLastActionStatus:u,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:m,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(Wl,{waitingLabel:X,waitingHint:we,transportType:i}),j==="mouse"&&W&&t.jsx(Bl,{cursorPos:be,viewportRef:l,imgRef:m}),M.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(Kl,{inputMode:j,onToggleInputMode:se,isImeOpen:C,setIsImeOpen:P,isMenuOpen:y,setIsMenuOpen:h,imeText:f,setImeText:w,handleImeSubmit:F,isConnActive:E,zoom:A,isMobile:v,mobileFillZoom:g,onZoomOut:()=>T(Z=>Math.max(.5,Z-.25)),onZoomReset:pe,onZoomIn:()=>T(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 zr(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=s,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const m=Math.floor(l/60);if(m<24)return`${m}h${r}`;const p=Math.floor(m/24);return p<7?`${p}d${r}`:new Date(e).toLocaleDateString()}const Qo=e=>zr(e);function Ul(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden}}function Ps(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 Vr(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...Ul(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 Rr(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 ea(e,s,r){var M,d,b;const n=Rr(e,s),a=Ps(e),i=e.sessionId&&((M=r==null?void 0:r.notificationStateBySessionId)==null?void 0:M.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,m=a.isGenerating,p=a.isWaiting,u=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||p,f=n.inboxBucket==="working"||m,S=n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation));return{unread:S,requiresAction:u,isWorking:f,isReconnecting:c,isConnecting:l,isGenerating:m,isWaiting:p,inboxBucket:u?"needs_attention":f?"working":S?"task_complete":"idle"}}function Fl(e,s,r){return ea(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function Jo({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ps(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),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(ds,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,m)=>{const p=c(l).toLowerCase(),u=/^(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 ${u?"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:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:f?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:w?"⏳ ...":c(l)},m)})})]})]})}var zl=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Vl(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function wt(e,s){if(Vl(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":zl.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 Zo(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 Gl(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 an(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Gr(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 ql(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 Yl(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Xl(e){return ql(e.trim().replace(/\.local$/i,""))}function Ql(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function ei(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&&!Yl(c));if(r&&r!=="Unknown")return Xl(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function It(e,s={}){return Ql(e)||ei(e,s)}function ti(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 si(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 us(e,s){return ti(e).join(" · ")}function Qs(e){return e.transport==="pty"}function ws(e){return e.transport==="acp"}function Jl(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 Ha(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 Zl(e){return wt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function ed(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"),m=r.indexOf(c||"idle");m>=0&&(l<0||m<l)&&s.set(a,{...n,status:c})}return Array.from(s.values())}function td(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 sd(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&&td(s.receivedAt)||0}function rd(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Rn(e){return Math.max(rd(e),sd(e.activeChat))}function nd(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 ta(e,s){return nd(Rn(e),Rn(s),It(e,{fallbackId:e.id}),It(s,{fallbackId:s.id}),e.id,s.id)}const ri="adhdev_notification_prefs",Ua={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function ad(){try{const e=localStorage.getItem(ri);if(e){const s=JSON.parse(e);return{...Ua,...s}}}catch{}return{...Ua}}function od(e){try{localStorage.setItem(ri,JSON.stringify(e))}catch{}}let Wt=ad(),Sr=[];function id(){Sr.forEach(e=>e())}function cd(e){Wt={...Wt,...e},od(Wt),id()}function ld(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Sr.push(r),()=>{Sr=Sr.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{cd(r)},[]);return[{...Wt},s]}function Fs(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 dd={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function ud(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function ni(){return"Notification"in window&&Notification.permission==="granted"}let Jt=null;async function md(){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 Pn(e,s,r){if(ni())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 pd(e,s={}){const r={...dd,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{md().then(l=>{i.current=l})},[]);const c=o.useCallback((l,m,p)=>{const u=Date.now();u-a.current<r.throttleMs||(a.current=u,Pn(l,m,p))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!ni())&&Fs("browser")&&i.current!==!0){if(document.hasFocus()){for(const m of e)n.current.set(m.id,wt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const p=n.current.get(m.id),u=wt(m.status,{activeModal:m.activeModal}),f=m.name||m.id;if(r.onApproval&&Fs("approval")&&u==="waiting_approval"&&p!=="waiting_approval"){const w=((l=m.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,w.slice(0,120),`approval-${m.id}`)}r.onComplete&&Fs("completion")&&Zo(p)&&u==="idle"&&c(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&u==="error"&&p!=="error"&&c(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,u)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const fd=/^(run|approve|accept|yes|allow|always)/,hd=/^(run|approve|accept|yes|allow|always|proceed|save)/,xd=/^(reject|deny|delete|remove|abort|cancel|no)/;function sa(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function bd(e){const s=sa(e).toLowerCase();return fd.test(s)?"primary":xd.test(s)?"danger":"default"}function gd(e){return hd.test(sa(e).toLowerCase())?"approve":"reject"}function yd(e){return e.map((s,r)=>({label:sa(s),variant:bd(s),action:gd(s),button:s,buttonIndex:r}))}function vd(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 wd(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function jd(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 kd{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 M,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 m=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,p=(m==null?void 0:m.type)||"";let u=at(p);const f=this.resolveOwningDaemon(s);if(f){const b=It(f,{fallbackId:f.id});b&&(u=!p||p==="adhdev-daemon"?b:`${b}/${u}`)}let w="",S="info";if(s.event==="agent:generating_completed"){const b=s.duration?` (${s.duration}s)`:"";w=`✅ ${u} 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=`⚡ ${u} approval needed`,S="warning",n&&!((M=s.modalButtons)!=null&&M.length)&&this.emitSystemMessage(n,{role:"system",timestamp:a,content:vd(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=yd(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=wd(u,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=`⚠️ ${u} agent is taking a long time${b}`,S="warning",Fs("browser")&&!document.hasFocus()&&Pn(`⚠️ ${u} — 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=jd(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=""}Fs("browser")&&!document.hasFocus()&&Pn("👁️ 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 kd,Fa=new Map;function Is(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ai(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Sd(e){return!Is(e)||!Is(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function lr(e){return!Is(e)||!Is(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function $s(e){if(!(!Is(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function dr(e){return Is(e)&&e.success===!1}function Nd(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 Cd(e,s){return e&&ai(e.currentValue)?e.currentValue:s}function Nr(e,s){return e.options||s[e.id]||[]}function on(e,s){return{value:s}}function Id(e,s,r){var a;return r?((a=Nr(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const Ad={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Md({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=Mt(),m=`${e}:${s||n}`,p=Ad[n]||"#94a3b8",[u,f]=o.useState({}),w=o.useRef(0),S={};for(const R of i||[])R.defaultValue!==void 0&&(S[R.id]=R.defaultValue);const M={...S,...c||{},...Date.now()<w.current?u:{}};o.useEffect(()=>{c&&Date.now()>w.current&&f({})},[c]);const[d,b]=o.useState(Fa.get(m)||{}),[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=Cd(U,N);f(I=>({...I,[R.id]:G})),Nd(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 B=async R=>{if(y===R.id){h(null);return}if(Nr(R,d).length>0){h(R.id);return}if(R.dynamic&&R.listScript){P(R.id);try{const U=await j(R.listScript,{}),G=Sd(U);if(!G){const D=$s(U);D&&ot.showToast(D,"warning");return}const I=G.options;if(b(D=>{const E={...D,[R.id]:I};return Fa.set(m,E),E}),ai(G.currentValue)){const D=G.currentValue;f(E=>({...E,[R.id]:D}))}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,on(R,N)),I=lr(G);if(I&&!I.ok||dr(G))throw new Error((I==null?void 0:I.error)||$s(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")}},T=async R=>{const N=Nr(R,d).map(W=>W.value);if(N.length===0)return;const U=String(M[R.id]||""),I=(N.indexOf(U)+1)%N.length,D=N[I];if(typeof D!="string")return;const E=(c==null?void 0:c[R.id])??S[R.id];f(W=>({...W,[R.id]:D})),w.current=Date.now()+5e3;try{if(!R.setScript)return;const W=await j(R.setScript,on(R,D)),X=lr(W);if(X&&!X.ok||dr(W))throw new Error((X==null?void 0:X.error)||$s(W)||`Could not update ${R.label}`);k(R,D,X)}catch(W){g(R,E);const X=W instanceof Error?W.message:`Could not update ${R.label}`;ot.showToast(X,"warning")}},L=async R=>{const U=!M[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,on(R,U)),D=lr(I);if(D&&!D.ok||dr(I))throw new Error((D==null?void 0:D.error)||$s(I)||`Could not update ${R.label}`);k(R,U,D)}catch(I){g(R,G);const D=I instanceof Error?I.message:`Could not update ${R.label}`;ot.showToast(D,"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)||$s(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(M[R.id]||""),U=Id(R,d,N),G=y===R.id,I=C===R.id,D=Nr(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:()=>B(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&&D.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>h(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] bg-[var(--surface-primary)] border border-border-subtle rounded-lg mb-1 max-h-[220px] overflow-y-auto min-w-40 shadow-[0_-4px_16px_rgba(0,0,0,0.3)]",children:[t.jsx("div",{className:"px-3 py-1.5 text-[9px] font-bold text-text-muted tracking-wider border-b border-border-subtle",children:R.label.toUpperCase()}),D.map(E=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:E.value===N?`${p}18`:"transparent",color:E.value===N?p:"var(--text-secondary)",fontWeight:E.value===N?600:400,borderLeft:E.value===N?`2px solid ${p}`:"2px solid transparent"},title:E.description||E.label,onMouseEnter:W=>{W.currentTarget.style.background=`${p}12`},onMouseLeave:W=>{W.currentTarget.style.background=E.value===N?`${p}18`:"transparent"},onClick:()=>A(R,E.value),children:E.label},E.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:()=>T(R),title:`Click to cycle: ${D.map(E=>E.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 Td=o.memo(function({contextKey:s,panelLabel:r,isSending:n,onSend:a,isActive:i=!0}){const c=o.useRef(null),[l,m]=o.useState("");o.useEffect(()=>{m("")},[s]),o.useEffect(()=>{var u;i&&((u=c.current)==null||u.focus())},[s,i]);const p=()=>{const u=l.trim();!u||n||(m(""),a(u))};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:u=>m(u.target.value),onPaste:u=>{const f=u.clipboardData.getData("text");f&&m(w=>w+f),u.preventDefault()},onKeyDown:u=>{if(u.key==="Enter"){if(u.nativeEvent.isComposing){u.preventDefault();return}u.preventDefault(),p()}},onBlur:u=>{if(window.innerWidth<768){const f=u.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",As=(e,s)=>et(e)?e.mode||"terminal":"chat",oi=(e,s)=>et(e)&&As(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 ii(e){return e.machineName||""}function er(e){return qt(e)}function Dt(e){return e.agentType||""}function Pr(e){return e.hostIdeType||""}function ra(e){return e.displayPrimary||e.agentName||"Agent"}function ci(e){return[e.displaySecondary,ii(e)].filter(Boolean)}function ms(e){return e.agentName||at(Dt(e))}function Ld(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(Pr(e)||Dt(e))}function na(e){return Vt(e)?e.sessionId:e.nativeSessionId}function za(e){return Vt(e)?"native":e.tabKey}function _d(e){return e.sessionId}function Rd(e,s){if(s)return Vt(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Pd(e,s){const r=Dt(e),n=Vt(e),a=et(e)||Xe(e),i=n?a?ms(e)||(s==null?void 0:s.cliName)||at(Pr(e)||r):s!=null&&s.type?at(s.type):at(Pr(e)||r):ms(e);return{isNativeConversation:n,isCli:et(e),isAcp:Xe(e),isCliTerminal:oi(e),providerType:r,displayLabel:i,targetEntry:Rd(e,s)}}function li({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=_s(),c=qt(e),l=ii(e),m=e.transport==="cdp-page"||e.transport==="cdp-webview",p=e.streamSource==="agent-stream"&&!!e.agentName,u=!p&&(e.transport==="pty"||e.transport==="acp"),f=ms(e),w=Ld(e),S=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),M=o.useCallback(()=>{if(r){r();return}const d=na(e);d&&i(`/dashboard?activeTab=${encodeURIComponent(d)}`)},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[m&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:M,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(Xs,{size:12}),t.jsx("span",{children:f})]}),u&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[t.jsx(Xs,{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 cn(e,s){return`${e}:${s}`}function Dd(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function ur(e,s){Dd()&&console.debug(`[subscription-manager] ${e}`,s)}class Ed{constructor(){Ye(this,"active",new Map)}subscribe(s,r,n,a){var p;const i=cn(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 u={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,u),ur("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((p=s.sendData)==null?void 0:p.call(s,r,n))??!1}const m=()=>{var w;const u=this.active.get(i);if(!u||(u.handlers.delete(a),u.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 m.initialSendAccepted=l,m}publish(s){const r=cn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Ss.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),Ss.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=cn(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 Ed;function $d(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 Bd(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:$d(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 Kd(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 Dr(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),m=e.sessions||[],{topLevel:p,childrenByParent:u}=Kd(m),f=Bd(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"),M=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=(u.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 M){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 ln=new Map,dn=new Map,un=new Set,zs=new Map,Wd=1200;function Od(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 Va(e,s){const r=zs.get(e);!r||r.size===0||(zs.delete(e),r.forEach(n=>n(s)))}function Hd(e,s){return new Promise(r=>{const n=zs.get(e)||new Set;zs.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&zs.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function tr(){const{sendCommand:e,sendData:s}=Mt(),{injectEntries:r,getIdes:n}=_r();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??6e4,l=dn.get(a)||0;if(!(i!=null&&i.force)&&un.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const m=ln.get(a);if(m)return m;const p=(async()=>{if(s&&!un.has(a)&&(un.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=Dr(d.status,{daemonId:a,existingDaemon:y,existingEntries:b,timestamp:d.timestamp});h.length>0&&r(h),dn.set(a,Date.now()),Va(a,!0)}),!(i!=null&&i.force)&&await Hd(a,Wd)))return;const u=await e(a,"get_status_metadata"),f=Od(u);if(!f)return;const w=n(),S=w.find(d=>d.id===a),M=Dr(f,{daemonId:a,existingDaemon:S,existingEntries:w,timestamp:f.timestamp||Date.now()});M.length>0&&r(M,{authoritativeDaemonIds:[a]}),dn.set(a,Date.now()),Va(a,!0)})().finally(()=>{ln.delete(a)});return ln.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 aa(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=Cs(e.content),i=Cs(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 Ga(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 Ms(e){return Cs(e==null?void 0:e.content)}function Dn(e,s){return!e||!s||e.length<=s.length||s.length<80?!1:e.startsWith(s)||e.includes(s)}function Ud(e,s){const r=Ms(e),n=Ms(s);return!r||!n||r===n?null:Dn(r,n)?e:Dn(n,r)?s:null}function Fd(e,s){const r=Ud(e,s);if(r)return r;const n=Ga(e),a=Ga(s);return a!==n?a>n?s:e:Ms(s).length>=Ms(e).length?s:e}function ts(e){const s=[];for(const r of e){const n=s.findIndex(a=>aa(a,r));if(n>=0){s.splice(n,1,Fd(s[n],r));continue}s.push(r)}return s}function zd(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:ts([...r,...n])}function qa(e){return[...e].sort((s,r)=>{const n=Ut(s),a=Ut(r);return n&&a&&n!==a?n-a:0})}function Ya(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=>aa(i,n));return a>=0?(r.splice(a,1),!1):!0})}function Vd(e,s){return e.filter(r=>{const n=Ms(r),a=String((r==null?void 0:r.role)||"").toLowerCase(),i=Ut(r);return!s.some(c=>{if(aa(r,c))return!0;const l=String((c==null?void 0:c.role)||"").toLowerCase();if(!n||!a||a!==l)return!1;const m=Ms(c);if(!Dn(m,n)&&m!==n)return!1;const p=Ut(c);return i&&p?Math.abs(i-p)<=15e3:!0})})}const Gd=60,qd=200;function Yd(e={}){return e.isCliLike?qd:Gd}const sr=60,Xa=new Map;function Xd(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 di(e,s){return`${e}::${s}`}function En(e=sr){return{liveMessages:[],cursor:mi([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function ui(e){if(!e)return"";let s="";try{s=JSON.stringify(e.content??"")}catch{s=String(e.content??"")}return Xd([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),s])}function mi(e,s=sr){return{knownMessageCount:e.length,lastMessageSignature:ui(e[e.length-1]),tailLimit:s}}function pr(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 Qd(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return ts([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return ts([...e.slice(0,n),...r])}case"full":{const n=Math.max(Number(s.totalMessages||0),r.length);if(n>r.length&&e.length>r.length){const a=Math.max(0,n-r.length);return ts([...e.slice(0,a),...r])}return r}default:return r}}class Jd{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=En(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}hydrateLiveMessages(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=ts([...r,...this.snapshot.liveMessages]);if(n.length<r.length)return;const a=mi(n,this.snapshot.cursor.tailLimit);pr(this.snapshot.liveMessages)===pr(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a})}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}retain(){this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),this.retainCount===0&&this.disconnect()}async loadHistoryPage(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await s(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},knownMessageCount:this.snapshot.cursor.knownMessageCount,lastMessageSignature:this.snapshot.cursor.lastMessageSignature,...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}},s=>{this.handleUpdate(s)}))}disconnect(){var s;(s=this.transportSubscription)==null||s.call(this),this.transportSubscription=null}dispose(){this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){const r=Qd(this.snapshot.liveMessages,s),n={knownMessageCount:Math.max(r.length,Number(s.totalMessages||0)),lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:ui(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};pr(this.snapshot.liveMessages)===pr(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 pi(e){const s=di(e.daemonId,e.sessionId),r=Xa.get(s);if(r)return r.updateOptions(e),r;const n=new Jd(e);return Xa.set(s,n),n}function Zd(e,s){return{...e,loadHistoryPage:s}}function eu(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function tu(e){const s=new Set,r=[];for(const n of e){const a=er(n),i=n.sessionId||"";if(!a||!i)continue;const c=di(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(eu),{descriptors:r,signature:r.map(n=>`${n.subscriptionKey}|${n.historySessionId}`).join("||")}}function su(e,s){const{sendData:r,sendCommand:n}=Mt(),a=(s==null?void 0:s.enabled)!==!1,i=er(e),c=e.sessionId||"",l=e.providerSessionId||c,m=`daemon:${i}:session:${c}`,p=Math.max(0,(s==null?void 0:s.tailLimit)??sr),u=o.useMemo(()=>!a||!i||!c?null:pi({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:m,sendData:r,tailLimit:p}),[i,a,l,r,c,m,p]),[f,w]=o.useState(()=>(u==null?void 0:u.getSnapshot())||En(p));o.useEffect(()=>{if(!u){w(En(p));return}u.hydrateLiveMessages(e.messages),u.retain(),w(u.getSnapshot());const M=u.subscribe(d=>{w(d)});return()=>{M(),u.release()}},[e.messages,u,p]);const S=o.useCallback(async()=>{!u||!i||!c||await u.loadHistoryPage(async()=>{const M=e.agentType,d=await n(i,"chat_history",{agentType:M,offset:u.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,u,i,l,n,c]);return o.useMemo(()=>Zd(f,S),[S,f])}function ru(e,s){const{sendData:r}=Mt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,sr),i=o.useMemo(()=>tu(e),[e]);o.useEffect(()=>{if(!r||i.descriptors.length===0)return;const c=i.descriptors.map(l=>pi({...l,sendData:r,tailLimit:a}));return c.forEach(l=>l.retain()),()=>{c.forEach(l=>l.release())}},[i.signature,n,r,a])}function nu(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function au(e){return nu(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const ou=60;function $n({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,handleFocusAgent:a,isFocusingAgent:i,actionLogs:c,userName:l,showMetaChips:m=!1,scrollToBottomRequestNonce:p,isInputActive:u=!0}){var I,D;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(()=>Ps(e),[e.status,e.connectionState]),M=o.useMemo(()=>Pd(e,s),[e,s]),d=Yd({isCliLike:M.isCli||M.isAcp}),b=su(e,{enabled:!!e.sessionId}),[y,h]=o.useState(d),C=e.tabKey,P=b.historyMessages,v=b.hasMoreHistory,j=b.historyError,k=zd(b.liveMessages,e.messages);o.useEffect(()=>{h(d)},[d,C]);const g=Math.max(0,k.length-y),x=ra(e),B=er(e),A=au(e),[T,L]=o.useState(!1);o.useEffect(()=>{const E=M.targetEntry;B&&(!E||E.providerControls===void 0||E.controlValues===void 0)&&w(B,{minFreshMs:3e4}).catch(()=>{})},[B,M.isAcp,(I=M.targetEntry)==null?void 0:I.providerControls,(D=M.targetEntry)==null?void 0:D.controlValues,w]);const O=o.useCallback(async()=>{if(!T){if(k.length>y){h(E=>Math.min(k.length,E+ou));return}L(!0);try{await b.loadHistoryPage()}finally{L(!1)}}},[b,T,k.length,y]),{allMessages:R,receivedAtMap:N}=o.useMemo(()=>{const E=g>0?k.slice(-y):k;if(P.length===0){const Le=qa(ts(E)),ie={};return Le.forEach((Ie,te)=>{const de=`${e.tabKey}:${vs(Ie,te)}`;let ae=Ut(Ie)||f.current.get(de)||0;ae||(ae=Date.now(),f.current.set(de,ae)),ie[vs(Ie,te)]=ae}),{allMessages:Le,receivedAtMap:ie}}const W=Vd(P,E),X=qa(ts([...W,...E])),we={};return X.forEach((Le,ie)=>{const Ie=`${e.tabKey}:${vs(Le,ie)}`;let te=Ut(Le)||f.current.get(Ie)||0;te||(te=Date.now(),f.current.set(Ie,te)),we[vs(Le,ie)]=te}),{allMessages:X,receivedAtMap:we}},[e.tabKey,g,P,k,y]),U=o.useMemo(()=>c.filter(E=>E.routeId===e.tabKey).sort((E,W)=>E.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(Xs,{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(Ns,{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(Fo,{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(Ns,{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"&&!T)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,T,k.length,x,S.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[m&&t.jsx(li,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(Pl,{messages:R,actionLogs:U,agentName:ms(e)||x||"Agent",userName:l,isCliMode:M.isCli||M.isAcp,isWorking:S.isGenerating,contextKey:e.tabKey,receivedAtMap:N,onLoadMore:O,isLoadingMore:T,hasMoreHistory:v,hiddenLiveCount:g,loadError:j??void 0,emptyState:G,scrollToBottomRequestNonce:p}),u&&!M.isCliTerminal&&(()=>{var E,W;return t.jsx(Md,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:M.providerType,displayLabel:M.displayLabel,controls:(E=M.targetEntry)==null?void 0:E.providerControls,controlValues:(W=M.targetEntry)==null?void 0:W.controlValues})})(),!M.isCliTerminal&&t.jsx(Td,{contextKey:e.tabKey,panelLabel:x,isSending:n,onSend:r,isActive:u})]})}let fi=ls;function hi(){return fi()}class iu{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 xi=new iu;class cu{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 cu;function lu(e){e.dashboardWS&&(xi=e.dashboardWS),e.connectionManager&&(dt=e.connectionManager),e.useDaemonsHook&&(fi=e.useDaemonsHook)}function it(e){return ra(e)}function ps(e){return ci(e).join(" · ")}function bi(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=Cs(s==null?void 0:s.content);return r||(e.title?e.title:ps(e)||"No messages yet")}function gi(e,s){const{isReconnecting:r,isConnecting:n}=Ps(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function du(e,s){const r=["Chat",...ci(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function ss(e){return gi(e)||ps(e)}function uu(e){return`${it(e)} · ${bi(e)}`}function mu(e){const s=Pr(e),r=s?at(s):ms(e);return`${it(e)} — ${r||"Agent"}`}function pu(e){return ms(e)||"CLI"}function yi(e){return e.title||ms(e)||e.routeId}function vi(e){return e?`Remote · ${it(e)||e.workspaceName||"Session"}`:"Remote"}function fu({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,isVisible:i=!0}){var D;const{ides:c}=ls(),l=o.useRef(null),{sendCommand:m,sendData:p}=Mt(),[u,f]=o.useState(""),[w,S]=o.useState(!1),[M,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||((D=e.routeId)==null?void 0:D.split(":")[0])||e.routeId||"",B=c.find(E=>E.id===x&&E.type==="adhdev-daemon"),A=(B==null?void 0:B.terminalSizingMode)==="fit"?"fit":"measured",T=.6,L=1.15,O=()=>{if(typeof window>"u")return 1;const E=window.innerWidth||0;return E<=360?.68:E<=390?.74:E<=430?.82:E<=480?.9:1},R=()=>{var E,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=(E=r.current)==null?void 0:E.reset)==null||W.call(E)},N=()=>{var E,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=(E=r.current)==null?void 0:E.reset)==null||W.call(E)},U=()=>{var W;if(j.current=null,!i)return;const E=C.current;E&&(C.current="",(W=r.current)==null||W.write(E))},G=E=>{E&&(C.current+=E,i&&j.current===null&&(j.current=requestAnimationFrame(U)))},I=(E,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),E&&((de=r.current)==null||de.write(E)))};return o.useEffect(()=>{R()},[g]),o.useEffect(()=>{var W;if(!g)return;const E=((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()=>{E()}},[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 E=(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()=>{E==null||E()}},[x,g,r]),o.useEffect(()=>{s&&R()},[s,k,r]),o.useEffect(()=>{f("")},[e.tabKey]),o.useEffect(()=>{const E=()=>{b.current||d(O())};return E(),window.addEventListener("resize",E),()=>window.removeEventListener("resize",E)},[]),o.useEffect(()=>{var W;if(!i){(W=l.current)==null||W.blur();return}v.current&&(v.current=!1,N());const E=P.current;E&&(P.current=null,I(E.text,E.seq,E.cols,E.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 E=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",E),()=>{window.removeEventListener("adhdev:fit-cli-terminal",E)}},[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(E=>Math.max(T,Number((E-.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(E=>Math.min(L,Number((E+.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/M}%`,height:`${100/M}%`,transform:`scale(${M})`,transformOrigin:"top left"},children:t.jsx(Yo,{ref:r,readOnly:!w||!i,sizingMode:A,onInput:E=>{w&&(p!=null&&p(x,{type:"pty_input",sessionId:g,targetSessionId:g,data:E})||m(x,"pty_input",{targetSessionId:g,data:E}).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:u,disabled:!w||!i||a,onChange:E=>f(E.target.value),onPaste:E=>{const W=E.clipboardData.getData("text");W&&f(X=>X+W),E.preventDefault()},onKeyDown:E=>{if(E.key!=="Enter")return;if(E.nativeEvent.isComposing){E.preventDefault();return}E.preventDefault();const W=u.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 E=u.trim();!w||!E||a||(f(""),n(E))},disabled:!w||!i||!u.trim()||a,className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${u.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:u.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:u.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]})})]})}function hu({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 xu({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",m=()=>{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:m,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 oa({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(Ur,{size:n}):t.jsx(Ht,{size:n})})}function Qa({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Ja({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=zr(e.updatedAt),l=!e.readAt;return t.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[s?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",s]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?t.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),t.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:m=>{m.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:m=>{m.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:m=>{m.stopPropagation(),i()},children:"Delete"})]})]})}function bu({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:m,onSetCliViewMode:p,onHideConversation:u,hiddenConversations:f=[],onShowConversation:w,onShowAllHidden:S,onResetPanelsToMain:M,inboxOpen:d,onInboxOpenChange:b,hiddenOpen:y,onHiddenOpenChange:h,onOpenNewSession:C,actionShortcuts:P,notifications:v,notificationUnreadCount:j,onOpenNotification:k,onMarkNotificationRead:g,onMarkNotificationUnread:x,onDeleteNotification:B}){const{ides:A,p2pStates:T={}}=ls(),L=!!e&&et(e)&&!Xe(e),O=!!e&&Xe(e),R=m||(e?oi(e)?"terminal":"chat":null),[N,U]=o.useState(!1),G=o.useRef(null),I=o.useRef(null),D=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",E=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(T),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]),xe=j;o.useEffect(()=>{if(!d)return;const F=be=>{var se;(se=G.current)!=null&&se.contains(be.target)||b(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[d,b]),o.useEffect(()=>{if(!y)return;const F=be=>{var se;(se=I.current)!=null&&se.contains(be.target)||h(!1)};return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[y,h]),o.useEffect(()=>{if(!y&&!d)return;const F=be=>{if(!be.altKey)return;const se=be.code.match(/^Digit([1-9])$/);if(!se)return;const pe=Number(se[1])-1,Z=y?f[pe]:void 0,le=d?ae[pe]:void 0;if(!(!Z&&!le)){if(be.preventDefault(),be.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 be=a.find(se=>se.tabKey===F);be&&(u==null||u(be))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(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:D,boxShadow:E}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[t.jsx("span",{title:n?"Connected":r==="connected"?"Partial":"Disconnected",className:"header-subtitle-dot inline-block w-1.5 h-1.5 rounded-full shrink-0",style:{background:D,boxShadow:E}}),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(ml,{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:ps(e)||it(e),children:it(e)}),(L||O)&&l&&t.jsxs(t.Fragment,{children:[L&&p&&R&&t.jsx(oa,{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(Qn,{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 be=F.dataTransfer.getData("text/tab-key");F.preventDefault(),U(!1),oe(be)},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(zo,{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(Qa,{value:P==null?void 0:P.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[M&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:M,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&&u&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>u(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(Qa,{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,ps(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(Fr,{size:16}),xe>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:xe})]}),d&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[te.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),te.map(F=>t.jsx(Ja,{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:()=>B(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(Ja,{notification:F,onOpen:()=>k(F),onMarkRead:()=>g(F.id),onMarkUnread:()=>x(F.id),onDelete:()=>B(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 gu(e,s){return String(e||"")!==String(s||"")}function yu(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(m=>String(m||"").toLowerCase()).join(`
|
|
31
|
-
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!ti(c.summaryMetadata).map(m=>m.toLowerCase()).join(`
|
|
32
|
-
`).includes(a)))}function vu(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 wi(e,s={}){return vu(yu(e,s),s.sortMode||"recent")}function Er(e){return e?"Resume saved history":"Start fresh"}function ia(e){return e?"Resuming saved history…":"Starting fresh…"}function wu(){return"Start fresh"}function ji(e,s=!1){return e==="cli"?Er(s):e==="ide"?"Start IDE":"Start ACP session"}function ki(e,s=!1){return e==="cli"?ia(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function ju(){return"Recover hosted runtime"}function ku(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Su(){return"Open saved history"}function Nu(){return"Saved History"}function ca(){return"Use saved history when you want continuity in the same provider conversation."}function Cu(){return"No saved history found yet."}function Iu(){return"Refresh saved history"}function Au(){return"Refreshing saved history…"}function rs(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function ns(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 Ls(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function la(e){return`Resume saved history with ${e}?`}function da(){return"Review or change the target workspace before resuming saved history."}function Mu(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 ua({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:m,onClose:p,onNewChat:u,onSwitchSession:f,onRefreshHistory:w,onResumeSavedSession:S}){var g;const M=s.find(x=>x.id===e.routeId),d=(M==null?void 0:M.chats)||[],b=(g=M==null?void 0:M.activeChat)==null?void 0:g.id,y=et(e)&&!Xe(e),[h,C]=o.useState(()=>gt()),P=l||h,v=x=>{if(m){m(x);return}C(x)},j=o.useMemo(()=>wi(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?Nu():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:mu(e)}),y&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:ca()})]}),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:u,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 B=e.providerSessionId===x.providerSessionId,A=B||!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 ${B?"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 ${B?"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:Mu(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",us(x.summaryMetadata)?` · ${us(x.summaryMetadata)}`:"",x.messageCount>0?` · ${x.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:B?"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(xl,{size:32})}),t.jsx("div",{className:"text-[13px]",children:y?a.length>0?"No saved history matches these filters.":Cu():"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:Au()})})]}),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(Rs,{size:13})," ",y?Iu():"Refresh History"]})})})]})]});return typeof document>"u"?k:Ys.createPortal(k,document.body)}const Za={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 Si({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=Za[n.type]||Za.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 Lu(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function _u(e){return e.sessionId||e.instanceId||e.agentType}function mn(e,s){return e||s}function eo(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 Ni(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=It(r,{fallbackId:r.id}));return s}function Ci(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 ma(e,s,r={}){return Ru(e,s,Ci(e,r))}function Ru(e,s,r={}){var f,w,S,M,d,b;const n=[],a=r.machineName,i=r.connectionState,c=Lu(e),l=Jl(e.type,{agentName:e.cliName}),m=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}}):[],u=Tu(e);if(u){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=(M=e.agents)==null?void 0:M[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 B=(et(e)||Xe(e),e.type),A=(et(e)||Xe(e))&&Ha(k,h,B)?"":k,T=j.messages||[],L=eo(s,[e.id,y]),O=Ya(T,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:B,status:v,title:A,messages:[...T,...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:m,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:mn(y,e.id),machineName:a,connectionState:i})}if(u&&(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=Zl(y),P=_u(y),v=`${e.id}:${P}`,j=y.title&&String(y.title).trim()||"",k=Ha(j,y.agentName,y.agentType)?"":j,g=y.messages||[],x=eo(s,[v,y.sessionId,y.instanceId]),B=Ya(g,x);(y.transport==="cdp-webview"||y.sessionId||y.providerSessionId||g.length>0||B.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,...B],hostIdeType:e.type,workspaceName:c,displayPrimary:k||c||y.agentName||m,displaySecondary:`${m} · ${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:mn(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||m,displaySecondary:m,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:mn(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function Pu(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 Du(e,s){const r=Pu(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const Ii=[{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:"🏄"}],Ai=[{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:"🧩"}],Mi=[{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:"🟠"}],Eu=Ii,$u=Ai,Bu=Mi;function fs(...e){return Oc(Hc(e))}function Ku({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:fs("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 Ti({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(Ku,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:fs("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:fs("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 Li({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:fs("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 Wu={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"},Ou={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Hu({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:fs("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Wu[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:Ou[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 Uu={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"},Fu={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function zu({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:fs("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Uu[e],r),children:[t.jsx("span",{className:fs("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Fu[e])}),n]})}const Bn="adhdev:themechange";function Vu(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function gs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function ys(e){return e==="system"?Vu():e}function _i(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Cr(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(Bn,{detail:{preference:e,theme:s}}))}function Gu(){const e=gs(),s=ys(e);_i(s),Cr(e,s)}function pa(){const[e,s]=o.useState(gs),[r,n]=o.useState(()=>ys(gs()));o.useEffect(()=>{_i(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=m=>{if(e==="system"){const p=m.matches?"light":"dark";n(p),Cr("system",p)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=m=>{const p=m.detail||{},u=p.preference,f=p.theme;s(u==="dark"||u==="light"||u==="system"?u:gs()),n(f==="dark"||f==="light"?f:ys(gs()))},l=m=>{if(m.key!=="theme")return;const p=gs(),u=ys(p);s(p),n(u)};return window.addEventListener(Bn,c),window.addEventListener("storage",l),()=>{window.removeEventListener(Bn,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=ys(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}Cr(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",m=ys(l);n(m);try{localStorage.setItem("theme",l)}catch{}return Cr(l,m),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const to={dark:"Dark",light:"Light",system:"System"};function qu({collapsed:e}){const{preference:s,cycleTheme:r}=pa(),n=s==="dark"?t.jsx(gl,{size:16}):s==="light"?t.jsx(bl,{size:16}):t.jsx(yl,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${to[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:to[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 Yu({onPrefChange:e}){const[s,r]=ld(),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(Fr,{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(vl,{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(wl,{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(Xs,{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 $r(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Xu(e,s){const r=$r(e),n=$r(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 Ri(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function Vs(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Xu(r,s)>=0)return!1;const n=$r(r),a=$r(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Qu(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function pn(e,s){return e instanceof Error?e.message:s}function Ju({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(Li,{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(em,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function so({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 Ys.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 Zu(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Eu,...$u,...Bu].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 em({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var O,R;const[i,c]=o.useState("idle"),[l,m]=o.useState(""),[p,u]=o.useState(null),[f,w]=o.useState("idle"),[S,M]=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"),m("Starting upgrade...");try{const N=Qu(await r(e.id,"daemon_upgrade",{}));N.alreadyLatest?(c("done"),m(`Already on v${N.version||"latest"}.`)):N.upgraded||N.success?(c("done"),m(`Upgrade to v${N.version||"latest"} started. Daemon is restarting...`)):(c("error"),m(N.error||"Upgrade failed"))}catch(N){c("error"),m(pn(N,"Connection lost during upgrade"))}}},g=async()=>{if(u(null),!!n){w("loading");try{await n(e.id),w("done"),M("Machine disconnected.")}catch(N){w("error"),M(pn(N,"Failed to disconnect"))}}},x=async()=>{if(u(null),!!a){w("loading");try{await a(e.id),w("done"),M("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(N){w("error"),M(pn(N,"Failed to revoke token"))}}},B="0.8.71",A=Ri(e,B),T=Vs(e,B),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${B}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${T?"↑ Update now":`↑ Update${` to v${B}`}`}`}),n&&t.jsx("button",{onClick:()=>u("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>u("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(zu,{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=Zu(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(so,{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:()=>u(null)}),p==="revoke"&&t.jsx(so,{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:()=>u(null)})]})}const tm=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function sm(){const{preference:e,setPreference:s}=pa();return t.jsx("div",{className:"flex gap-2",children:tm.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 rm(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 nm(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function fn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function ro(e){const{r:s,g:r,b:n}=nm(e);return .2126*fn(s)+.7152*fn(r)+.0722*fn(n)}function no(e,s){const r=ro(e),n=ro(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Pi(e){const s=rm(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return no(s,r)>=no(s,n)?r:n}const Kn={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},Wn={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},am=[{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"}}}],Di="adhdev-chat-theme",Ei="adhdev-chat-theme-custom";function Ir(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Di)||"ember"}catch{return"ember"}}function Et(e){try{const s=localStorage.getItem(Ei);if(s){const r=JSON.parse(s);return{...e==="dark"?Kn:Wn,...r[e]}}}catch{}return e==="dark"?Kn:Wn}function fr(e,s){try{localStorage.setItem(Ei,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 Br(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 om={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function Gs(e,s){var a;const r=(a=om[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",Br(r,24)),n.style.setProperty("--accent-on-primary",Pi(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Br(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 as(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",Br(e.accentColor,30)),s.style.setProperty("--accent-on-primary",Pi(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Br(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 fa(){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 im(e){try{localStorage.setItem(Di,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=os()?"dark":"light";as(Et(s))}else fa(),Gs(e,os()?"dark":"light")}function cm(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Ir();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=os()?"dark":"light";as(Et(s))}else fa(),Gs(e,os()?"dark":"light")}function os(){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 Bs({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function lm({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Et(r));o.useEffect(()=>{a(Et(r))},[r]);const i=o.useCallback((c,l)=>{a(m=>{const p={...m,[c]:l},f=Et(r==="dark"?"light":"dark");return r==="dark"?fr(p,f):fr(f,p),as(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(Bs,{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(Bs,{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(Bs,{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(Bs,{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(Bs,{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?Kn:Wn,m=Et(e?"light":"dark");e?fr(c,m):fr(m,c),a(c),as(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 dm(){const[e,s]=o.useState(Ir),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Et("dark"));o.useEffect(()=>{n(os());const m=new MutationObserver(()=>{const f=os();n(f);const w=Ir();w==="custom"?as(Et(f?"dark":"light")):Gs(w,f?"dark":"light")});m.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const p=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const f=os();n(f);const w=Ir();w==="custom"?as(Et(f?"dark":"light")):Gs(w,f?"dark":"light")};return p.addEventListener("change",u),()=>{m.disconnect(),p.removeEventListener("change",u)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?as(Et(r?"dark":"light")):(fa(),Gs(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Et(r?"dark":"light"))},[r]);const c=m=>{s(m),im(m)},l=[...am,{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(m=>{const p=e===m.id,u=r?m.preview.dark:m.preview.light,f=m.id==="honey"||m.id==="ember"?"#1a1a1a":m.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(m.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:u.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:f},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[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:m.id==="custom"?"🎨 Custom":m.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:m.description})]})]})]},m.id)})}),e==="custom"&&t.jsx(lm,{dark:r,onColorsChange:m=>i(m)})]})}const $i="adhdev_mobileDashboardMode_v1";function Bi(){try{return localStorage.getItem($i)==="workspace"?"workspace":"chat"}catch{return"chat"}}function um(e){try{localStorage.setItem($i,e)}catch{}}function mm(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(Bi()==="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),um(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}function pm(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 fm(e,s){const{sendData:r}=Mt(),{injectEntries:n,getIdes:a}=_r(),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(m=>Gt.subscribe({sendData:r},m,{type:"subscribe",topic:"machine.runtime",key:`machine:${m}`,params:{intervalMs:s==null?void 0:s.intervalMs}},p=>{const u=a().find(w=>w.id===m),f=pm(u,m,p);n([f])}));return()=>{l.forEach(m=>m())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}const hm=4e3;function Ki(e,s){const{sendData:r}=Mt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const m=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 m.initialSendAccepted?l=setTimeout(()=>{c(!1)},hm):c(!1),()=>{l&&clearTimeout(l),m()}},[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 xm(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Wi(e){const{sendData:s}=Mt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=xm(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}),Ss.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return()=>{i()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const Oi="adhdev_hiddenTabs";function bm(){try{const e=localStorage.getItem(Oi);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function xs(e){try{localStorage.setItem(Oi,JSON.stringify([...e]))}catch{}}function gm(){const[e,s]=o.useState(bm),r=o.useCallback(p=>{s(u=>{const f=new Set(u);return f.has(p)?f.delete(p):f.add(p),xs(f),f})},[]),n=o.useCallback(p=>{s(u=>{if(u.has(p))return u;const f=new Set(u);return f.add(p),xs(f),f})},[]),a=o.useCallback(p=>{s(u=>{if(!u.has(p))return u;const f=new Set(u);return f.delete(p),xs(f),f})},[]),i=o.useCallback(()=>{s(p=>{if(p.size===0)return p;const u=new Set;return xs(u),u})},[]),c=o.useCallback((p,u)=>{s(f=>{const w=new Set(f);for(const S of u)w.add(S);return xs(w),w})},[]),l=o.useCallback((p,u)=>{s(f=>{const w=new Set(f);for(const S of u)w.delete(S);return xs(w),w})},[]),m=o.useCallback(p=>e.has(p),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:m}}function ao(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 ym(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=ao(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(m=>ao(m,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function Hi(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 vm(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))Hi(s,a)===i&&(delete n[a],r=!0);return r?n:e}function wm({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{ud()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:yi(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return pd(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const m=Date.now(),p={};for(const[u,f]of Object.entries(l))m-f<5e3&&(p[u]=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 m=l.filter(p=>p.timestamp>c).slice(-100);return m.length===l.length?l:m})},6e4);return()=>clearInterval(i)},[n]),null}function jm(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 is(e){const s=[...e.messages].reverse().find(r=>!(r!=null&&r._localId))||e.messages[e.messages.length-1];return e.lastMessageAt||jm(s==null?void 0:s.receivedAt)||0}function On(e,s=0){return is(e)||e.lastUpdated||s||0}function Ui(e){return is(e)||e.lastUpdated||0}function Fi(e,s,r=Ui){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 Hn(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 km(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!Hn(e)&&!e.title.trim()}function Sm(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(Hn(r))-Number(Hn(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Fi(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=Sm(a);return n?i&&km(n)?i:n:i||r[0]||null}function Nm(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 hn(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 Cm(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 oo(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?Cm(Cs(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 Im(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||""),oo(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),oo(r.activeChat)].join(":"))].join("|")}function Am(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 Mm(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 Lm(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function _m(e){const s=Lm(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=Cs(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Rm({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>Nm(e),[e]),c=o.useMemo(()=>Ni(e),[e]),l=o.useRef([]),m=o.useRef([]),p=o.useRef([]),u=o.useRef(new Map),f=o.useRef(new Map),w=o.useMemo(()=>{const v=new Map,j=[];for(const B of i){const{connectionState:A="new",machineName:T}=Ci(B,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),L=Mm(B,r),O=Im(B),R=u.current.get(B.id);if(R&&R.ide===B&&R.sourceSignature===O&&R.connectionState===A&&R.machineName===T&&Tm(R.localRefs,L)){v.set(B.id,R),j.push(...R.conversations);continue}const N=ma(B,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),U={ide:B,sourceSignature:O,connectionState:A,machineName:T,localRefs:L,conversations:N};v.set(B.id,U),j.push(...N)}u.current=v;const k=new Map,g=B=>{const A=_m(B),T=f.current.get(B.tabKey);if(T&&T.signature===A)return k.set(B.tabKey,T),T.timestamp;const L={signature:A,timestamp:Ui(B)||(T==null?void 0:T.timestamp)||0};return k.set(B.tabKey,L),L.timestamp},x=[...j].sort((B,A)=>Fi(B,A,g));return f.current=k,x},[i,r,s,c]),S=o.useMemo(()=>{const v=Am(w,n);return hn(l.current,v)?l.current:(l.current=v,v)},[w,n]),M=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=M.get(j.routeId);k&&v.set(j.sessionId,k)}return v},[S,M]),b=o.useMemo(()=>{const v=new Map;for(const j of S)j.sessionId&&v.set(j.sessionId,j),v.set(j.routeId,M.get(j.routeId)||j),v.set(j.tabKey,j);return v},[S,M]),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 hn(m.current,v)?m.current:(m.current=v,v)},[S,a]),P=o.useMemo(()=>{const v=C.map(j=>j.tabKey);return hn(p.current,v)?p.current:(p.current=v,v)},[C]);return{chatIdes:i,conversations:S,visibleConversations:C,visibleTabKeys:P,resolveConversationBySessionId:y,resolveConversationByTarget:h}}function Pm({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 m=new URLSearchParams(l);return m.delete("activeTab"),m},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Dm({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(m=>{r(u=>u.some(w=>w.message===m.message&&m.timestamp-w.timestamp<3e3)?u:[...u.slice(-4),{id:m.id,message:m.message,type:m.type,timestamp:m.timestamp,targetKey:m.targetKey,actions:m.actions}]);const p=m.duration||5e3;setTimeout(()=>r(u=>u.filter(f=>f.id!==m.id)),p)}),c=ot.onSystemMessage((m,p)=>{var S,M;const u=a(m),f=(S=p._localId)==null?void 0:S.startsWith("sys_approval_"),w=!!(u&&(u.status==="waiting_approval"||(M=u.modalButtons)!=null&&M.length||u.modalMessage));f&&w||n(d=>({...d,[m]:[...d[m]||[],p]}))}),l=ot.onClearSystemMessage((m,p)=>{n(u=>{var f;return(f=u[m])!=null&&f.length?{...u,[m]:u[m].filter(w=>{var S;return!(w.role==="system"&&((S=w._localId)!=null&&S.startsWith(p)))})}:u})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=xi.on("status_event",c=>{ot.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var b;const m=l.data;if((m==null?void 0:m.type)!=="notification_action"||typeof m.action!="string"||!m.action.startsWith("approval_")||!(m.daemonId||m.targetSessionId||m.targetKey))return;const p=m.targetSessionId||m.targetKey||m.daemonId,u=a(p),f=(u==null?void 0:u.routeId)||m.daemonId;if(!f)return;const w=Number(m.buttonIndex),S=m.button||((b=u==null?void 0:u.modalButtons)==null?void 0:b[w])||"Approve",M=String(S).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),d=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(M);s(f,"resolve_action",{action:d?"approve":"reject",button:S,...Number.isFinite(w)&&{buttonIndex:w},...(u==null?void 0:u.sessionId)&&{targetSessionId:u.sessionId},...m.targetSessionId&&{targetSessionId:m.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 Em="adhdev_dashboardLayout_v1",$m="adhdev_dashboardDockview_v1",Bm="adhdev_dashboardDockviewHiddenRestore_v1",Ks={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function ha(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function zi(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Vi(e){return`${Em}:${e}`}function Km(e){const s=Vi(e);return ha(s,null)}function Wm(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=Vi(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Gi(e){return`${$m}:${e}`}function Om(e){const s=Gi(e);return ha(s,null)}function Hm(e,s){try{const r=Gi(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function qi(e){return`${Bm}:${e}`}function Um(e){const s=qi(e);return ha(s,{})}function Fm(e,s){try{const r=qi(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function zm(){return{groupAssignments:[...Ks.groupAssignments],focusedGroup:Ks.focusedGroup,groupActiveTabIds:{...Ks.groupActiveTabIds},groupTabOrders:{...Ks.groupTabOrders},groupSizes:[...Ks.groupSizes]}}function Vm(){const[e]=o.useState(()=>zi(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,m]=o.useState({}),[p,u]=o.useState([]),[f,w]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[S,M]=o.useState(!1),d=o.useCallback(()=>{if(S)return;const b=Km(e)??zm();r(new Map(b.groupAssignments)),a(b.focusedGroup),c(b.groupActiveTabIds),m(b.groupTabOrders),u(b.groupSizes),M(!0)},[S,e]);return o.useEffect(()=>{S&&Wm(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:m,groupSizes:p,setGroupSizes:u,isMobile:f,hasHydratedStoredLayout:S,hydrateStoredLayout:d}}function Gm(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 qm({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:m,historyModalOpen:p,activeConv:u,isRefreshingHistory:f,ides:w,handleRefreshHistory:S}){const M=o.useRef(!1),d=o.useRef(!1),b=o.useRef(null),y=o.useRef(!1);o.useEffect(()=>{if(!e||M.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),M.current=!0,d.current=!0,b.current!=null&&(window.clearTimeout(b.current),b.current=null),m(P=>{const v=new URLSearchParams(P);return v.delete("activeTab"),v},{replace:!0})},[e,s,r,n,a,i,c,l,m]),o.useEffect(()=>{if(!(d.current||a)&&s.length!==0){if(!e){i(),d.current=!0;return}if(M.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(!u||y.current||f)return;const h=w.find(C=>C.id===u.routeId);h&&(!h.chats||h.chats.length===0||Gm(h.chats,u))&&(y.current=!0,S())},[p,u,f,w,S]),o.useEffect(()=>{if(!u)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)}},[u==null?void 0:u.tabKey])}function Ym({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[m,p]=o.useState(null),[u,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=m==null?void 0:m.routeId;if(!y)return null;const h=m!=null&&m.tabKey?i.find(C=>C.tabKey===m.tabKey):a?i.find(C=>C.tabKey===a):null;return(h==null?void 0:h.routeId)===y?h:Bt(i,y)},[i,m,a]),M=o.useMemo(()=>{if(S)return c.find(y=>y.id===S.routeId)},[c,S]);o.useEffect(()=>{w&&(p({routeId:w.routeId,tabKey:za(w)}),f(w),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,w]);const d=o.useCallback(y=>{y&&(p({routeId:y.routeId,tabKey:za(y)}),f(y))},[]),b=o.useCallback(()=>{p(null),f(null)},[]);return{remoteDialogConv:S,remoteDialogIdeEntry:M,remoteDialogActiveConv:u,setRemoteDialogActiveConv:f,openRemoteDialog:d,closeRemoteDialog:b}}function js(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 Ws(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function xn(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 io({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,m]=o.useState(!1),[p,u]=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,...js(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"?Ws(a,"⚠️ Session tab not found — try refreshing history"):typeof C=="string"&&C.startsWith("error:")?Ws(a,`⚠️ Switch error: ${C}`):Ws(a,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),Ws(a,`❌ Switch failed: ${y.message||"connection error"}`)}},[s,e,a]),S=o.useCallback(async()=>{if(!(!s||l)){m(!0);try{const d=Js(s);await e(d,"new_chat",{...js(s)}),c(b=>({...b,[s.tabKey]:Date.now()})),i(b=>({...b,[s.tabKey]:[]}))}catch(d){console.error("New chat failed",d)}finally{m(!1)}}},[s,l,e,c,i]),M=o.useCallback(async()=>{var d,b;if(!(!s||p)){u(!0);try{const y=Js(s),h=async()=>e(y,"list_chats",{forceExpand:!0,...js(s)});let C=await h(),P=(C==null?void 0:C.chats)||((d=C==null?void 0:C.result)==null?void 0:d.chats);xn(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),xn(P,s)&&!xn(r,s)&&Ws(a,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{u(!1)}}},[s,r,p,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:p,handleLaunchIde:f,handleSwitchSession:w,handleNewChat:S,handleRefreshHistory:M}}function Xm(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 Qm(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function co(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(a=>s[Number(a)]===e[Number(a)])}function hr(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const m=a[l];typeof m=="number"&&m>0&&i.set(c,m)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function lo(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 Jm(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 Zm(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 uo(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 mo(e){return Array(e).fill(100/e)}function ep({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:m,visibleTabKeys:p}){const u=o.useRef(null),f=o.useMemo(()=>hr(e,p),[e,p]),w=f.assignments,S=o.useMemo(()=>l?1:f.groupCount,[f.groupCount,l]),M=S>1,d=o.useCallback((v,j)=>{s(k=>{const g=new Map(hr(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=hr(j,p).assignments,g=new Map;for(const[x,B]of k)B!==v&&(B>v?g.set(x,B-1):g.set(x,B));return g}),c(j=>{if(j.length<=1)return[];const k=[...j];k.splice(v,1);const g=k.reduce((x,B)=>x+B,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=u.current;if(!k)return;const g=j.clientX,x=k.offsetWidth,B=i.length===S?[...i]:mo(S),A=L=>{const R=(L.clientX-g)/x*100,N=[...B];N[v]=Math.max(15,B[v]+R),N[v+1]=Math.max(15,B[v+1]-R),c(N)},T=()=>{document.removeEventListener("mousemove",A),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",A),document.addEventListener("mouseup",T)},[i,S,c]),h=o.useCallback((v,j,k)=>{if(S>=4)return;const g=k==="left"?j:j+1;s(x=>{const B=hr(x,p).assignments,A=new Map;for(const T of m){const L=B.get(T.tabKey)??0,O=L>=g?L+1:L;O>0&&A.set(T.tabKey,O)}return g>0&&A.set(v,g),A}),c(x=>{const B=x.length===S?[...x]:mo(S),A=B[j]??100/S,T=Math.max(15,A/2),L=Math.max(15,A/2),O=[...B];O[j]=T,O.splice(g,0,L);const R=O.reduce((N,U)=>N+U,0);return O.map(N=>N/R*100)}),n(x=>{const B=uo(x,g);return B[g]=v,B}),a(x=>{const B=uo(x,g);return B[g]=[v],B}),r(g)},[S,s,p,m,c,n,a,r]);o.useEffect(()=>{Xm(e,w)||s(w)},[e,w,s]),o.useEffect(()=>{const{mapping:v,usedGroups:j}=f;n(k=>{const g=lo(k,v);return co(k,g)?k:g}),a(k=>{const g=lo(k,v);return co(k,g)?k:g}),r(k=>{const g=l?0:Jm(k,j,v);return k===g?k:g}),c(k=>{const g=l?[]:Zm(k,j,f.groupCount);return Qm(k,g)?k:g})},[f,l,n,a,r,c]);const C=o.useMemo(()=>{const v=Array.from({length:S},()=>[]);for(const j of m){const k=w.get(j.tabKey)??0,g=Math.min(k,S-1);v[g].push(j)}return v},[m,w,S]),P=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:u,normalizedGroupAssignments:w,numGroups:S,isSplitMode:M,groupedConvs:C,moveTabToGroup:d,closeGroup:b,handleResizeStart:y,splitTabRelative:h,clearAllSplits:P}}function tp({ides:e,sendDaemonCommand:s}){const r="0.8.71",n=o.useMemo(()=>e.filter(u=>u.type!=="adhdev-daemon"?!1:Ri(u,r)).sort((u,f)=>Number(Vs(f,r))-Number(Vs(u,r))),[r,e]),a=o.useMemo(()=>n.some(u=>Vs(u,r)),[r,n]),[i,c]=o.useState(!1),[l,m]=o.useState({}),p=o.useCallback(async u=>{var f,w;m(S=>({...S,[u]:"upgrading"}));try{const S=await s(u,"daemon_upgrade",{});(f=S==null?void 0:S.result)!=null&&f.upgraded||(w=S==null?void 0:S.result)!=null&&w.success?m(M=>({...M,[u]:"done"})):m(M=>({...M,[u]:"error"}))}catch{m(S=>({...S,[u]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:p}}const Un="adhdev_dashboard_notifications_v1",xa=80;function Ar(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Kr(e){return{...e,createdAt:Ar(e.createdAt),updatedAt:Ar(e.updatedAt,e.createdAt),lastEventAt:Ar(e.lastEventAt,e.updatedAt||e.createdAt)}}function sp(e){return e.providerSessionId||e.sessionId||e.tabKey||e.id}function rp(e){return[e.type,e.providerSessionId||e.sessionId||e.tabKey||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function np(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 m=Ar(a.lastMessageAt||(i==null?void 0:i.lastUpdated)||a.lastUpdated,r),p=rp({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(Kr({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:m,updatedAt:m,lastEventAt:m}))}return n.sort((a,i)=>i.updatedAt-a.updatedAt)}function ap(e,s,r=xa){const n=new Map;for(const i of e)i.deletedAt||n.set(i.id,Kr(i));for(const i of s){const c=Kr(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=sp(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 op(e,s,r=Date.now()){return e.map(n=>n.id===s?{...n,readAt:r,updatedAt:Math.max(n.updatedAt,r)}:n)}function ip(e,s){return e.map(r=>{if(r.id!==s)return r;const n={...r};return delete n.readAt,n})}function cp(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 lp(e,s){return e.filter(r=>r.id!==s)}function dp(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function up(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 mp(){if(typeof window>"u")return[];try{const e=window.localStorage.getItem(Un),s=e?JSON.parse(e):[];return Array.isArray(s)?s.map(r=>Kr(r)).filter(r=>!r.deletedAt):[]}catch{return[]}}function pp(e){if(!(typeof window>"u"))try{const s=e.filter(r=>!r.deletedAt).slice(0,xa);if(s.length===0){window.localStorage.removeItem(Un);return}window.localStorage.setItem(Un,JSON.stringify(s))}catch{}}function fp(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 hp(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=xa}=e,a=o.useMemo(()=>np(s,r),[s,r]),[i,c]=o.useState(()=>mp());o.useEffect(()=>{c(S=>{const M=ap(S,a,n);return fp(S,M)?S:M})},[a,n]),o.useEffect(()=>{pp(i)},[i]);const l=o.useMemo(()=>dp(i),[i]),m=o.useMemo(()=>up(i),[i]),p=o.useCallback((S,M)=>{c(d=>op(d,S,M))},[]),u=o.useCallback(S=>{c(M=>ip(M,S))},[]),f=o.useCallback((S,M)=>{c(d=>cp(d,S,M))},[]),w=o.useCallback(S=>{c(M=>lp(M,S))},[]);return{notifications:i,unreadCount:l,notificationStateBySessionId:m,markRead:p,markUnread:u,markTargetRead:f,deleteNotification:w}}function Yi(){return"select_session"}function xp(){return"open_panel"}function bp(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function gp(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function po(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function ba(e){return e instanceof Error?e.message:String(e||"")}function fo(e){const s=ba(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function ho(e,s){const r=ba(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function qr({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,m]=o.useState(!1),p=o.useRef(!1),u=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(bp(u.current,h))return;p.current=!0,m(!0),u.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,...js(s)}),g=po(k);if(v&&(g!=null&&g.deduplicated||(g==null?void 0:g.sent)===!1)){r(x=>({...x,[h.tabKey]:(x[h.tabKey]||[]).filter(B=>B._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(B=>{const A=B[h.tabKey];if(!A)return B;const T=A.filter(L=>L.timestamp>x);return T.length===A.length?B:{...B,[h.tabKey]:T}})},6e4)}catch(j){const k=ba(j);k.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",k):console.error("Send failed",j),u.current=gp(u.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,m(!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},...js(s)}),j=po(v);j.success||n(k=>[...k,{routeId:s.tabKey,text:ho(d,j==null?void 0:j.error),timestamp:Date.now()}])}catch(b){fo(b)||console.error("[ModalButton] Error:",b),n(y=>[...y,{routeId:s.tabKey,text:fo(b)?ho(d,b):`❌ **${d}** error`,timestamp:Date.now()}])}},[s,e,n]),M=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,xp(),{...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:M}}const ga=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:m,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:f,actionLogs:w,userName:S,scrollToBottomRequestNonce:M,isInputActive:d=!0}){const b=Wi(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(Jo,{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(ds,{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(fu,{activeConv:y,clearToken:r,terminalRef:i,handleSendChat:m,isSendingChat:p,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx($n,{activeConv:y,ideEntry:a,handleSendChat:m,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:f,actionLogs:w,userName:S,scrollToBottomRequestNonce:M,isInputActive:d})})]}):t.jsx($n,{activeConv:y,ideEntry:a,handleSendChat:m,isSendingChat:p,handleFocusAgent:u,isFocusingAgent:f,actionLogs:w,userName:S,scrollToBottomRequestNonce:M,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 yp({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,isFocusingAgent:l,onBack:m,onOpenNativeConversation:p,onOpenMachine:u,onOpenHistory:f,onOpenRemote:w,onHideConversation:S,onStopCli:M,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:m,type:"button","aria-label":"Back",children:t.jsx(Yn,{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(li,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>p(e),onOpenMachine:()=>u(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&d&&t.jsx(oa,{mode:d,onChange:b,compact:!0}),j&&M&&t.jsx("button",{onClick:()=>{M(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(Qn,{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(ga,{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 bn={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 vp(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Xi(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(vp())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(bn[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:bn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:bn[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 Qi({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 xr({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 bs({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 Os({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 br({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:m,isConnecting:p}=Ps(e.conversation),u=it(e.conversation),f=ps(e.conversation),w=gi(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",M=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 ${M}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(u)}),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:u}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${h}`,children:Qo(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${b}`,children:[f,m?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 xo({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 wp({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:m,onShowConversation:p,onShowAllHidden:u,onOpenNewSession:f,onOpenMachine:w,onOpenSettings:S,onSectionChange:M,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(Fr,{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(Hr,{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(Os,{icon:t.jsx(xo,{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(Os,{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(Xi,{})})}):t.jsx(bs,{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(xr,{title:"Needs attention",className:"mb-0"}),t.jsx(bs,{children:s.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(br,{item:k,type:"needs_attention",getAvatarText:l,onOpenConversation:m})},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(xr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(bs,{children:r.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(br,{item:k,type:"task_complete",getAvatarText:l,onOpenConversation:m})},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(xr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(bs,{children:n.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(br,{item:k,type:"working",getAvatarText:l,onOpenConversation:m})},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(xr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(bs,{children:a.map((k,g)=>t.jsx("div",{className:g>0?"border-t border-border-subtle/70":"",children:t.jsx(br,{item:k,type:"earlier",getAvatarText:l,onOpenConversation:m})},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(Os,{icon:t.jsx(xo,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(Os,{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(Os,{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:u,children:"Restore all"})]}),t.jsx(bs,{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:ps(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(Qi,{section:e,onSectionChange:M})]})}function jp(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 Ji(e){const s=[e.workspace||"Workspace unknown"],r=us(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=jp(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Yr(...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 kp(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 Xr(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=kp(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 Sp(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 Np(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Qr(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=Np(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,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${c}${u}`:`${p.replace(/[\\/]+$/,"")}${c}${u}`,m=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,u)=>p.name.localeCompare(u.name)):[];return{path:i,directories:m}}function Jr({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:m,onConfirm:p}){const[u,f]=o.useState(r);o.useEffect(()=>{f(r)},[r]);const w=Sp(r),S=u.trim();return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:t.jsx(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||m(w)},disabled:!w||a,children:[t.jsx(Yn,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:u,onChange:M=>f(M.target.value),onKeyDown:M=>{M.key!=="Enter"||!S||a||(M.preventDefault(),m(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||m(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(M=>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:()=>m(M.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(Ns,{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:M.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:M.path})]})]},M.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 ya({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:m=!1,showArgsInput:p,argsValue:u,onArgsChange:f,showModelInput:w,modelValue:S,onModelChange:M,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:m,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&&M&&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=>M(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:m})]}),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:u||"",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:m})]})]}),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:m,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:m,children:[t.jsx(Jn,{size:14}),m?l:c]})]})]})})}function bo(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function cs(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const m of s.workspaces||[])i.push({key:`saved:${m.id}`,label:`${m.id===s.defaultWorkspaceId?"⭐ ":""}${bo(m.path,m.label)}`,description:m.path,workspaceId:m.id,workspacePath:m.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(m=>m.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:bo(c),description:c,workspaceId:null,workspacePath:c}),n){const m=`saved:${n}`;if(i.some(p=>p.key===m))return{options:i,selectedKey:m}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Cp(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Ip(e){return[Cp(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Ap(e){return e.lastLaunchedAt?zr(e.lastLaunchedAt):""}function Zi(e){return{metaText:Ip(e),updatedLabel:Ap(e)}}function gn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function Mp({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var mt,tt,xt,pt;const c=tr(),[l,m]=o.useState(!1),p=(((mt=e.detectedIdes)==null?void 0:mt.length)||0)>0,u=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=u[0])==null?void 0:tt.id)||""),[M,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),[B,A]=o.useState(gn(p,s.length,r.length)),T=o.useRef(null),[L,O]=o.useState(null),R=o.useRef("__home__"),[N,U]=o.useState("__home__"),[G,I]=o.useState(""),[D,E]=o.useState(""),[W,X]=o.useState(""),[we,Le]=o.useState([]),[ie,Ie]=o.useState(()=>gt().textQuery),[te,de]=o.useState(()=>gt().workspaceQuery),[ae,xe]=o.useState(()=>gt().modelQuery),[oe,F]=o.useState(()=>gt().resumableOnly),[be,se]=o.useState(()=>gt().sortMode),[pe,Z]=o.useState(!1),[le,ne]=o.useState(!1),ge=o.useRef(null),me=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const $=w==="__custom__"?M.trim():((xt=u.find(ce=>ce.id===w))==null?void 0:xt.path)||"",ye=w==="__custom__"&&!!$&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),he=w!=="__custom__"&&((pt=u.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=Xr(e.platform,Yr(M.trim(),he,ke,e.defaultWorkspacePath,(Ve=u.find(ct=>ct.id===f))==null?void 0:Ve.path,u.map(ct=>ct.path)));J(ce)},[M,f,J,ke,he,e.platform,u]),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)=>{T.current=Ve,R.current=ce.selectedWorkspaceKey||"__home__",U(ce.selectedWorkspaceKey||"__home__"),I(ce.initialArgs||""),E(ce.initialModel||""),X(""),Le([]);const ct=ce.providerType?`${e.id}:${ce.providerType}`:null;if(gu(me.current,ct)){const Je=gt();Ie(Je.textQuery),de(Je.workspaceQuery),xe(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(()=>wi(we,{textQuery:ie,workspaceQuery:te,modelQuery:ae,resumableOnly:oe,sortMode:be}),[ae,oe,we,be,ie,te]);o.useEffect(()=>{W&&(Ze.some(ce=>ce.providerSessionId===W)||X(""))},[Ze,W]);const ut=o.useCallback(()=>{T.current&&(ne(!0),T.current().finally(()=>{T.current=null,ne(!1),O(null)}))},[]),qe=o.useCallback(()=>{T.current=null,O(null)},[]),ht=o.useCallback(ce=>{R.current=ce,U(ce)},[]);return o.useEffect(()=>{var ce;ge.current!==e.id&&(ge.current=e.id,S(f||((ce=u[0])==null?void 0:ce.id)||"__custom__"),d(""),y(""),C([]),k(""),x(!1),Ie(gt().textQuery),de(gt().workspaceQuery),xe(gt().modelQuery),F(gt().resumableOnly),se(gt().sortMode),me.current=null,A(gn(p,s.length,r.length)))},[r.length,s.length,f,p,e.id,u]),o.useEffect(()=>{var ce;w!=="__custom__"&&(w&&u.some(Ve=>Ve.id===w)||S(f||((ce=u[0])==null?void 0:ce.id)||"__custom__"))},[f,w,u]),o.useEffect(()=>{B==="ide"&&p||B==="cli"&&s.length>0||B==="acp"&&r.length>0||A(gn(p,s.length,r.length))},[B,r.length,s.length,p]),{showAllRecent:l,setShowAllRecent:m,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:f,workspaceChoice:w,customWorkspacePath:M,browseCurrentPath:b,browseDirectories:h,browseBusy:P,browseError:j,browseDialogOpen:g,activeLauncherKind:B,launchConfirm:L,launchConfirmWorkspaceKeyRef:R,launchConfirmWorkspaceKey:N,launchConfirmArgs:G,launchConfirmModel:D,launchConfirmResumeId:W,launchConfirmSavedSessions:we,launchConfirmTextFilter:ie,launchConfirmWorkspaceFilter:te,launchConfirmModelFilter:ae,launchConfirmResumableOnly:oe,launchConfirmSortMode:be,filteredLaunchConfirmSavedSessions:Ze,launchConfirmSessionsLoading:pe,launchConfirmBusy:le,resolvedWorkspacePath:$,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:E,setLaunchConfirmResumeId:X,setLaunchConfirmTextFilter:Ie,setLaunchConfirmWorkspaceFilter:de,setLaunchConfirmModelFilter:xe,setLaunchConfirmResumableOnly:F,setLaunchConfirmSortMode:se}}function Tp({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:m,section:p,showBottomNav:u,onBack:f,onSectionChange:w,onOpenConversation:S,onOpenRecent:M,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=Mp({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:C,onListSavedSessions:v}),B=o.useMemo(()=>k.map(N=>{const{metaText:U,updatedLabel:G}=Zi(N);return{key:`recent-launch:${N.id}`,primary:N.label,secondary:U,updatedLabel:G,onClick:()=>{const{options:I,selectedKey:D}=cs({machine:{workspaces:x.workspaceRows,defaultWorkspaceId:x.defaultWorkspaceId},currentWorkspacePath:N.workspace});x.openLaunchConfirm({title:N.kind==="ide"?rs("restart-ide",N.label):N.providerSessionId?la(N.label):rs("start-fresh",N.label),description:N.kind==="ide"?ns("restart-ide"):N.providerSessionId?da():ns("start-fresh"),confirmLabel:N.kind==="ide"?Ts("restart-ide"):N.providerSessionId?Er(!0):Ts("start-fresh"),busyLabel:N.kind==="ide"?Ls("restart-ide"):N.providerSessionId?ia(!0):Ls("start-fresh"),workspaceOptions:I,selectedWorkspaceKey:D,details:[{label:"Mode",value:j(N.kind)},...N.providerType?[{label:"Provider",value:N.providerType}]:[]]},async()=>{const E=I.find(W=>W.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(E),await M({...N,workspace:(E==null?void 0:E.workspacePath)??null})})}}}),[x,M,k]),A=o.useMemo(()=>g.map(N=>({key:`recent-chat:${N.conversation.tabKey}`,primary:it(N.conversation),secondary:du(N.conversation,{timestampLabel:N.timestamp?Qo(N.timestamp):null}),unread:N.unread,onClick:()=>S(N.conversation)})),[S,g]),T=x.showAllRecent?B:B.slice(0,4),L=B.length>0,O=A.length>0,R=m?"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(Yn,{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:T.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))}),B.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 ${B.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?"⭐ ":"",Gr(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(Ns,{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}=cs({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(D=>D.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}=cs({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 D=G.find(E=>E.key===x.launchConfirmWorkspaceKeyRef.current);x.setWorkspaceSelectionFromOption(D),P(U,N.type,{workspaceId:(D==null?void 0:D.workspaceId)??null,workspacePath:(D==null?void 0:D.workspacePath)??null,args:x.launchConfirmArgs,model:x.launchConfirmModel,resumeSessionId:x.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[N.icon?`${N.icon} `:"",N.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:x.resolvedWorkspacePath||"Use selected workspace"})]},N.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,x.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>h(x.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[i&&t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:b,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",c]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:d,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),x.browseDialogOpen&&t.jsx(Jr,{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(ya,{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?Er(!!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:ca()}),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:wu()}),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=Ji(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}),u&&t.jsx(Qi,{section:p,onSectionChange:w})]})}function ec(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 Lp(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:us(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,m,p,u;const a=Qs(n)?"cli":ws(n)?"acp":"ide",i=us(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(Qs(n)?n.cliName||n.type:ws(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:ws(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((u=(p=(m=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:m.at)==null?void 0:p.call(m,-1))==null?void 0:u.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function _p(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=Rn(n),m=a.filter(f=>f.unread||f.requiresAction).length,p=ec(n),u=[n.platform||"machine",p].filter(Boolean);return{id:n.id,label:It(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:m,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?uu(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 gr(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 Rp({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:m,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:w,onRequestedMobileSectionConsumed:S,setSelectedTabKey:M,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=Rr(k,c),x=Math.max(Date.now(),is(k),g.lastUpdated||0);gr("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:is(k),readAt:x}),P({sessionId:k.sessionId,tabKey:k.tabKey}),l(qt(k)||k.routeId,"mark_session_seen",{sessionId:k.sessionId,seenAt:x}).then(B=>{gr("mark_read:result",{tabKey:k.tabKey,sessionId:k.sessionId,result:B})}).catch(B=>{gr("mark_read:error",{tabKey:k.tabKey,sessionId:k.sessionId,error:B instanceof Error?B.message:String(B)})})},[c,l]);return o.useEffect(()=>{var g;if(!n){d("inbox"),M(((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,M]),o.useEffect(()=>{if(!m)return;const k=e.find(g=>g.tabKey===m);k&&(M(k.tabKey),d("chat"),p==null||p())},[e,p,m,d,M]),o.useEffect(()=>{if(!u)return;const k=s.find(g=>g.id===u);k&&(b(k.id),C(),y("machines"),h("inbox"),d("machine"),f==null||f())},[s,f,u,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&&gr("inbox_state",{screen:i,selectedTabKey:a,items:k.map(g=>{const x=Rr(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:is(g.conversation)}})})},[r,c,i,a]),{markConversationRead:j}}function Pp(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function go(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Dp(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Ep({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[m,p]=o.useState(null),u=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]),M=o.useCallback(async(h,C,P,v)=>{var g,x,B;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)),(B=v==null?void 0:v.model)!=null&&B.trim()&&(A.initialModel=v.model.trim());const T=await e(h,"launch_cli",A),L=(T==null?void 0:T.result)||T,O=(L==null?void 0:L.sessionId)||(L==null?void 0:L.id);if(T!=null&&T.success&&O){p(null),i("done"),l(`${P} launched`),s(`/dashboard?activeTab=${encodeURIComponent(O)}`);return}if(T!=null&&T.success){i("loading"),l(`${P} launch requested — waiting for session…`);return}p(null),i("error"),l((T==null?void 0:T.error)||(L==null?void 0:L.error)||`Could not launch ${C.toUpperCase()} workspace`)}catch(A){if(Dp(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)=>Qr(e,h,C),[e]);o.useEffect(()=>{var v;if(!m)return;const h=go(m.workspacePath),C=r.find(j=>{var T,L,O,R;if(!j||j.type==="adhdev-daemon"||Pp(j.daemonId||j.id)!==m.machineId||(j.transport==="acp"?"acp":j.transport==="pty"?"cli":null)!==m.kind||String(j.agentType||j.type||"")!==m.providerType)return!1;const B=String(j.providerSessionId||"");if(m.resumeSessionId&&B)return B===m.resumeSessionId;if(h){const N=go(j.workspace||j.runtimeWorkspaceLabel);return N?N===h:!1}return Number(j.lastUpdated||j._lastUpdate||j.timestamp||((R=(O=(L=(T=j.activeChat)==null?void 0:T.messages)==null?void 0:L.at)==null?void 0:O.call(L,-1))==null?void 0:R.timestamp)||0)>=m.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(`${m.providerType} launched`),s(`/dashboard?activeTab=${encodeURIComponent(P)}`))},[n,r,s,m]),o.useEffect(()=>{if(!m)return;const h=window.setTimeout(()=>{p(C=>!C||C.startedAt!==m.startedAt?C:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[m]);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 M(h,C.kind,C.providerType,{workspacePath:C.workspace||null,resumeSessionId:C.providerSessionId||null})},[f,M]);return{machineAction:{state:a,message:c},resetMachineAction:u,handleLaunchDetectedIde:f,handleAddWorkspace:w,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:M,handleListSavedSessions:d,handleBrowseDirectory:b,handleOpenRecent:y}}function $p({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:m,setMachineBackTarget:p}){const u=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(),m("machines"),p(h),c("machine")},[a,p,c,m,l]),M=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=>{m(y),c("inbox")},[c,m]);return{openConversation:u,openNativeConversation:f,backFromConversation:w,openMachine:S,openConversationMachine:M,backFromMachine:d,changeMachineSection:b}}function Bp(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Kp(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 yr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Wp({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:m,requestedActiveTabKey:p,onRequestedActiveTabConsumed:u,requestedMachineId:f,onRequestedMachineConsumed:w,requestedMobileSection:S,onRequestedMobileSectionConsumed:M,onOpenHistory:d,onOpenRemote:b,onStopCli:y,wsStatus:h,isConnected:C,onShowHiddenConversation:P,onShowAllHiddenConversations:v,onHideConversation:j,onOpenNewSession:k,notificationStateBySessionId:g,onMarkNotificationTargetRead:x}){const[B,A]=o.useState(()=>{var J;return((J=e[0])==null?void 0:J.tabKey)||null}),[T,L]=o.useState(()=>e[0]?"chat":"inbox"),[O,R]=o.useState("chats"),[N,U]=o.useState(null),[G,I]=o.useState("inbox"),D=_s(),E="0.8.71",W=o.useMemo(()=>e.find(J=>J.tabKey===B)||e[0]||null,[e,B]),X=o.useMemo(()=>W?r.find(J=>J.id===W.routeId):void 0,[r,W]),we=o.useMemo(()=>!W||Xe(W)||!et(W)?null:As(W),[W]),Le=o.useMemo(()=>r.filter(J=>J.type==="adhdev-daemon").sort(ta),[r]),ie=o.useMemo(()=>Le.find(J=>J.id===N)||null,[Le,N]),Ie=o.useMemo(()=>Vr(r),[r]),te=qr({sendDaemonCommand:a,activeConv:W||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),de=Ep({sendDaemonCommand:a,navigate:D,ides:r,conversations:e}),ae=o.useMemo(()=>e.map(J=>{const Se=T==="chat"&&(W==null?void 0:W.tabKey)===J.tabKey,Ue=ea(J,Ie,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Se,notificationStateBySessionId:g}),De=is(J),Ge=bi(J);return{conversation:J,timestamp:De,preview:Ge,unread:Ue.unread,requiresAction:Ue.requiresAction,isWorking:Ue.isWorking,inboxBucket:Ue.inboxBucket}}),[e,Ie,g,T,W]),{markConversationRead:xe}=Rp({conversations:e,machineEntries:Le,items:ae,selectedConversation:W,selectedTabKey:B,screen:T,liveSessionInboxState:Ie,sendDaemonCommand:a,requestedActiveTabKey:p,onRequestedActiveTabConsumed:u,requestedMachineId:f,onRequestedMachineConsumed:w,requestedMobileSection:S,onRequestedMobileSectionConsumed:M,setSelectedTabKey:A,setScreen:L,setSelectedMachineId:U,setSection:R,setMachineBackTarget:I,resetMachineAction:de.resetMachineAction,markNotificationTargetRead:x}),oe=$p({conversations:e,selectedConversation:W,machineBackTarget:G,markConversationRead:xe,resetMachineAction:de.resetMachineAction,setSelectedTabKey:A,setScreen:L,setSelectedMachineId:U,setSection:R,setMachineBackTarget:I}),F=o.useMemo(()=>yr(ae.filter(J=>J.requiresAction)),[ae]),be=o.useMemo(()=>yr(ae.filter(J=>J.unread&&!J.requiresAction)),[ae]),se=o.useMemo(()=>yr(ae.filter(J=>!J.unread&&!J.requiresAction&&J.isWorking)),[ae]),pe=o.useMemo(()=>yr(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(()=>Lp(ie,r),[r,ie]),ne=(ie==null?void 0:ie.version)||null,ge=!!ie&&!!ne&&!0&&ne!==E,me=o.useMemo(()=>(ie==null?void 0:ie.availableProviders)||[],[ie]),$=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(()=>_p(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:T==="chat"&&W?t.jsx(yp,{selectedConversation:W,isAcp:Xe(W),isStandalone:l,selectedIdeEntry:X,actionLogs:n,userName:m,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){Kp(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}):T==="machine"&&ie?t.jsx(Tp,{selectedMachineEntry:ie,selectedMachineConversations:Z,selectedMachineRecentLaunches:le,cliProviders:$,acpProviders:ye,selectedMachineNeedsUpgrade:ge,appVersion:E,machineAction:de.machineAction,isStandalone:l,section:O,showBottomNav:G==="inbox",onBack:oe.backFromMachine,onSectionChange:oe.changeMachineSection,onOpenConversation:oe.openConversation,onOpenRecent:ke,onOpenMachineDetails:()=>D(`/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(wp,{section:O,attentionItems:F,unreadItems:be,workingItems:se,completedItems:pe,hiddenConversations:s,machineCards:he,getAvatarText:Bp,onOpenConversation:oe.openConversation,onShowConversation:P,onShowAllHidden:v,onOpenNewSession:k,onOpenMachine:oe.openMachine,onOpenSettings:()=>D("/settings"),onSectionChange:R,wsStatus:h,isConnected:C,isStandalone:l})})}function yn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Op({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,m]=o.useState(!1),[p,u]=o.useState(null),f=o.useCallback(()=>{c.current=0,m(!1),u(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,m(!0))},[]),S=o.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!yn(s,r)){u("merge");return}const y=b.currentTarget.getBoundingClientRect(),h=b.clientX-y.left,C=y.width/3;h<C?u("split-left"):h>C*2?u("split-right"):u("merge")},[s,r]),M=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,m(!1),u(null))},[]),d=o.useCallback(b=>{c.current=0,m(!1);const y=b.dataTransfer.getData("text/tab-key"),h=y?e.some(P=>P.tabKey===y):!1,C=p;if(u(null),i(),!!y){if(b.preventDefault(),C==="split-left"&&yn(s,r)){r==null||r(y,"split-left");return}if(C==="split-right"&&yn(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:M,handleDrop:d}}function Hp(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 Up({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,m]=o.useState(r??[]),[p,u]=o.useState(null),f=o.useRef(null),w=o.useRef(null),S=o.useRef(n),M=o.useRef(a);o.useEffect(()=>{S.current=n},[n]),o.useEffect(()=>{M.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{m(k=>{const g=Hp(k,e);return g.length===k.length&&g.every((x,B)=>x===k[B])?k:g})},[e]);const d=o.useMemo(()=>{const k=p??l;if(k.length===0)return e;const g=new Map(k.map((x,B)=>[x,B]));return[...e].sort((x,B)=>{const A=g.get(x.tabKey)??999,T=g.get(B.tabKey)??999;return A-T})},[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(B=>B.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)=>{m(B=>{var O;const A=B.filter(R=>R!==k),T=A.indexOf(g);if(T<0)return B;const L=x==="left"?T:T+1;return A.splice(L,0,k),(O=M.current)==null||O.call(M,A),A}),u(null)},[]),C=o.useCallback((k,g,x)=>{const A=(l.length>0?l:e.map(O=>O.tabKey)).filter(O=>O!==k),T=A.indexOf(g);if(T<0)return;const L=x==="left"?T:T+1;A.splice(L,0,k),f.current=A,u(A)},[l,e]),P=o.useCallback(()=>{var g;const k=f.current;k&&(m(k),(g=M.current)==null||g.call(M,k))},[]),v=o.useCallback(()=>{f.current=null,u(null)},[]),j=o.useCallback(k=>{m(g=>{var B;const x=g.filter(A=>A!==k);return x.push(k),(B=M.current)==null||B.call(M,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 Fp({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 va({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(Xi,{}),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 tc="adhdev-tab-shortcuts";function sc(){try{return JSON.parse(localStorage.getItem(tc)||"{}")}catch{return{}}}function rc({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>sc()),[l,m]=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]),u=o.useCallback(f=>{c(f);try{localStorage.setItem(tc,JSON.stringify(f))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const f=w=>{if(w.preventDefault(),w.stopPropagation(),w.key==="Escape"){m(null);return}const S=p(w);if(!S)return;const M={...i};for(const[d,b]of Object.entries(M))b===S&&delete M[d];M[l]=S,u(M),m(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,l,i,u,p]),o.useEffect(()=>{if(!e)return;const f=w=>{if(!(!w.ctrlKey&&!w.metaKey&&!w.altKey)){for(const[S,M]of Object.entries(i))if(s.includes(S)&&p(w)===M){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:m,saveShortcuts:u}}const zp=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:m,onSelectTab:p,onConversationActivated:u,onPreviewReorder:f,onReorderTab:w,onCommitPreviewOrder:S,onClearPreviewOrder:M,onDragStateReset:d,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:h,longPressTimer:C,isGroupActive:P}){const v=Ps(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(),M(),d()},[l,b,S,M,d]),B=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(),D=U.clientX<I.left+I.width/2?"left":"right";f(G,s.tabKey,D)}},[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(),D=U.clientX<I.left+I.width/2?"left":"right";c.includes(G)?w(G,s.tabKey,D):y&&y(G)}M()},[s.tabKey,c,w,y,M]),T=o.useCallback(U=>{U.stopPropagation(),m(),p(s.tabKey),u(s)},[s,u,m,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:B,onDrop:A,onClick:T,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:ss(s)}):v.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[ss(s),t.jsx("span",{className:"connecting-dots"})]}):ss(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 Vp({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:m,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:w,onDragTabKeyChange:S,onReceiveTab:M,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:B,saveShortcuts:A}=rc({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 T=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(zp,{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:m,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:w,onDragTabKeyChange:S,onReceiveTab:M,onOpenContextMenu:T,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(),B(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:()=>B(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 Gp({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:m,userName:p,groupIndex:u,onFocus:f,isSplitMode:w,numGroups:S,onMoveTab:M,onReceiveTab:d,style:b,onActiveTabChange:y,initialActiveTabId:h,initialTabOrder:C,onTabOrderChange:P,onHideTab:v,isFocused:j,allowTabShortcuts:k=!0}){const{sendCommand:g}=Mt(),x=o.useRef(null),{activeTabId:B,activeConv:A,sortedConversations:T,draggingTabRef:L,selectTab:O,handleTabReorder:R,updatePreviewOrder:N,commitPreviewOrder:U,clearPreviewOrder:G,moveTabToEnd:I,setDraggingTabKey:D}=Up({conversations:e,initialActiveTabId:h,initialTabOrder:C,onActiveTabChange:y,onTabOrderChange:P}),E=qr({sendDaemonCommand:a,activeConv:A,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:W,dropAction:X,resetDragState:we,handleDragEnter:Le,handleDragOver:ie,handleDragLeave:Ie,handleDrop:te}=Op({conversations:e,numGroups:S,onMoveTab:M,onReceiveTab:d,onOwnTabDrop:I,onClearPreviewOrder:G}),de=A&&!Xe(A)&&As(A)==="terminal",ae=o.useMemo(()=>A?s.find(se=>se.id===A.routeId):void 0,[s,A]),xe=o.useMemo(()=>A?n.filter(se=>se.routeId===A.tabKey):[],[n,A]),oe=o.useMemo(()=>Vr(s),[s]),F=o.useMemo(()=>new Set(T.filter(se=>Fl(se,oe,{isOpenConversation:se.tabKey===B})).map(se=>se.tabKey)),[B,oe,T]);Zs("PaneGroup",{groupIndex:u,conversationCount:e.length,activeTabId:B,dragOver:W});const be=o.useCallback(se=>{se.streamSource==="agent-stream"&&se.agentType&&g(se.routeId,Yi(),{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(Vp,{conversations:T,activeTabId:B,groupIndex:u,numGroups:S,unreadTabKeys:F,draggingTabRef:L,onFocus:f,onSelectTab:O,onConversationActivated:be,onPreviewReorder:N,onReorderTab:R,onCommitPreviewOrder:U,onClearPreviewOrder:G,onDragStateReset:we,onDragTabKeyChange:D,onMoveTab:M,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(Fp,{dropAction:X,canSplit:!!(S<4&&M)}),A?t.jsx(ga,{activeConv:A,clearToken:r[A.tabKey]||0,isCliTerminal:!!de,ideEntry:ae,terminalRef:x,handleModalButton:E.handleModalButton,handleRelaunch:E.handleRelaunch,handleSendChat:E.handleSendChat,isSendingChat:E.isSendingChat,handleFocusAgent:E.handleFocusAgent,isFocusingAgent:E.isFocusingAgent,actionLogs:xe,userName:p,isInputActive:!w||!!j}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(va,{conversationsCount:e.length,isSplitMode:w,isStandalone:l,hasRegisteredMachines:m})})]})]})}function qp({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:m,setLocalUserMessages:p,setActionLogs:u,isStandalone:f,hasRegisteredMachines:w,userName:S,focusedGroup:M,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((B,A)=>{const T=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(Gp,{style:s?{flexBasis:T??`${100/r}%`,flexGrow:T?0:1,flexShrink:T?0:1}:void 0,conversations:B,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:m,setLocalUserMessages:p,setActionLogs:u,isStandalone:f,hasRegisteredMachines:w,userName:S,groupIndex:A,isFocused:s&&M===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 nc({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?dt.onScreenshot("ide-page",(u,f)=>{if(u!==e)return;const w=new FileReader;w.onload=()=>i(w.result),w.readAsDataURL(f)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var u;return e?((u=dt.onStatus)==null?void 0:u.call(dt,(f,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 m=o.useCallback(async(p,u)=>{const f=e?dt.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(p,u,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:m}}const ac="adhdev-dashboard-action-shortcuts",Yp=1200,Xp={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Qp(){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 oc(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 Fn(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Wr(e){const s=Object.fromEntries(oc(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(ac)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Xp))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function ic(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function Jp({enabled:e=!0,onTrigger:s}){const r=Qp(),[n,a]=o.useState(()=>Wr(r)),[i,c]=o.useState(null),[l,m]=o.useState([]),p=o.useRef({parts:[],timer:null}),u=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(ic(d.key)),b.join("+"))},[r]),f=o.useCallback(d=>{a(d);try{localStorage.setItem(ac,JSON.stringify(d))}catch{}},[]);o.useEffect(()=>{const d=Wr(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}},Yp))},[]);o.useEffect(()=>{if(!i)return;const d=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){c(null),m([]);return}const y=u(b);if(!y)return;const C=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(l.length===0&&C){m([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),m([])};return window.addEventListener("keydown",d,!0),()=>window.removeEventListener("keydown",d,!0)},[n,u,f,i,l]),o.useEffect(()=>{if(!e||i)return;const d=b=>{if(b.defaultPrevented)return;const y=u(b);if(!y)return;const h=b.metaKey||b.ctrlKey||b.altKey;if(Fn(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(([,T])=>!!T),g=k.find(([,T])=>T===v);if(g){b.preventDefault(),w(),s(g[0]);return}if(k.some(([,T])=>T.startsWith(`${v} `))){b.preventDefault(),p.current.parts=P,S();return}const B=k.find(([,T])=>T===j);if(B){b.preventDefault(),w(),s(B[0]);return}if(k.some(([,T])=>T.startsWith(`${j} `))){b.preventDefault(),p.current.parts=[j],S();return}w()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[n,S,e,u,s,w,i]),o.useEffect(()=>()=>w(),[w]);const M=o.useMemo(()=>oc(r),[r]);return{isMac:r,actionDefinitions:M,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:m,saveShortcuts:f}}function Zp({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 ef(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function yo({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!ef(n):!0}const cc=o.createContext(null);function Zr(){const e=o.useContext(cc);if(!e)throw new Error("DashboardDockviewContext missing");return e}function Mr(e){return it(e)||e.tabKey}function tf(e){return`remote:${e}`}function zt(e){return e.startsWith("remote:")}function vo(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function vn(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,m;try{s.focus(),(m=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||m.call(l)}catch{}})}catch{}}function vr(e,s){e.classList.remove(Tn.className,Ln.className),e.classList.add(s==="light"?Tn.className:Ln.className)}function wo(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 sf(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 rf(e,s,r){var c;const n=[s];let a;for(const l of n){let m;for(const p of l){const u=e.addPanel({id:p.tabKey,component:"conversation",title:Mr(p),params:{kind:"conversation",tabKey:p.tabKey},...m?{position:{referencePanel:m,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});m||(m=u.id)}a=m??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function jo(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!==Mr(n)&&a.api.setTitle(Mr(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:Mr(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 ko(e,s,r){var m,p;const n=r?tf(r):null;for(const u of[...e.panels])zt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Bt(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=vi(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((m=e.activePanel)==null?void 0:m.id)??((p=e.panels.find(u=>!zt(u.id)))==null?void 0:p.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function nf({params:e,api:s}){var f;const r=Zr(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=qr({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 m=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(va,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const u=!Xe(c)&&As(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(ga,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:u,ideEntry:m,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 af({params:e}){var m;const s=Zr(),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)||((m=r==null?void 0:r.routeId)==null?void 0:m.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=nc({doId:a,targetSessionId:r?na(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(Xo,{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 of(){const e=Zr();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(va,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function cf(e){var S,M;sf(e);const s=Zr(),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=((M=e.api.group.activePanel)==null?void 0:M.id)===e.api.id,i=e.api.isGroupActive,c=ea(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,m=c.isConnecting,p=c.isGenerating,u=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"}):u?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):m?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:ss(n)}):m?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:ss(n)}):t.jsx("span",{children:ss(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 lf({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:m,initialDataLoaded:p,userName:u,toggleHiddenTab:f,actionShortcuts:w,registerActionHandlers:S,onActiveTabChange:M,requestedActiveTabKey:d,requestedRemoteIdeId:b,onRequestedActiveTabConsumed:y,scrollToBottomRequest:h,notificationStateBySessionId:C}){var Ke,Re,ft;const{theme:P}=pa(),{sendCommand:v}=Mt(),j=o.useRef(null),k=o.useRef(null),g=o.useRef(!1),x=o.useRef(!1),B=o.useRef(!1),A=o.useRef(null),T=o.useRef([]),[L,O]=o.useState(null),[R,N]=o.useState(!1),[U,G]=o.useState(!1),[I,D]=o.useState(0),E=o.useRef(null),W=o.useMemo(()=>zi(typeof window<"u"?window.innerWidth:1280),[]),X=o.useRef(typeof window>"u"?{}:Um(W)),we=o.useMemo(()=>new Map(e.map(K=>[K.tabKey,K])),[e]),Le=o.useMemo(()=>Vr(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"),vr(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"),vr(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"),vr(ee,P),ee.classList.toggle("is-showing-dockview-overlay",U),ee.classList.toggle("is-dragging-dockview",R)}catch{}},[R,U,P]),xe=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),ge();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}},[]),be=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()),vn(document)},[]),ge=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=vi(_),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?ss(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;">${vo(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;">${vo(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():vn((V=z.group.element)==null?void 0:V.ownerDocument)}catch{}}},[]),$=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,Te=0,Pe=0,$e=!1;if(K==="left"?($e=Y<Ce,_e=Math.max(0,ve.left-_.right),Te=Math.abs(re-Ne),Pe=Fe(ve.top,ve.bottom,_.top,_.bottom)):K==="right"?($e=Y>Ce,_e=Math.max(0,_.left-ve.right),Te=Math.abs(re-Ne),Pe=Fe(ve.top,ve.bottom,_.top,_.bottom)):K==="above"?($e=re<Ne,_e=Math.max(0,ve.top-_.bottom),Te=Math.abs(Y-Ce),Pe=Fe(ve.left,ve.right,_.left,_.right)):($e=re>Ne,_e=Math.max(0,_.top-ve.bottom),Te=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+Te+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(),vn((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}=rc({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(ic(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&&xe(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":$(-1);return;case"selectNextGroupTab":$(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)&&be(V);return}default:return}},[$,le,he,se,Z,be,pe,F,oe,ke,xe,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:m,liveSessionInboxState:Le,notificationStateBySessionId:C,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:be,userName:u,scrollToBottomRequest:h,tabShortcuts:Se,openTabContextMenu:({x:K,y:H,tabKey:z,sourceDocument:V})=>O({x:K,y:H,tabKey:z,sourceDocument:V??document}),popoutTab:xe,moveTabBackToMain:oe,isTabInPopout:F,floatTab:se,isTabFloating:pe}),[n,s,we,ie,r,l,m,Le,C,a,c,i,be,u,h,Se,xe,oe,F,se,pe]),ht=L?Zp({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(B.current)return!1;const K=tt(A.current);return K&&(B.current=!0),K},[tt]),pt=o.useCallback(()=>{var H;const K=j.current;K&&Hm(W,{activeTabId:((H=K.activePanel)==null?void 0:H.id)??null,layout:K.toJSON()})},[W]),ce=o.useCallback(()=>{Fm(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:()=>$(-1),activateNextTabInGroup:()=>$(1),floatActiveTab:()=>{const K=Z();K&&se(K)},popoutActiveTab:()=>{const K=Z();K&&xe(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)),[$,le,se,he,Z,pe,F,ke,oe,xe,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")&&(E.current!=null&&window.clearTimeout(E.current),window.requestAnimationFrame(()=>{Je(),jt()}),E.current=window.setTimeout(()=>{Je(),jt(),E.current=null},80))},[bt,Je,jt]),Nt=o.useCallback(K=>{var z;j.current=K.api;const H=Om(W);if(A.current=(H==null?void 0:H.activeTabId)??null,H!=null&&H.layout&&K.api.fromJSON(H.layout,{reuseExistingPanels:!1}),x.current=yo({hasStoredLayout:!!(H!=null&&H.layout),initialDataLoaded:p,visibleConversationCount:e.length,ides:r}),x.current||(jo(K.api,e),ko(K.api,e,b)),K.api.totalPanels===0&&e.length>0){const V=rf(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,B.current=!0,ge(),V&&zt(V.id)){const Ce=((ve=V.params)==null?void 0:ve.routeId)||V.id.slice(7),Ne=Bt(e,Ce);M((Ne==null?void 0:Ne.tabKey)??null),pt();return}if(M((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,Yi(),{agentType:ee.agentType,...ee.sessionId&&{targetSessionId:ee.sessionId}}).catch(()=>{})}),K.api.onDidLayoutChange(()=>{pt(),ge(),D(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{}ge(),D(Ce=>Ce+1)})}),M(((z=K.api.activePanel)==null?void 0:z.id)??null)},[mt,tt,kt,bt,we,r,p,W,Je,M,pt,d,b,v,ge,e]);o.useLayoutEffect(()=>{const K=j.current;if(!K||!g.current||x.current&&yo({hasStoredLayout:!0,initialDataLoaded:p,visibleConversationCount:e.length,ides:r}))return;x.current&&(x.current=!1);const H=T.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(),jo(K,e),ko(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(),T.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"||E.current!=null&&window.clearTimeout(E.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=wo(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&&vr(K,P),de(),ge(),ae()},[ge,ae,de,P]),o.useEffect(()=>{ge(),ae()},[ge,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;Fn(H.target)&&!V||Wr(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=wo(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=sc();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(Fn(We.target)&&!Q)return;const Ee=Wr(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 Tt=P==="light"?Tn:Ln,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(cc.Provider,{value:qe,children:[t.jsx("div",{ref:k,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(Uc,{className:`h-full min-h-0 min-w-0 adhdev-dockview${R?" is-dragging-dockview":""}${U?" is-showing-dockview-overlay":""}`,components:{conversation:nf,remote:af},defaultTabComponent:cf,watermarkComponent:of,onReady:Nt,singleTabMode:"default",tabAnimation:"smooth",theme:Tt,popoutUrl:"/popout.html"})}),L&&Ys.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(Cl,{size:13,className:"shrink-0 opacity-70"}),z=()=>{};switch(K.id){case"dockInWindow":case"dockBackToGrid":H=t.jsx(Al,{size:13,className:"shrink-0 opacity-70"}),z=()=>{le(L.tabKey),O(null)};break;case"moveBackToMain":H=t.jsx(Nl,{size:13,className:"shrink-0 opacity-70"}),z=()=>{oe(L.tabKey),O(null)};break;case"floatAsPanel":H=t.jsx(Il,{size:13,className:"shrink-0 opacity-70"}),z=()=>{se(L.tabKey),O(null)};break;case"openInNewWindow":H=t.jsx(Sl,{size:13,className:"shrink-0 opacity-70"}),z=()=>{xe(L.tabKey),O(null)};break;case"setShortcut":z=V=>{V.stopPropagation(),De(L.tabKey),O(null)};break;case"removeShortcut":H=t.jsx(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(zo,{size:13,className:"shrink-0 opacity-70"}),z=()=>{be(L.tabKey),O(null)};break}return t.jsxs("button",{className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${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&&Ys.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 lc="adhdev-recent-launch-args-v1",df=8;function uf(e){return String(e||"").trim().replace(/\s+/g," ")}function dc(e,s){return`${e.trim()}::${s.trim()}`}function uc(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(lc)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function mf(e){if(!(typeof window>"u"))try{window.localStorage.setItem(lc,JSON.stringify(e))}catch{}}function mc(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=uc().byKey[dc(r,n)])==null?void 0:i.items)||[]}function pc(e,s,r){var u;const n=String(e||"").trim(),a=String(s||"").trim(),i=uf(r);if(!n||!a||!i)return;const c=uc(),l=dc(n,a),m=((u=c.byKey[l])==null?void 0:u.items)||[],p=[i,...m.filter(f=>f!==i)].slice(0,df);c.byKey[l]={items:p},mf(c)}function pf(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 wa(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 fc(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=wa((i==null?void 0:i.meta)||void 0),m=((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")&&(m||l)?r.push(i):n.push(i)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function hc(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function ks(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 wn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function ff(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function So(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function No(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 hf(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function xf(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 bf(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 gf({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:a,onOpenConversation:i,onClose:c}){var G;const[l,m]=o.useState(n||((G=e[0])==null?void 0:G.id)||null),[p,u]=o.useState(""),[f,w]=o.useState(null),[S,M]=o.useState(!1);o.useEffect(()=>{var I;m(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 D=ff(I.daemonId||I.id);return!!(d!=null&&d.id)&&D===d.id}),[d==null?void 0:d.id,r]),y=Ki(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 D of b){const E=s.find(W=>W.sessionId===D.sessionId||W.routeId===D.id);D.sessionId&&E&&I.set(D.sessionId,E)}return I},[b,s]),j=o.useCallback(async()=>{if(d!=null&&d.id){M(!0);try{const I=await a(d.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),D=wn(I);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Could not load hosted runtime diagnostics");P(D.diagnostics||D.result||null),u("")}catch(I){const D=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";u(D)}finally{M(!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,D)=>{if(!(d!=null&&d.id)||I==="session_host_stop_session"&&!window.confirm(`Stop ${D.displayName}?
|
|
55
|
-
This will terminate the hosted runtime.`))return;const E=`${I}:${D.sessionId}`;w(E);try{const W=await a(d.id,I,{sessionId:D.sessionId}),X=wn(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}: ${D.displayName}`,"success"),await j()}catch(W){const X=W instanceof Error?W.message:"Session host action failed";u(X),ot.showToast(X,"warning")}finally{w(W=>W===E?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 D=await a(d.id,"session_host_prune_duplicate_sessions",{}),E=wn(D);if(!(E!=null&&E.success))throw new Error((E==null?void 0:E.error)||"Duplicate prune failed");const W=E.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(D){const E=D instanceof Error?D.message:"Duplicate prune failed";u(E),ot.showToast(E,"warning")}finally{w(D=>D==="session_host_prune_duplicate_sessions"?null:D)}}},[d==null?void 0:d.id,j,a]),x=o.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((I,D)=>(D.lastActivityAt||0)-(I.lastActivityAt||0)),[h==null?void 0:h.sessions]),B=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)||[]}:fc(x),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,x]),A=B.liveRuntimes,T=B.recoverySnapshots,L=B.inactiveRecords,O=o.useMemo(()=>bf(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,D)=>{var ae,xe;const E=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=wa(I.meta),Ie=typeof((ae=I.meta)==null?void 0:ae.runtimeRecoveryError)=="string"?String(I.meta.runtimeRecoveryError):"",te=D==="recovery"?"Recover":"Resume",de=hc(D);return t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-3.5",children:[t.jsx("div",{className:"flex items-start justify-between gap-3",children:t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("div",{className:"text-[14px] font-bold text-text-primary",children: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 ${xf(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:((xe=I.writeOwner)==null?void 0:xe.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:hf(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(Xn,{size:11})," ",I.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",No(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:[E&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(E),c()},children:"Open chat"}),D==="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"}),D==="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(Rs,{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:()=>m(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(ds,{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:T.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:No(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:So(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(ds,{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(Ur,{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:ks("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:ks("recovery")}),T.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:T.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:ks("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 D=x.find(E=>E.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:(D==null?void 0:D.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:So(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]})]})]})]})})}function Us({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 xc({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?Ji(n):null;return t.jsxs(Us,{title:"Saved history",description:ca(),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:Su()})]}),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 jn(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 wr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function yf({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:m,sendDaemonCommand:p,onOpenConversation:u}){var Nt,Tt;const f=tr(),w=o.useMemo(()=>[...e].sort(ta),[e]),[S,M]=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(jn(w[0])),[g,x]=o.useState(""),[B,A]=o.useState(""),[T,L]=o.useState([]),[O,R]=o.useState(""),[N,U]=o.useState([]),[G,I]=o.useState(!1),[D,E]=o.useState(""),[W,X]=o.useState(!1),[we,Le]=o.useState(()=>gt()),[ie,Ie]=o.useState(!1),[te,de]=o.useState(null),[ae,xe]=o.useState(!1),[oe,F]=o.useState(""),[be,se]=o.useState(!1),[pe,Z]=o.useState(""),[le,ne]=o.useState([]),[ge,me]=o.useState(!1),[$,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)&&M(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(jn(d)),x(""),A(""),R(""),U([]),E(""),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:jn(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),E(""),m(q,Ke).then(ft=>{Se.current===Re&&U(ft)}).catch(ft=>{Se.current===Re&&(U([]),E(ft instanceof Error?ft.message:"Could not load saved sessions"))}).finally(()=>{Se.current===Re&&I(!1)})},[m]),ut=o.useCallback((q,Ke)=>{L(mc(q,Ke))},[]);o.useEffect(()=>{if(R(""),Le(gt()),!d||!g||j==="ide"?L([]):ut(d.id,g),j!=="cli"){U([]),E(""),I(!1);return}if(!d||!g){U([]),E(""),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__"?"":((Tt=b.find(q=>q.id===h))==null?void 0:Tt.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=>wr(ft.path)===wr(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=>wr(ft.path)===wr(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=Xr(d.platform,Yr(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;xe(!0),F("");const q=B.trim()?B.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(xe(!1),!Ke.ok){F(Ke.error||"Could not start session");return}j!=="ide"&&B.trim()&&(pc(d.id,g,B),ut(d.id,g)),n()},[j,B,ut,n,c,l,qe,d,O,g,h]),jt=j?ji(j,j==="cli"&&!!O):"Start",kt=j?ki(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(Us,{title:"Machine",children:t.jsx("select",{value:d.id,onChange:q=>M(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(Us,{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}),ju()]})}),t.jsxs(Us,{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?"⭐ ":"",Gr(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(Ns,{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(Us,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:B,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}),T.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:T.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(xc,{busy:ae,savedSessionsLoading:G,savedSessionsError:D,selectedSession:pt,onRefresh:()=>{!d||!g||Ze(d.id,g)},onOpenHistory:()=>{!d||!g||(X(!0),Ze(d.id,g))},onClearSelection:()=>R("")}),oe&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${oe.includes("saved")||oe.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:oe})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:n,disabled:ae,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:bt,disabled:ae||!j||!g||h==="__custom__"&&!qe,children:[t.jsx(Jn,{size:14}),ae?kt:jt]})]})]})}),be&&t.jsx(Jr,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:pe,directories:le,busy:ge,error:$,onClose:()=>se(!1),onNavigate:ct,onConfirm:q=>{v(q),Z(q),C("__custom__"),se(!1)}}),W&&ce&&t.jsx(ua,{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),xe(!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(()=>{xe(!1),de(Re=>Re===q.providerSessionId?null:Re)})}}),ie&&d&&t.jsx(gf,{machineCards:[{id:d.id,label:It(d,{fallbackId:d.id}),subtitle:[d.platform||"machine",ec(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(),u(q)},onClose:()=>Ie(!1)})]}):null}function vf(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 wf(e){return e instanceof Error?e.message:String(e||"")}function jf(e){const s=wf(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function kf({showMobileChatMode:e,isMobile:s,activeConv:r,chatIdes:n,wsStatus:a,isConnected:i,onOpenHistory:c,onOpenRemote:l,onStopCli:m,activeCliViewMode:p,onSetActiveCliViewMode:u,mobileChatConversations:f,hiddenConversations:w,ides:S,actionLogs:M,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,initialDataLoaded:C,userName:P,requestedMobileTabKey:v,onRequestedMobileTabConsumed:j,requestedMachineId:k,onRequestedMachineConsumed:g,requestedMobileSection:x,onRequestedMobileSectionConsumed:B,containerRef:A,isSplitMode:T,numGroups:L,groupSizes:O,groupedConvs:R,clearedTabs:N,focusedGroup:U,setFocusedGroup:G,moveTabToGroup:I,splitTabRelative:D,closeGroup:E,handleResizeStart:W,groupActiveTabIds:X,setGroupActiveTabIds:we,groupTabOrders:Le,setGroupTabOrders:ie,toggleHiddenTab:Ie,visibleConversations:te,requestedDesktopTabKey:de,onRequestedDesktopTabConsumed:ae,onDesktopActiveTabChange:xe,onHideConversation:oe,onShowHiddenConversation:F,onShowAllHiddenConversations:be,scrollToBottomRequest:se,machineEntries:pe,onBrowseMachineDirectory:Z,onSaveMachineWorkspace:le,onLaunchMachineIde:ne,onLaunchMachineProvider:ge,onListMachineSavedSessions:me,notifications:$,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;Ys.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),xe(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,xe,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)},[]),Tt=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,...js(r)})}catch(_e){jf(_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}=Jp({enabled:kt&&!qe,onTrigger:Q=>{var Ee,ze,_,Y,re,_e,Te,Pe,$e,Be,st,Ft,Yt,rr,Xt,nr;if(Q==="openShortcutHelp"){Ke();return}if(Q==="hideCurrentTab"){r&&oe(r);return}if(Q==="toggleHiddenTabs"){Tt(!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"){(Te=De.current)==null||Te.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"&&u(p==="chat"?"terminal":"chat")}}),Ne=nt.useCallback(()=>{ht(!1),ee(null),ve([])},[ee,ve]),Fe=nt.useMemo(()=>bt==="all"?K:K.filter(Q=>vf(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(bu,{activeConv:r,agentCount:n.length,wsStatus:a,isConnected:i,conversations:te,hiddenConversations:w,onOpenHistory:c,onHideConversation:oe,onShowConversation:xt,onShowAllHidden:be,onResetPanelsToMain:q,notifications:$,notificationUnreadCount:ye,onOpenNotification:pt,onMarkNotificationRead:ke,onMarkNotificationUnread:J,onDeleteNotification:Se,inboxOpen:Ge,onInboxOpenChange:Nt,hiddenOpen:Ze,onHiddenOpenChange:Tt,onOpenNewSession:s?void 0:()=>tt(!0),actionShortcuts:H,onOpenRemote:()=>{!r||et(r)||Xe(r)||l(r)},onStopCli:m,activeCliViewMode:p,onSetCliViewMode:u}),e?t.jsx(Wp,{conversations:f,hiddenConversations:w,ides:S,actionLogs:M,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,userName:P,requestedActiveTabKey:v,onRequestedActiveTabConsumed:j,requestedMachineId:k,onRequestedMachineConsumed:g,requestedMobileSection:x,onRequestedMobileSectionConsumed:B,onOpenHistory:c,onOpenRemote:l,onStopCli:m,wsStatus:a,isConnected:i,onShowHiddenConversation:xt,onShowAllHiddenConversations:be,onOpenNewSession:()=>tt(!0),notificationStateBySessionId:he,onMarkNotificationTargetRead:Ue}):s?t.jsx(qp,{containerRef:A,isSplitMode:T,numGroups:L,groupSizes:O,groupedConvs:R,clearedTabs:N,ides:S,actionLogs:M,sendDaemonCommand:d,setLocalUserMessages:b,setActionLogs:y,isStandalone:h,hasRegisteredMachines:pe.length>0,userName:P,focusedGroup:U,setFocusedGroup:G,moveTabToGroup:I,splitTabRelative:D,closeGroup:E,handleResizeStart:W,groupActiveTabIds:X,setGroupActiveTabIds:we,groupTabOrders:Le,setGroupTabOrders:ie,toggleHiddenTab:Ie,allowTabShortcuts:!1}):t.jsx(lf,{visibleConversations:te,clearedTabs:N,ides:S,actionLogs:M,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:xe,requestedActiveTabKey:de,onRequestedActiveTabConsumed:ae,scrollToBottomRequest:se}),mt&&t.jsx(yf,{machines:pe,conversations:f,ides:S,onClose:()=>tt(!1),onBrowseDirectory:Z,onSaveWorkspace:le,onLaunchIde:ne,onLaunchProvider:ge,onListSavedSessions:me,sendDaemonCommand:d,onOpenConversation:Q=>{tt(!1),F(Q),xe(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 kn=[{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 Sf({onClose:e}){const[s,r]=o.useState(0),n=kn[s],a=s===kn.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:kn.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 Nf({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",m=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)":m?"var(--accent-primary)":"var(--text-muted)",boxShadow:m?"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 Cf({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),m=o.useMemo(()=>Ni(s),[s]),p=o.useMemo(()=>e?ma(e,n,{machineNames:m,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,m,r]),u=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"&&(u||f[0]&&l(f[0].tabKey))},[c,u,f]);const S=o.useMemo(()=>c==="native"&&u?u:f.find(b=>b.tabKey===c)||w||u||f[0],[c,u,w,f]),M=o.useMemo(()=>f.map(b=>({tabKey:b.tabKey,title:yi(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:M,hasExtensions:M.length>0,resolveConversationByTarget:d}}function If({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:m,isStandalone:p,userName:u,onOpenHistory:f,onConversationChange:w,onClose:S}){const[M,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}=Cf({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,D={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=D,!(I&&I.routeId===D.routeId&&I.tabKey===D.tabKey&&I.streamSource===D.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]),B=Wi(x),A=o.useMemo(()=>B.status||B.modalMessage||B.modalButtons?{...x,...B.status?{status:B.status}:{},...B.modalMessage!==void 0?{modalMessage:B.modalMessage}:{},...B.modalButtons!==void 0?{modalButtons:B.modalButtons}:{}}:x,[x,B]),T=er(A),L=qr({sendDaemonCommand:c,activeConv:A,setLocalUserMessages:l,setActionLogs:m,isStandalone:p}),{connScreenshot:O,screenshotUsage:R,handleRemoteAction:N}=nc({doId:T,targetSessionId:na(A),connState:A.connectionState||"new",viewMode:M}),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=D=>{D.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:ra(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 D=M===I;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${D?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>d(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?t.jsx(ul,{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(Qn,{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 ${M==="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:[M!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${M==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(Nf,{hasExtensions:k,ideName:P||"IDE",activeChatTab:b,extensionTabs:j,onSelectTab:y}),t.jsx(Jo,{activeConv:A,onModalButton:L.handleModalButton}),t.jsx($n,{activeConv:A,ideEntry:C,showMetaChips:!1,handleSendChat:L.handleSendChat,isSendingChat:L.isSendingChat,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:U,userName:u})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${M==="split"?"order-1 md:order-2":""}`,children:t.jsx(Xo,{addLog:()=>{},connState:A.connectionState||"new",connScreenshot:O,screenshotUsage:R,transportType:A.transport,onAction:N})})]})]})})}function Af({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=pu(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 Mf({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:a,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:m,onNewHistoryChat:p,onSwitchHistorySession:u,onRefreshHistory:f,onResumeSavedHistorySession:w,remoteDialogConv:S,remoteDialogIdeEntry:M,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:h,setLocalUserMessages:C,setActionLogs:P,isStandalone:v,userName:j,onOpenRemoteHistory:k,onRemoteConversationChange:g,onCloseRemoteDialog:x,cliStopDialogOpen:B,cliStopTargetConv:A,onCancelCliStop:T,onStopCliNow:L,onSaveCliAndStop:O,toasts:R,onDismissToast:N,onClickToast:U,showOnboarding:G,onCloseOnboarding:I}){var W;const[D,E]=nt.useState(()=>gt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(ua,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:D,onSavedHistoryFiltersChange:E,onClose:m,onNewChat:p,onSwitchSession:u,onRefreshHistory:f,onResumeSavedSession:w}),S&&t.jsx(If,{activeConv:S,ideEntry:M,ides:r,connectionStates:d,actionLogs:b,localUserMessages:y,sendDaemonCommand:h,setLocalUserMessages:C,setActionLogs:P,isStandalone:v,userName:j,onOpenHistory:k,onConversationChange:g,onClose:x}),B&&A&&(et(A)||Xe(A))&&t.jsx(Af,{activeConv:A,canSaveAndStop:et(A)&&!Xe(A)&&!!((W=A.resume)!=null&&W.supported),onCancel:T,onStopNow:L,onSaveAndStop:O}),t.jsx(Si,{toasts:R,onDismiss:N,onClickToast:U}),G&&t.jsx(Sf,{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(Rs,{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}),m=n[c.id],p=c.version||c.daemonVersion||"unknown",u=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:l}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",p]}),u&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),m==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):m==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):m==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):t.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:u?"Update now":"Upgrade"})]},c.id)})]}),!r&&t.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:t.jsx(St,{size:16})})]})}function Lf(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Co(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function _f(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Rf(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 Pf(){var Ca,Ia,Aa,Ma,Ta;const{sendCommand:e}=Mt(),s=tr(),r=qn(),n=_s(),[a,i]=Fc(),c=a.get("activeTab"),l=((Ca=r.state)==null?void 0:Ca.openRemoteForTabKey)||null,m=((Ia=r.state)==null?void 0:Ia.openMachineId)||null,p=((Aa=r.state)==null?void 0:Aa.mobileSection)||null,u=hi(),f=u.ides||[],w=u.initialLoaded??!0,{updateRouteChats:S,setToasts:M}=u,[d,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),y=u.toasts||[],h=u.wsStatus||"connected",C=u.isConnected??!0,P=u.connectionStates||{},v=u.showReconnected||!1,{groupAssignments:j,setGroupAssignments:k,focusedGroup:g,setFocusedGroup:x,groupActiveTabIds:B,setGroupActiveTabIds:A,groupTabOrders:T,setGroupTabOrders:L,groupSizes:O,setGroupSizes:R,isMobile:N,hasHydratedStoredLayout:U,hydrateStoredLayout:G}=Vm(),[I,D]=o.useState(!1),[E,W]=o.useState(!1),[X,we]=o.useState(null),[Le,ie]=o.useState([]),[Ie,te]=o.useState(!1),[de,ae]=o.useState(null),[xe]=o.useState(()=>Bi()),[oe,F]=o.useState([]),[be,se]=o.useState({}),[pe,Z]=o.useState({}),[le,ne]=o.useState({}),[ge,me]=o.useState(null),[$,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(be).length,actionLogCount:oe.length});const Se=f.find(fe=>fe.type==="adhdev-daemon"),Ue=o.useMemo(()=>f.filter(fe=>fe.type==="adhdev-daemon").sort(ta),[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(()=>ym(f,pe),[f,pe]),{hiddenTabs:qe,hideTab:ht,toggleTab:mt,showTab:tt,showAllTabs:xt}=gm(),{chatIdes:pt,conversations:ce,visibleConversations:Ve,visibleTabKeys:ct,resolveConversationBySessionId:Je,resolveConversationByTarget:bt}=Rm({ides:ut,connectionStates:P,localUserMessages:be,clearedTabs:le,hiddenTabs:qe});ru(ce),o.useEffect(()=>{Object.keys(pe).length!==0&&Z(fe=>vm(fe,f))},[f,pe]);const jt=o.useMemo(()=>Vr(f),[f]),{notifications:kt,unreadCount:Nt,notificationStateBySessionId:Tt,markRead:q,markUnread:Ke,markTargetRead:Re,deleteNotification:ft}=hp({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}=ep({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,Me;if(!N){if(ge){const ue=ce.find(Oe=>Oe.tabKey===ge);if(ue)return ue}return Ve[0]}const fe=B[g];if(fe){const ue=ce.find(Oe=>Oe.tabKey===fe);if(ue)return ue}return((Ae=ve[g])==null?void 0:Ae[0])||((Me=ve[0])==null?void 0:Me[0])},[ge,N,B,g,ce,ve,Ve]);o.useEffect(()=>{if(N){K.current=null;return}if(!(je!=null&&je.sessionId)){K.current=null;return}const fe=Rr(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 Me=()=>{if(document.visibilityState!=="visible"||K.current===Ae)return;K.current=Ae;const ue=Math.max(Date.now(),is(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(Me,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(Me,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}=Pm({isMobile:N,urlActiveTab:c,resolveConversationBySessionId:Je,setSearchParams:i}),{remoteDialogConv:_,remoteDialogIdeEntry:Y,remoteDialogActiveConv:re,setRemoteDialogActiveConv:_e,openRemoteDialog:Te,closeRemoteDialog:Pe}=Ym({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&&xe==="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)=>Qr(e,fe,Ae),[e]),bc=o.useCallback(async(fe,Ae)=>{if(!Ae.trim())return{ok:!1,error:"Choose a workspace path first."};try{const Me=await e(fe,"workspace_add",{path:Ae.trim()});return Me!=null&&Me.success?{ok:!0}:{ok:!1,error:(Me==null?void 0:Me.error)||"Could not save workspace"}}catch(Me){return{ok:!1,error:Me instanceof Error?Me.message:"Could not save workspace"}}},[e]),gc=o.useCallback(async(fe,Ae,Me)=>{var ue;try{const Oe={ideType:Ae,enableCdp:!0};(ue=Me==null?void 0:Me.workspacePath)!=null&&ue.trim()&&(Oe.workspace=Me.workspacePath.trim());const lt=await e(fe,"launch_ide",Oe);return!(lt!=null&<.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:(Me==null?void 0:Me.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Oe){return{ok:!1,error:Oe instanceof Error?Oe.message:"Could not launch IDE"}}},[e]),yc=o.useCallback(async(fe,Ae,Me,ue)=>{var lt,Ds,hs;const Oe=Date.now();try{const Rt={cliType:Me};(lt=ue==null?void 0:ue.workspacePath)!=null&<.trim()?Rt.dir=ue.workspacePath.trim():ue!=null&&ue.workspaceId&&(Rt.workspaceId=ue.workspaceId),(Ds=ue==null?void 0:ue.resumeSessionId)!=null&&Ds.trim()&&(Rt.resumeSessionId=ue.resumeSessionId.trim()),Array.isArray(ue==null?void 0:ue.cliArgs)&&ue.cliArgs.length>0&&(Rt.cliArgs=ue.cliArgs),(hs=ue==null?void 0:ue.initialModel)!=null&&hs.trim()&&(Rt.initialModel=ue.initialModel.trim());const yt=await e(fe,"launch_cli",Rt),Ct=(yt==null?void 0:yt.result)||yt,Es=(Ct==null?void 0:Ct.sessionId)||(Ct==null?void 0:Ct.id);return yt!=null&&yt.success&&Es?(Xt(Es),{ok:!0}):yt!=null&&yt.success?(ke({machineId:fe,kind:Ae,providerType:Me,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 _f(Rt)?(ke({machineId:fe,kind:Ae,providerType:Me,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]),vc=o.useCallback(async(fe,Ae)=>{if(!fe||!Ae)return[];try{const Me=await e(fe,"list_saved_sessions",{providerType:Ae,kind:"cli",limit:30}),ue=(Me==null?void 0:Me.result)??Me;return Array.isArray(ue==null?void 0:ue.sessions)?ue.sessions:[]}catch(Me){return console.error("List saved sessions failed",Me),[]}},[e]);o.useEffect(()=>{var ue;if(!he)return;const fe=Co(he.workspacePath),Ae=f.find(Oe=>{var yt,Ct,Es,La;if(!Oe||Oe.type==="adhdev-daemon"||Lf(Oe.daemonId||Oe.id)!==he.machineId||(Qs(Oe)?"cli":ws(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 tn=Co(Oe.workspace||Oe.runtimeWorkspaceLabel);return tn?tn===fe:!1}return Number(Oe.lastUpdated||Oe._lastUpdate||Oe.timestamp||((La=(Es=(Ct=(yt=Oe.activeChat)==null?void 0:yt.messages)==null?void 0:Ct.at)==null?void 0:Es.call(Ct,-1))==null?void 0:La.timestamp)||0)>=he.startedAt-5e3});if(!Ae)return;const Me=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;Me&&(ke(null),Xt(Me))},[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]),wm({visibleConversations:Ve,clearedTabs:le,setClearedTabs:ne,setActionLogs:F}),Dm({ides:f,sendDaemonCommand:e,setToasts:M,setLocalUserMessages:se,resolveConversationByTarget:bt});const{isRefreshingHistory:wc,handleRefreshHistory:jc}=io({sendDaemonCommand:e,activeConv:je,chats:(Ma=f.find(fe=>fe.id===(je==null?void 0:je.routeId)))==null?void 0:Ma.chats,updateRouteChats:S,setToasts:M,setLocalUserMessages:se,setClearedTabs:ne}),{isCreatingChat:kc,isRefreshingHistory:Sc,handleSwitchSession:Nc,handleNewChat:Cc,handleRefreshHistory:Ic}=io({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:M,setLocalUserMessages:se,setClearedTabs:ne}),en=o.useCallback(async()=>{if(!(!$e||!Be||Ie)){te(!0);try{const fe=$e.daemonId||$e.routeId,Ae=Dt($e),Me=await e(fe,"list_saved_sessions",{agentType:Ae,providerType:Ae,kind:"cli",limit:50}),ue=(Me==null?void 0:Me.result)??Me;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,en())},[en,I,Ie,Be,st]);const Ac=o.useCallback(async fe=>{if(!$e||!Be||!fe.providerSessionId||!fe.workspace)return;const Ae=$e.daemonId||$e.routeId,Me=Dt($e);try{ae(fe.providerSessionId);const ue=await e(Ae,"launch_cli",{cliType:Me,dir:fe.workspace,resumeSessionId:fe.providerSessionId,initialModel:si(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(Ds=>{const hs=new URLSearchParams(Ds);return hs.set("activeTab",lt),hs},{replace:!0}),D(!1)}catch(ue){console.error("Resume saved session failed",ue)}finally{ae(null)}},[$e,Be,e,i]);qm({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:wc,ides:f,handleRefreshHistory:jc});const ja=o.useCallback(async(fe,Ae)=>{const Me=Ae||X||je;if(!Me||!et(Me)&&!Xe(Me))return;const ue=Dt(Me),Oe=Me.routeId||Me.daemonId||"";try{await e(Oe,"stop_cli",{cliType:ue,targetSessionId:Me.sessionId,mode:fe})}catch(lt){console.error("Stop CLI failed:",lt)}},[je,X,e]),Mc=o.useCallback(async fe=>{const Ae=fe||je;!Ae||!et(Ae)&&!Xe(Ae)||(we(Ae),W(!0))},[je]),Tc=o.useMemo(()=>!je||!et(je)||Xe(je)?null:As(je),[je]),Lc=o.useCallback(async fe=>{if(!je||!et(je)||Xe(je))return;const Ae=As(je);if(Ae===fe)return;const Me=je.sessionId;Me&&Z(ue=>({...ue,[Me]:fe}));try{await e(qt(je)||je.routeId,"set_cli_view_mode",{targetSessionId:je.sessionId,cliType:Dt(je),mode:fe})}catch(ue){Me&&Z(Oe=>{const lt={...Oe};return Ae===Hi(f,Me)?delete lt[Me]:lt[Me]=Ae,lt}),Rf(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:_c,hasRequiredVersionDaemons:ka,appVersion:Rc,versionBannerDismissed:Pc,setVersionBannerDismissed:Dc,upgradingDaemons:Ec,handleBannerUpgrade:$c}=tp({ides:f,sendDaemonCommand:e}),Sa=o.useCallback(fe=>{me(fe.tabKey),i(Ae=>{const Me=new URLSearchParams(Ae),ue=_d(fe);return ue?Me.set("activeTab",ue):Me.delete("activeTab"),Me},{replace:!0})},[i]),Na=o.useCallback(fe=>{tt(fe.tabKey),Sa(fe)},[Sa,tt]),Bc=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(hu,{wsStatus:h,showReconnected:v}),t.jsx(xu,{terminalBackend:Ge,isStandalone:De,machineLabel:Qe,machineKey:Ze}),(!Pc||ka)&&t.jsx(Tf,{daemons:_c,targetVersion:Rc,required:ka,upgradingDaemons:Ec,onUpgrade:$c,onDismiss:()=>Dc(!0)}),t.jsx(kf,{showMobileChatMode:Yt,isMobile:N,activeConv:je,chatIdes:pt,wsStatus:h,isConnected:C,onOpenHistory:fe=>{fe&&_e(fe),D(!0)},onOpenRemote:Te,onStopCli:Mc,activeCliViewMode:Tc,onSetActiveCliViewMode:Lc,mobileChatConversations:Ft,ides:f,actionLogs:oe,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:F,isStandalone:De,initialDataLoaded:w,userName:u.userName,requestedMobileTabKey:Ee,onRequestedMobileTabConsumed:ze,requestedMachineId:m,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:B,setGroupActiveTabIds:A,groupTabOrders:T,setGroupTabOrders:L,toggleHiddenTab:mt,visibleConversations:Ve,hiddenConversations:rr,requestedDesktopTabKey:Q,onRequestedDesktopTabConsumed:ze,onDesktopActiveTabChange:me,onHideConversation:Bc,onShowHiddenConversation:Na,onShowAllHiddenConversations:xt,scrollToBottomRequest:$,machineEntries:Ue,onBrowseMachineDirectory:nr,onSaveMachineWorkspace:bc,onLaunchMachineIde:gc,onLaunchMachineProvider:yc,onListMachineSavedSessions:vc,notifications:kt,notificationUnreadCount:Nt,notificationStateBySessionId:Tt,onMarkNotificationRead:q,onMarkNotificationUnread:Ke,onDeleteNotification:ft,onMarkNotificationTargetRead:Re}),t.jsx("style",{children:`
|
|
60
|
-
body { overflow: hidden; overscroll-behavior: none; }
|
|
61
|
-
`}),t.jsx(Mf,{historyModalOpen:I,historyTargetConv:$e,ides:f,isHistoryCreatingChat:kc,isHistoryRefreshingHistory:Be?!1:Sc,savedHistorySessions:Le,isSavedHistoryLoading:Ie,isResumingSavedHistorySessionId:de,onCloseHistory:()=>D(!1),onNewHistoryChat:Cc,onSwitchHistorySession:Nc,onRefreshHistory:Be?en:Ic,onResumeSavedHistorySession:Ac,remoteDialogConv:_,remoteDialogIdeEntry:Y,connectionStates:P,actionLogs:oe,localUserMessages:be,sendDaemonCommand:e,setLocalUserMessages:se,setActionLogs:F,isStandalone:De,userName:u.userName,onOpenRemoteHistory:fe=>{fe&&_e(fe),D(!0)},onRemoteConversationChange:_e,onCloseRemoteDialog:Pe,cliStopDialogOpen:E,cliStopTargetConv:X,onCancelCliStop:()=>{W(!1),we(null)},onStopCliNow:async()=>{W(!1),await ja("hard",X),we(null)},onSaveCliAndStop:async()=>{W(!1),await ja("save",X),we(null)},toasts:y,onDismissToast:fe=>M(Ae=>Ae.filter(Me=>Me.id!==fe)),onClickToast:fe=>{if(fe.targetKey){const Ae=bt(fe.targetKey);Ae&&(x(z.get(Ae.tabKey)??0),Na(Ae),ye({tabKey:Ae.tabKey,nonce:Date.now()}))}},showOnboarding:d,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function Df({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,m]=o.useState(null),[p,u]=o.useState(null),[f,w]=o.useState(!1),[S,M]=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,D,E=!1)=>{c(W=>[...W.slice(-100),{timestamp:Date.now(),level:I,message:D}]),setTimeout(()=>{var W;return(W=a.current)==null?void 0:W.scrollIntoView({behavior:"smooth"})},100),E&&ot.showToast(D,I==="error"||I==="warn"?"warning":"success")},[a]),j=o.useCallback(I=>{const D=I instanceof Error?I.message:String(I||"");return D.includes("P2P command timeout")||D.includes("P2P not connected")||D.includes("P2P not available")},[]),k=o.useCallback(async(I,D)=>{var E;if(!e||l)return!1;m(I),v("info",`Launching ${at(I)}${D!=null&&D.workspace?` in ${D.workspace}`:""}...`);try{const W={ideType:I,enableCdp:!0};(E=D==null?void 0:D.workspace)!=null&&E.trim()?W.workspace=D.workspace.trim():D!=null&&D.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{m(null)}},[e,l,v,r]),g=o.useCallback(async I=>{if(!e)return{success:!1};const{cliType:D,dir:E,workspaceId:W,useDefaultWorkspace:X,useHome:we,argsStr:Le,model:ie,resumeSessionId:Ie}=I;if(!D)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const te=Le?Le.split(/\s+/).filter(Boolean):void 0,de=(E==null?void 0:E.trim())||(W?"(saved id)":X?"(default workspace)":we?"(home)":"");v("info",`Launching ${D}${de?` in ${de}`:""}${ie?` (model: ${ie})`:""}...`),u(D);try{const ae={cliType:D,cliArgs:te,initialModel:ie||void 0};E!=null&&E.trim()?ae.dir=E.trim():W?ae.workspaceId=W:X?ae.useDefaultWorkspace=!0:we&&(ae.useHome=!0),Ie&&(ae.resumeSessionId=Ie);const xe=await r(e,"launch_cli",ae),oe=(xe==null?void 0:xe.result)||xe;return xe!=null&&xe.success?(v("info",`${D} 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: ${(xe==null?void 0:xe.error)||(oe==null?void 0:oe.error)}`,!0),(xe==null?void 0:xe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&M({cliType:D,argsStr:Le,model:ie}),{success:!1,sessionId:oe==null?void 0:oe.sessionId})}catch(ae){return j(ae)?(v("warn",`${D} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(v("error",`Launch error: ${ae.message}`,!0),{success:!1})}finally{u(null)}},[e,v,j,r]),x=o.useCallback(async(I,D,E,W)=>e?I?D.trim()?g({cliType:I,dir:D,argsStr:E,model:W}):(M({cliType:I,argsStr:E,model:W}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,g]),B=o.useCallback(async(I,D,E)=>{if(e&&window.confirm(`Stop ${I}?
|
|
62
|
-
This will terminate the process.`))try{const W=await r(e,"stop_cli",{cliType:I,dir:D,targetSessionId:E});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(D){v("error",`Restart failed: ${D.message}`,!0)}},[v,r]),T=o.useCallback(async I=>{if(window.confirm(`Stop ${at(I.type)}?
|
|
63
|
-
This will disconnect CDP and optionally kill the process.`))try{const D=await r(I.daemonId,"stop_ide",{ideType:I.type,killProcess:!0});D!=null&&D.success?v("info",`${at(I.type)} stopped`,!0):v("error",`Stop failed: ${(D==null?void 0:D.error)||"Unknown error"}`,!0)}catch(D){v("error",`Stop failed: ${D.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 D=await r(e,"workspace_add",{path:I.trim()});return D!=null&&D.success?(v("info",`Workspace added: ${I.trim()}`),!0):(v("error",(D==null?void 0:D.error)||"workspace_add failed"),!1)}catch(D){return v("error",D.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 D=await r(e,"workspace_remove",{id:I});D!=null&&D.success?v("info","Workspace removed",!0):v("error",(D==null?void 0:D.error)||"workspace_remove failed",!0)}catch(D){v("error",D.message,!0)}finally{w(!1)}}},[e,v,r]),N=o.useCallback(async I=>{var D;if(e){w(!0);try{const E=await r(e,"workspace_set_default",I===null?{clear:!0}:{id:I});if(E!=null&&E.success){v("info",I?"Default workspace updated":"Default workspace cleared",!0);const W=typeof E.defaultWorkspacePath=="string"?E.defaultWorkspacePath:"";W&&((D=C.current)==null||D.call(C,W))}else v("error",(E==null?void 0:E.error)||"workspace_set_default failed",!0)}catch(E){v("error",E.message,!0)}finally{w(!1)}}},[e,v,r]),U=o.useCallback(async I=>{var E;if(!e||!I.trim())return;const D=I.trim();w(!0);try{const W=await r(e,"workspace_set_default",{path:D});W!=null&&W.success?(v("info","Default workspace set from history"),(E=C.current)==null||E.call(C,D)):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:M,editingNickname:d,setEditingNickname:b,nicknameInput:y,setNicknameInput:h,addLog:v,handleLaunchIde:k,runLaunchCliCore:g,handleLaunchCli:x,handleStopCli:B,handleRestartIde:A,handleStopIde:T,handleDetectIdes:L,handleWorkspaceAdd:O,handleWorkspaceRemove:R,handleWorkspaceSetDefault:N,handleWorkspaceResumePath:U,handleSaveNickname:G,setOnDefaultWorkspaceChanged:P}}function Ef({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var A;const{workspaceBusy:l,handleWorkspaceAdd:m,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=i,[f,w]=o.useState(!1),[S,M]=o.useState(""),[d,b]=o.useState([]),[y,h]=o.useState(!1),[C,P]=o.useState(""),v=o.useCallback(async T=>{h(!0),P("");try{const L=await Qr(c,e,T);M(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 T=[...r.map(O=>O.workspace),...n.map(O=>O.workspace),...a.map(O=>O.workspace)],L=Xr(s.platform,Yr(T,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,B=((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(Vo,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Gl(s.uptime):"Waiting…"}),t.jsx(cr,{icon:t.jsx(At,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(cr,{icon:t.jsx(Ur,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(cr,{icon:t.jsx(fl,{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(Wa,{value:k?Math.min(Math.round(B/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:k?`${B.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(Wa,{value:x,max:100,label:"Memory",color:"#3b82f6",detail:k?`${an(s.totalMem-g)} / ${an(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${an(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(Ns,{size:14})," Workspaces"]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[t.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),t.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:l,value:s.defaultWorkspaceId||"",onChange:T=>void u(T.target.value===""?null:T.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(T=>t.jsx("option",{value:T.id,children:T.label||T.path},T.id))]}),s.defaultWorkspacePath&&t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:l,onClick: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(T=>t.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[T.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:Gr(T.path,T.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:T.path,children:T.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void p(T.id),children:"Remove"})]},T.id))})]}),f&&t.jsx(Jr,{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:T=>{v(T)},onConfirm:T=>{(async()=>{if(!T)return;await m(T)&&w(!1)})()}})]})}function $f(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 Bf(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(m=>m.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 Sn(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 Io(e){if(!e||typeof e!="object")return null;if(Sn(e))return e;const s=e,r=s.result;return Sn(r)?r:Sn(s.sourceConfig)?s.sourceConfig:null}function Kf(e){const s=e.trim();return s||null}const Ao=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Wf=[{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 Of({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[m,p]=o.useState([]),[u,f]=o.useState(""),[w,S]=o.useState([]),[M,d]=o.useState(""),b=o.useRef(null),y=o.useRef(null),h=g=>{p(x=>x.includes(g)?x.filter(B=>B!==g):[...x,g])},C=()=>p([...Ao]),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(m.length!==0){i("running"),S(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${m.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),d("");try{const g=await r(e,"provider_auto_fix",{providerType:s.type,functions:m,agent:c,...u?{comment:u}:{}});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:Wf.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:Ao.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:m.includes(g)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:m.includes(g)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:m.includes(g)?"#a78bfa":"var(--text-secondary)"},children:[m.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:u,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})]}),M&&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:M})]})]}),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"&&m.length>0&&`${m.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:m.length===0,className:"machine-btn",style:{background:m.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:m.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:m.length>0?"#a78bfa":void 0,opacity:m.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 Hf({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)||""),[m,p]=o.useState(""),[u,f]=o.useState(""),[w,S]=o.useState(!1),[M,d]=o.useState(""),[b,y]=o.useState(!1),h=j=>{const k=j.toLowerCase().replace(/[^a-z0-9-]/g,"");p(k),(!u||u===C(m))&&f(C(k))},C=j=>j.split("-").map(k=>k.charAt(0).toUpperCase()+k.slice(1)).join(" "),P=async()=>{if(!(!m||!u||!c)){S(!0),d("");try{const j=await r(e,"provider_clone",{type:m,name:u,category:"ide",location:"user",cloneFrom:c});j!=null&&j.success||j!=null&&j.created?(y(!0),a==null||a(m)):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:m})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",m,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",m]})," 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:m,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/",m||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:u,onChange: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"})]}),M&&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:M})]})}),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:!m||!u||w,className:"machine-btn",style:{background:m&&u?"rgba(34,197,94,0.12)":void 0,borderColor:m&&u?"rgba(34,197,94,0.3)":void 0,color:m&&u?"#86efac":void 0,opacity:!m||!u||w?.4:1},children:w?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Uf({machineId:e,providers:s,sendDaemonCommand:r}){var A;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,m]=o.useState(null),[p,u]=o.useState("all"),[f,w]=o.useState(null),[S,M]=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 T=await r(e,"get_provider_source_config",{}),L=Io(T);L&&(b(L),h(L.sourceMode),P(L.explicitProviderDir||""))}catch{}},[e,r]),g=o.useCallback(async()=>{if(e){c(!0);try{const T=await r(e,"get_provider_settings",{}),L=$f(T);if(L){const O=Bf(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(T,L,O)=>{m(`${T}.${L}`),a(R=>R.map(N=>N.type===T?{...N,values:{...N.values,[L]:O}}:N));try{const R=await r(e,"set_provider_setting",{providerType:T,key:L,value:O});R!=null&&R.success||g()}catch{g()}m(null)},B=async()=>{j(!0);try{const T=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Kf(C)}),L=Io(T);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(T=>t.jsx("button",{onClick:()=>u(T),className:`machine-btn text-[10px] px-2 py-0.5 ${p===T?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:T.toUpperCase()},T))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>M(!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:T=>h(T.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:T=>P(T.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void B(),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(T=>T.category===p).length>1&&(()=>{const T=n.filter(N=>N.category===p),L=new Map;for(const N of T)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===T.length);if(O.length===0)return null;const R=async(N,U)=>{for(const G of T)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 (",T.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(T=>p==="all"||T.category===p).map(T=>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:T.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:T.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:T.category==="acp"?"rgba(139,92,246,0.08)":T.category==="cli"?"rgba(59,130,246,0.08)":T.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:T.category==="acp"?"#a78bfa":T.category==="cli"?"#60a5fa":T.category==="ide"?"#86efac":"var(--status-warning)"},children:T.category}),T.category==="ide"&&t.jsx("button",{onClick:()=>w(s.find(L=>L.type===T.type)||{type:T.type,name:T.displayName,displayName:T.displayName,icon:T.icon,category:T.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:T.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===`${T.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(T.type,L.key,!(T.values[L.key]??L.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:T.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:T.values[L.key]??L.default?21:3}})}):L.type==="number"?t.jsx("input",{type:"number",value:Number(T.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(T.type,L.key,R)},className:"machine-input w-20 text-center text-[11px]"}):L.type==="select"&&L.options?t.jsx("select",{value:String(T.values[L.key]??L.default??""),onChange:O=>x(T.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(T.values[L.key]??L.default??""),onBlur:O=>x(T.type,L.key,O.target.value),className:"machine-input w-[120px] text-[11px]"})})]},L.key))})]},T.type))}),f&&t.jsx(Of,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>w(null)}),S&&t.jsx(Hf,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>M(!1),onCreated:()=>{M(!1),g()}})]})}const Ff=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function zf({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Vf(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Mo(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 Gf({machineId:e,sendDaemonCommand:s}){const[r,n]=o.useState([]),[a,i]=o.useState([]),[c,l]=o.useState([]),[m,p]=o.useState(0),[u,f]=o.useState(0),[w,S]=o.useState(!0),[M,d]=o.useState("debug"),[b,y]=o.useState("all"),h=o.useRef(null),C=o.useRef(!1),P=Vf(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:M,since:m}),s(e,"get_debug_trace",zf({count:120,since:u,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(T=>[...T,...x.logs.map(O=>({timestamp:O.ts,level:O.level,message:`[${O.category}] ${O.message}`}))].slice(-300));const A=Math.max(...x.logs.map(T=>T.ts));p(A)}const B=(g==null?void 0:g.result)||g;if(g!=null&&g.success&&Array.isArray(B==null?void 0:B.trace)){i(B.trace.slice(-120));const A=B.trace.reduce((T,L)=>Math.max(T,Number(L.ts||0)),u);A>u&&f(A)}}catch{}l(Ss.list({limit:120}))};v();const j=setInterval(v,3e3);return()=>clearInterval(j)},[e,w,m,u,M,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 ${M===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),Ss.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:Ff.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:Mo(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:Mo(v.payload)})]},v.id))]})]}),t.jsx("div",{ref:h})]})}function Nn(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Cn(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 qf(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Yf(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 Qf({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,m]=o.useState(!1),p=Ki(e,{enabled:!!e,includeSessions:!0,limit:12,intervalMs:8e3}),u=p.diagnostics,f=p.loading,w=p.applyDiagnostics,S=o.useMemo(()=>pf({diagnostics:u,loading:f,refreshing:l,error:n}),[u,f,l,n]),M=o.useMemo(()=>new Map(s.map(A=>[A.sessionId||A.id,A])),[s]),d=o.useCallback(async()=>{if(e){m(!0);try{const A=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:12}),T=Nn(A);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");w(T.diagnostics||T.result||null),a("")}catch(A){const T=A instanceof Error?A.message:"Could not load hosted runtime diagnostics";a(T)}finally{m(!1)}}},[w,e,r]);o.useEffect(()=>{!e||u||f||l||d()},[u,f,e,d,l]);const b=o.useCallback(async(A,T)=>{const L=`${A}:${T.sessionId}`;if(!(A==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
|
|
66
|
-
This will terminate the hosted runtime.`))){c(L);try{const O=await r(e,A,{sessionId:T.sessionId}),R=Nn(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}: ${T.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 T=await r(e,"session_host_prune_duplicate_sessions",{}),L=Nn(T);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(T){const L=T instanceof Error?T.message:"Duplicate prune failed";ot.showToast(L,"warning"),a(L)}finally{c(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,d,r]),h=o.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((A,T)=>(T.lastActivityAt||0)-(A.lastActivityAt||0)),[u==null?void 0:u.sessions]),C=o.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:fc(h),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,h]),P=C.liveRuntimes,v=C.recoverySnapshots,j=C.inactiveRecords,k=o.useMemo(()=>Xf(P),[P]),g=o.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),x=o.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(A=>A.level==="warn"||A.level==="error")||null,[u==null?void 0:u.recentLogs]),B=(A,T)=>{var E;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=wa(A.meta),U=M.get(A.sessionId),G=A.attachedClients.length===1?"1 client":`${A.attachedClients.length} clients`,I=T==="recovery"?"Recover":"Resume",D=hc(T);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children: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 ${Yf(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:((E=A.writeOwner)==null?void 0:E.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:qf(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(Xn,{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: ",D]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="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"}),T==="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:ku()})]}),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(Rs,{size:13}),f||l?"Refreshing…":"Refresh"]})]})]}),n&&!u&&t.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(ds,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children: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:u.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:To(u.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Cn(u.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(ds,{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:[Cn(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(Ur,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:ks("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=>B(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:ks("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=>B(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:ks("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:j.map(A=>B(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 T=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:(T==null?void 0:T.displayName)||((L=M.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:Cn(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:u.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function Jf({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 In({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 An({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 Zf({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),m=r.slice(0,4),u=Vs(e,"0.8.71");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(In,{icon:t.jsx(Ht,{size:13}),children:"Current Chats"}),t.jsx(An,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(f=>{const w=On(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:zr(w)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:ps(f)})]},f.tabKey)})})})]}),m.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(In,{icon:t.jsx(Vo,{size:13}),children:"Recent Launches"}),t.jsx(An,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:m.map(f=>{const{metaText:w,updatedLabel:S}=Zi(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(In,{icon:t.jsx(ds,{size:13}),children:"Daemon Update"}),t.jsx(An,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:u?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:u?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),t.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[t.jsx(Rs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function eh(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function th(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const sh={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 jr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function rh(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 Mn({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:m,initialWorkspacePath:p}){const u=_s(),{handleLaunchIde:f,handleStopCli:w,handleRestartIde:S,handleStopIde:M,handleDetectIdes:d,launchingIde:b,launchingAgentType:y,addLog:h}=c,[C,P]=o.useState(null),v=o.useCallback(_=>{_&&u(eh(_))},[u]),j=sh[e],k=e==="ide",g=e==="acp",x=o.useMemo(()=>n.filter(_=>_.category===e&&(e==="ide"||_.installed!==!1)),[e,n]),B=o.useMemo(()=>new Map(x.map(_=>[_.type,_.displayName||_.type])),[x]),[A,T]=o.useState(""),[L,O]=o.useState(""),[R,N]=o.useState([]),[U,G]=o.useState(""),[I,D]=o.useState(""),[E,W]=o.useState([]),[X,we]=o.useState(!1),[Le,ie]=o.useState(""),[Ie,te]=o.useState(!1),[de,ae]=o.useState(()=>gt()),[xe,oe]=o.useState(null),[F,be]=o.useState(p?"__custom__":m||s.defaultWorkspaceId||""),[se,pe]=o.useState(p||""),[Z,le]=o.useState([]),[ne,ge]=o.useState(!1),[me,$]=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&&be(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(p){be("__custom__"),pe(p);return}m&&(be(m),pe(""))},[m,p]),o.useEffect(()=>{k||A&&(x.some(_=>_.type===A)||(T(""),D("")))},[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 Qr(l,r,_);$(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;be("__custom__"),ge(!0);const _=a.map(re=>re.workspace),Y=Xr(s.platform,Yr(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=>jr(_e.path)===jr(Y));if(re){be(re.id),pe("");return}be("__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=>jr(_e.path)===jr(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]),Tt=o.useMemo(()=>{if(e!=="cli"||!A)return null;const _=B.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,B,ce,I,A]),q=o.useCallback(_=>{if(e==="ide"||!_){N([]);return}N(mc(r,_))},[e,r]);o.useEffect(()=>{if(D(""),q(A),e!=="cli"||!A){W([]),ie(""),we(!1);return}Nt(A)},[e,q,Nt,A]);const Ke=o.useMemo(()=>E.find(_=>_.providerSessionId===I)||null,[E,I]);o.useEffect(()=>{if(!I)return;const _=E.find(Y=>Y.providerSessionId===I);_!=null&&_.canResume||D("")},[E,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",`${B.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,B]),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 Te=(_==null?void 0:_.argsStr)??L;!k&&(Te!=null&&Te.trim())&&(pc(r,Y,Te),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=ji(k?"ide":g?"acp":"cli",!k&&!g&&!!I),We=ki(k?"ide":g?"acp":"cli",!k&&!g&&!!I),je=()=>{var Te;const _=k?at(A):B.get(A)||A,Y=!k&&!g&&!!I,{options:re,selectedKey:_e}=cs({machine:s,currentWorkspaceId:F&&F!=="__custom__"?F:null,currentWorkspacePath:ce});Re({title:Y?la(_):rs("start-fresh",_),description:Y?da():ns("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:((Te=E.find(Pe=>Pe.providerSessionId===I))==null?void 0:Te.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?(be(Pe.workspaceId),pe("")):Pe!=null&&Pe.workspacePath?(be("__custom__"),pe(Pe.workspacePath)):(be(""),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?M(_):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){rh(_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(be(Y),Y==="__custom__"&&l){bt();return}Y!=="__custom__"&&pe("")},className:"px-3 py-1.5 rounded-md min-w-[200px] flex-1 text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",children:(s.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(s.workspaces||[]).map(_=>t.jsxs("option",{value:_.id,children:[_.id===s.defaultWorkspaceId?"⭐ ":"",Gr(_.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,Te=Z.includes(_.type||_.id||""),Pe=A===(_.type||"");return t.jsxs("button",{onClick:()=>{if(_e&&Y){const $e=Y.sessionId;$e?u(`/dashboard?activeTab=${encodeURIComponent($e)}`,{state:{openRemoteForTabKey:$e}}):u("/dashboard",{state:{openRemoteForTabKey:Y.id}});return}Te||T($e=>$e===(_.type||"")?"":_.type||"")},disabled:!!b||Te,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${_e?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Pe?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:b&&b!==_.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:i(_.type)}),re&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${_e?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.name||at(_.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${_e?"text-green-400":Te?"text-orange-400":Pe?"text-accent-primary":"text-text-muted"}`,children:_e?"Open Session":Te?"Starting...":Pe?"Configure":"Select"})]})]},_.type)}):t.jsxs("div",{className:"col-span-full py-6 flex flex-col items-center justify-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted italic gap-2",children:["No IDEs detected.",t.jsxs("button",{onClick:d,className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded-lg flex items-center gap-1.5",children:[t.jsx(ll,{size:14})," Scan System"]})]}):x.length>0?x.map(_=>{const Y=A===_.type,re=Z.includes(_.type),Te=!!a.find(Pe=>Pe.type===_.type&&wt(Pe.status)!=="stopped");return t.jsxs("button",{onClick:()=>T(Pe=>Pe===_.type?"":_.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Y?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:_.icon}),Te&&t.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${re?"text-orange-400":Y?"text-accent-primary":"text-text-muted"}`,children:re?"Starting...":Y?"Configure":"Select"})]})]},_.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),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):B.get(A)||A})]}),ze,!k&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!g&&e==="cli"&&t.jsx(xc,{busy:!!y||!!b||Z.includes(A),savedSessionsLoading:X,savedSessionsError:Le,selectedSession:Ke,onRefresh:()=>void Nt(A),onOpenHistory:()=>{A&&(te(!0),Nt(A))},onClearSelection:()=>D("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[g&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:U,onChange:_=>G(_.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:L,onChange:_=>O(_.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),R.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:R.map(_=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>O(_),title:_,children:_},_))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick: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(_):B.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 Te;(Te=navigator.clipboard)==null||Te.writeText(`adhdev attach ${re.runtimeKey}`),P(re.runtimeKey||null),window.setTimeout(()=>{P(Pe=>Pe===re.runtimeKey?null:Pe)},1200)},children:C===re.runtimeKey?"Copied":"Copy"})]}),re.runtimeWriteOwner&&t.jsx("span",{style:{color:re.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:re.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:th(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 Te=_.sessionId;if(Te){u(`/dashboard?activeTab=${encodeURIComponent(Te)}`,{state:{openRemoteForTabKey:Te}});return}u("/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 Te=_.workspace||"",{options:Pe,selectedKey:$e}=cs({machine:s,currentWorkspacePath:Te});Re({title:rs("restart-ide",at(_.type)),description:ns("restart-ide"),confirmLabel:Ts("restart-ide"),busyLabel:Ls("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!==Te){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(Rs,{size:14})})]}),g&&t.jsx("button",{onClick:()=>{const Te=_.sessionId;Te&&v(Te)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!_.sessionId,children:t.jsx(Ht,{size:14})}),re&&_e!=="stopped"&&t.jsxs(t.Fragment,{children:[re.mode&&t.jsx(oa,{mode:re.mode,onChange:Te=>void Ee(re,Te,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Te=_.sessionId;Te&&v(Te)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!_.sessionId,children:re.mode==="chat"?t.jsx(Ht,{size:14}):t.jsx(At,{size:13})})]}),_e==="stopped"?t.jsx("button",{onClick:()=>{const Te=_.workspace||"",Pe=k?at(_.type):ve(_),{options:$e,selectedKey:Be}=cs({machine:s,currentWorkspacePath:Te});Re({title:rs("restart-stopped",Pe),description:ns("restart-stopped"),confirmLabel:Ts("restart-stopped"),busyLabel:Ls("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(Jn,{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(Te=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Zo(Te.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Te.name," · ",wt(Te.status)]},Te.id))}),Y&&(H[Y.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(H[Y.type]||[]).map(Te=>t.jsxs("button",{disabled:V===`${Y.type}.${Te.type}`,onClick:async()=>{const Pe=`${Y.type}.${Te.type}`;ee(Pe);try{await l(r,"set_ide_extension",{ideType:Y.type,extensionType:Te.type,enabled:!Te.enabled}),z($e=>({...$e,[Y.type]:($e[Y.type]||[]).map(Be=>Be.type===Te.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 ${Te.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Te.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Te.name,t.jsx("span",{className:"text-[9px] font-normal",children:Te.enabled?"ON":"OFF"})]},Te.type))})]})]},_.id)})]}),ne&&l&&t.jsx(Jr,{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:()=>ge(!1),onNavigate:_=>{Je(_)},onConfirm:_=>{pe(_),be("__custom__"),ge(!1)}}),Ge&&t.jsx(ya,{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&&Tt&&t.jsx(ua,{activeConv:Tt,ides:[],isCreatingChat:!1,isRefreshingHistory:X,savedSessions:E,isSavedSessionsLoading:X,isResumingSavedSessionId:xe,savedHistoryFilters:de,onSavedHistoryFiltersChange:ae,onClose:()=>te(!1),onNewChat:()=>{D(""),te(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Nt(A)},onResumeSavedSession:_=>{if(!_.canResume||xe)return;const Y=kt(_);D(_.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 Lo=[{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 nh({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:m="ide",initialWorkspaceId:p,initialWorkspacePath:u,sendDaemonCommand:f}){var d;const[w,S]=o.useState(m);o.useEffect(()=>{S(m)},[m]);const M=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:Lo.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:M[b.id]})]},b.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(d=Lo.find(b=>b.id===w))==null?void 0:d.helper})]}),w==="ide"&&t.jsx(Mn,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:u}),w==="cli"&&t.jsx(Mn,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:u}),w==="acp"&&t.jsx(Mn,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:f,initialWorkspaceId:p,initialWorkspacePath:u})]})}function ah({onNicknameSynced:e}={}){var F,be,se,pe,Z,le,ne,ge,me;const{id:s}=zc(),r=_s(),n=qn(),{sendCommand:a}=Mt(),i=tr(),c=hi(),l=c.ides||[],m=c.initialLoaded??!0,p=l.find($=>$.id===s&&$.type==="adhdev-daemon"),u=l.some($=>$.type==="adhdev-daemon"),[f,w]=o.useState("workspace"),[S,M]=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]),fm(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:15e3});const g=()=>{if(u){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},x=Df({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 B=(p==null?void 0:p.availableProviders)||[],A={};for(const $ of B)A[$.type]=$.icon;const T=$=>A[$]||"",L=p?{id:p.id,hostname:ei(p,{fallbackId:p.id}),platform:((F=p.machine)==null?void 0:F.platform)||"unknown",arch:((be=p.machine)==null?void 0:be.arch)||"",cpus:((se=p.machine)==null?void 0:se.cpus)||0,totalMem:((pe=p.machine)==null?void 0:pe.totalMem)||0,freeMem:(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:(ge=p.machine)==null?void 0:ge.uptime,release:((me=p.machine)==null?void 0:me.release)||"",cdpConnected:!!p.cdpConnected,machineNickname:p.machineNickname||null,p2p:p.p2p?{screenshotActive:!1,...p.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:p.detectedIdes||[],workspaces:p.workspaces||[],defaultWorkspaceId:p.defaultWorkspaceId??p.activeWorkspaceId??null,defaultWorkspacePath:p.defaultWorkspacePath??p.activeWorkspacePath??null}:null,O=l.filter($=>$.daemonId===s&&$.type!=="adhdev-daemon").filter($=>!Qs($)&&!ws($)).map($=>({id:$.id,sessionId:$.sessionId,type:$.type,version:$.version||"",instanceId:$.instanceId||"",status:$.status,workspace:$.workspace||null,terminals:$.terminals||0,aiAgents:ed($.aiAgents||($.agents||[]).map(ye=>({id:ye.name,name:ye.name,status:ye.status,version:ye.version}))),activeChat:$.activeChat||null,chats:$.chats||[],childSessions:$.childSessions||[],cdpConnected:$.cdpConnected||!1,daemonId:s})),R=l.filter($=>$.daemonId===s&&Qs($)).map($=>({id:$.id,sessionId:$.sessionId,type:$.type,cliName:$.cliName||$.type,status:$.status,workspace:$.workspace||"",activeChat:$.activeChat||null,providerSessionId:$.providerSessionId,mode:$.mode,runtimeKey:$.runtimeKey,runtimeDisplayName:$.runtimeDisplayName,runtimeWorkspaceLabel:$.runtimeWorkspaceLabel,runtimeWriteOwner:$.runtimeWriteOwner||null,runtimeAttachedClients:$.runtimeAttachedClients||[],daemonId:s})),N=l.filter($=>$.daemonId===s&&ws($)).map($=>({id:$.id,sessionId:$.sessionId,type:$.type,acpName:$.cliName||$.type,status:$.status,workspace:$.workspace||"",activeChat:$.activeChat||null,providerSessionId:$.providerSessionId,daemonId:s})),U=p?It(p,{fallbackId:s}):"",G="workspace",I=n.state,D=I==null?void 0:I.initialMachineTab,E=I==null?void 0:I.initialWorkspaceCategory,W=I==null?void 0:I.initialWorkspaceId,X=I==null?void 0:I.initialWorkspacePath,we=D==="ides"||D==="clis"||D==="acps"?"workspace":D||G,Le=D==="ides"?"ide":D==="clis"?"cli":D==="acps"?"acp":E,ie=[...O.map($=>{var ye,he,ke,J,Se;return{id:`ide:${$.type}:${$.workspace||""}`,label:((ye=$.activeChat)==null?void 0:ye.title)||$.type,kind:"ide",providerType:$.type,subtitle:$.workspace||void 0,workspace:$.workspace||void 0,lastLaunchedAt:((Se=(J=(ke=(he=$.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($=>{var ye,he,ke,J,Se;return{id:`cli:${$.type}:${$.workspace||""}`,label:((ye=$.activeChat)==null?void 0:ye.title)||$.cliName,kind:"cli",providerType:$.type,providerSessionId:$.providerSessionId,subtitle:$.workspace||void 0,workspace:$.workspace||void 0,lastLaunchedAt:((Se=(J=(ke=(he=$.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($=>{var ye,he,ke,J,Se;return{id:`acp:${$.type}:${$.workspace||""}`,label:((ye=$.activeChat)==null?void 0:ye.title)||$.acpName,kind:"acp",providerType:$.type,providerSessionId:$.providerSessionId,subtitle:us($.summaryMetadata)||$.workspace||void 0,workspace:$.workspace||void 0,lastLaunchedAt:((Se=(J=(ke=(he=$.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(($,ye)=>(ye.lastLaunchedAt||0)-($.lastLaunchedAt||0)),Ie=((p==null?void 0:p.recentLaunches)||[]).length>0?((p==null?void 0:p.recentLaunches)||[]).map($=>({id:$.id,label:$.title||$.providerName||$.providerType,kind:$.kind,providerType:$.providerType,providerSessionId:$.providerSessionId,subtitle:us($.summaryMetadata)||$.workspace||void 0,workspace:$.workspace,summaryMetadata:$.summaryMetadata,lastLaunchedAt:$.lastLaunchedAt})):ie,te=o.useMemo(()=>{var ye;const $=((ye=c.connectionStates)==null?void 0:ye[s||""])||void 0;return l.filter(he=>he.daemonId===s&&he.type!=="adhdev-daemon").flatMap(he=>ma(he,{},{connectionStates:s&&$?{[s]:$}:void 0,defaultConnectionState:$})).filter(he=>!(he.transport==="pty"&&he.mode==="terminal")).sort((he,ke)=>On(ke)-On(he))},[l,c.connectionStates,s]),de=o.useCallback($=>{const ye=$.sessionId||$.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)}))},[]),xe=o.useCallback($=>{if(!L)return;const{options:ye,selectedKey:he}=cs({machine:L,currentWorkspacePath:$.workspace}),ke=async()=>{M($.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($.kind==="ide"&&$.providerType){await x.handleLaunchIde($.providerType,Se?{workspace:Se}:void 0);return}if(($.kind==="cli"||$.kind==="acp")&&$.providerType){await x.runLaunchCliCore({cliType:$.providerType,dir:Ue?void 0:Se||"",workspaceId:Ue||void 0,model:$.kind==="acp"&&si($.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:$.providerSessionId});return}await ke()},h.current=he,P(he),y({title:$.kind==="ide"?rs("restart-ide",$.label):$.providerSessionId?la($.label):rs("start-fresh",$.label),description:$.kind==="ide"?ns("restart-ide"):$.providerSessionId?da():ns("start-fresh"),confirmLabel:$.kind==="ide"?Ts("restart-ide"):$.providerSessionId?Er(!0):Ts("start-fresh"),busyLabel:$.kind==="ide"?Ls("restart-ide"):$.providerSessionId?ia(!0):Ls("start-fresh"),workspaceOptions:ye,details:[{label:"Mode",value:$.kind.toUpperCase()},...$.providerType?[{label:"Provider",value:$.providerType}]:[]]})},[x,L]);if(o.useEffect(()=>{w(we)},[G,we,s]),o.useEffect(()=>{Le&&M(Le)},[Le,s]),!L)return m?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick: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(Hr,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(dl,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(il,{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:$=>x.setNicknameInput($.target.value),onKeyDown:$=>{$.key==="Enter"&&x.handleSaveNickname(),$.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($=>t.jsxs("button",{onClick:()=>w($.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===$.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[$.label,$.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===$.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:$.count})]},$.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(Zf,{machineEntry:p,providers:B,recentLaunches:Ie,currentConversations:te,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:xe,onOpenConversation:de}),t.jsx(nh,{machine:L,machineId:s,providers:B,ideSessions:O,cliSessions:R,acpSessions:N,actions:x,getIcon:T,initialCategory:S,initialWorkspaceId:W,initialWorkspacePath:X,sendDaemonCommand:a})]}),f==="providers"&&t.jsx(Uf,{machineId:s,providers:B,sendDaemonCommand:a}),f==="overview"&&t.jsx(Ef,{machineId:s,machine:L,ideSessions:O,cliSessions:R,acpSessions:N,actions:x,sendDaemonCommand:a}),f==="session-host"&&t.jsx(Qf,{machineId:s,cliSessions:R,sendDaemonCommand:a}),f==="logs"&&t.jsx(Gf,{machineId:s,sendDaemonCommand:a})]})})}),x.launchPick&&L&&t.jsx(Jf,{machine:L,launchPick:x.launchPick,actions:x}),b&&t.jsx(ya,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:$=>{h.current=$,P($)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:v,onConfirm:ae,onCancel:()=>{d.current=null,y(null)}}),t.jsx(Si,{toasts:c.toasts||[],onDismiss:$=>c.setToasts(ye=>ye.filter(he=>he.id!==$)),onClickToast:$=>{$.targetKey&&r(`/dashboard?activeTab=${encodeURIComponent($.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 oh{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 oh;function ih(){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 kr=ih(),_o=3e3,ch=3e4;let $t=null,lh=0;const Or=new Map;let Zt=null,qs=null;function Ro(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function Hs(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function dh(e){return e==="connected"?"connected":e}async function Tr(e,s,r){const n=Du(e,r||{}),a=$t;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++lh}_${Date.now()}`;return new Promise((c,l)=>{const m=setTimeout(()=>{Or.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);Or.set(i,{resolve:p=>{clearTimeout(m),c(p)},reject:p=>{clearTimeout(m),l(p)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function zn(e,s){const r=$t;if(!r||r.readyState!==WebSocket.OPEN)return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class uh{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 mh(e){return(!_t||_t.daemonId!==e)&&(_t=new uh(e)),_t}function ph({children:e}){const s=o.useRef(_r()),r=_r();s.current=r;const{setUserName:n}=ls(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),m=o.useCallback((d,b)=>{l(d),qs==null||qs(d,b)},[]),p=o.useRef(null),u=o.useRef(),f=o.useRef(_o),w=o.useRef(!0),S=o.useRef(!1),M=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;m("connecting"),console.log(`[Standalone WS] Connecting to ${kr}...`),Hs("connect_attempt",{url:kr,reason:M.current,delayMs:f.current});let y;try{y=new WebSocket(kr)}catch(P){console.error("[Standalone WS] Failed to create WebSocket:",P),b();return}p.current=y,y.onopen=()=>{if(!w.current){y.close();return}m("connected"),f.current=_o,Hs("open",{url:kr,reason:M.current}),Gt.resubscribeAll({sendData:zn}),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=Or.get(k.requestId);g&&(Or.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:B,getIdes:A}=s.current,T=g.instanceId||"standalone",L=A().find(N=>N.id===T),O=mh(T);Kt.register(T,O),Kt.setState(T,"connected"),m("connected",T),Kt.emitStatus(T,g);const R=Dr(g,{daemonId:T,existingDaemon:L,existingEntries:A()});Ro("ws_status",{type:k.type,daemonId:T,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}))}),Ro("entries",{daemonId:T,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:[T]}),B(),c.current!==T&&((j=i.current)==null||j.call(i),c.current=T,i.current=Gt.subscribe({sendData:zn},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},N=>{if(N.topic!=="daemon.metadata")return;const U=s.current.getIdes(),G=U.find(D=>D.id===T),I=Dr(N.status,{daemonId:T,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"),m("disconnected"),p.current=null,M.current=`close:${P.code}${P.wasClean?":clean":":unclean"}`,Hs("close",{code:P.code,reason:P.reason||"",wasClean:P.wasClean}),b())},y.onerror=P=>{S.current||!w.current||(M.current="error",Hs("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(u.current);const y=f.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),Hs("schedule_reconnect",{reason:M.current,delayMs:y}),u.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,ch),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(u.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 fh({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(qs=(c,l)=>{r(c),l&&a(l)},()=>{qs=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=dh(s),m={};return n&&(m[n]=l),m.standalone=l,{wsStatus:s,isConnected:c,connectionStates:m}},[s,n]);return t.jsx(Zc,{connectionOverrides:i,children:t.jsx(ph,{children:e})})}const hh=[{id:"dashboard",path:"/dashboard",icon:t.jsx(Oo,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Ot,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(Hr,{}),label:"Settings"}];function xh({children:e}){const s=_s(),r=qn(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=u=>{s(u),a(!1)},m=()=>{c(u=>{const f=!u;try{localStorage.setItem("sidebar-collapsed",f?"1":"0")}catch{}return f})},p=u=>`nav-item${r.pathname.startsWith(u)?" 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:u=>u.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:hh.map(u=>t.jsxs("div",{className:p(u.path),id:`nav-${u.id}`,onClick:()=>l(u.path),title:i?u.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:u.icon}),!i&&u.label]},u.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(Ho,{})}),!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(Uo,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.71"]}),t.jsx(qu,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:m,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 bh=[{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(Fo,{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(Xs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Ho,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],gh=[{icon:t.jsx(pl,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(Oo,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Fr,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(ol,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(Xn,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(cl,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],yh=[{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 vh(){return t.jsxs(Ti,{icon:t.jsx(Uo,{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.71"]}),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:bh.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:Ii.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Mi.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Ai.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:gh.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:yh.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(Li,{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(kl,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function wh(){const{ides:e}=ls(),s=e.find(f=>f.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Mt(),{userName:a}=ls(),[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)},[m,p]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),u=f=>{p(f);try{localStorage.setItem("adhdev_sound",f?"1":"0")}catch{}};return t.jsxs(Ti,{icon:t.jsx(Hr,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Hu,{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.71"]}),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(Ju,{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(sm,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI."}),t.jsx(dm,{})]}),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(mm,{})]})]})}),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(Yu,{}),t.jsx(es,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(jl,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:m,onChange:u})]})}),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(al,{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()}})]})})})]})}Gu();cm();const jh=Ko({baseUrl:""});function Po(){const{ides:e,initialLoaded:s}=ls();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(_n,{to:`/machines/${r.id}`,replace:!0}):t.jsx(_n,{to:"/dashboard",replace:!0})}function kh(){const e=o.useMemo(()=>({sendCommand:Tr,sendData:zn}),[]);return t.jsx(Vc,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(sl,{client:jh,children:t.jsx(fh,{children:t.jsx(nl,{value:e,children:t.jsx(xh,{children:t.jsxs(Gc,{children:[t.jsx(Qt,{path:"/dashboard",element:t.jsx(Pf,{})}),t.jsx(Qt,{path:"/machine",element:t.jsx(Po,{})}),t.jsx(Qt,{path:"/machines/:id",element:t.jsx(ah,{})}),t.jsx(Qt,{path:"/machines",element:t.jsx(Po,{})}),t.jsx(Qt,{path:"/about",element:t.jsx(vh,{})}),t.jsx(Qt,{path:"/settings",element:t.jsx(wh,{})}),t.jsx(Qt,{path:"*",element:t.jsx(_n,{to:"/dashboard",replace:!0})})]})})})})})})}lu({connectionManager:Kt});qc(document.getElementById("root")).render(t.jsx(kh,{}));
|