@adhdev/daemon-standalone 0.8.93 → 0.8.94
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 +229 -112
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-42XeBRt-.js +79 -0
- package/public/assets/index-DHunFxdM.css +1 -0
- package/public/index.html +2 -2
- package/public/assets/index-B0yfK9dM.css +0 -1
- package/public/assets/index-BX2fAu2N.js +0 -79
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-2SYILvaH.js","assets/vendor-BRZ4K-AC.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var hd=Object.defineProperty;var xd=(e,s,r)=>s in e?hd(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var qe=(e,s,r)=>xd(e,typeof s!="symbol"?s+"":s,r);import{r as o,j as t,M as Ra,a as _a,b as Wi,c as Hi,u as Vs,R as at,d as pr,t as bd,e as gd,D as yd,f as ma,g as pa,h as Pa,i as vd,k as wd,B as jd,l as kd,m as cs,N as fa,n as Sd}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 Nd(e={}){const s=Math.max(1,Math.floor(e.capacity||200)),r=[];return{record(n){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...n,payload:n.payload?{...n.payload}:{}};return r.push(a),r.length>s&&r.splice(0,r.length-s),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(i=>!n.interactionId||i.interactionId===n.interactionId).filter(i=>!n.topic||i.topic===n.topic).filter(i=>!n.kind||i.kind===n.kind).slice(-a).map(i=>({...i,payload:i.payload?{...i.payload}:{}}))},clear(){r.splice(0,r.length)}}}const Ks=Nd();function To(e){const s={};for(const r of e)r.transport&&(s[r.transport]=(s[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:s}}function Cd(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function ha(e,s){if(!e)return s??null;if(!s)return e??null;const r=Array.isArray(e.messages)&&e.messages.length>0?e.messages:s.messages,n=e.activeModal||(e.status==="waiting_approval"?s.activeModal:null);return{...s,...e,messages:r,activeModal:n,inputContent:e.inputContent??s.inputContent}}function ar(e,s){const r=Cd(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerSessionId:e.providerSessionId??(s==null?void 0:s.providerSessionId),providerName:r??(s==null?void 0:s.providerName)??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerName??e.providerType,title:e.title??(s==null?void 0:s.title)??r??(s==null?void 0:s.providerName)??e.providerName??e.providerType,workspace:e.workspace??(s==null?void 0:s.workspace)??null,mode:e.mode??(s==null?void 0:s.mode),capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??(s==null?void 0:s.capabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),activeChat:ha(e.activeChat,s==null?void 0:s.activeChat),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),summaryMetadata:e.summaryMetadata??(s==null?void 0:s.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash),unread:e.unread??(s==null?void 0:s.unread),lastSeenAt:e.lastSeenAt??(s==null?void 0:s.lastSeenAt),inboxBucket:e.inboxBucket??(s==null?void 0:s.inboxBucket),completionMarker:e.completionMarker??(s==null?void 0:s.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(s==null?void 0:s.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(s==null?void 0:s.surfaceHidden),resume:e.resume??(s==null?void 0:s.resume),runtimeKey:e.runtimeKey??(s==null?void 0:s.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(s==null?void 0:s.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(s==null?void 0:s.runtimeWorkspaceLabel)}}function Lo(e,s){if(!(s!=null&&s.length))return e;if(!(e!=null&&e.length))return s;const r=new Map(e.map(n=>[n.id,n]));return s.map(n=>{const a=r.get(n.id);return a?ar(n,a):n})}const Fi=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}),Ui=o.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ro(e){var r,n;let s=0;return e.activeChat!==void 0&&(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 Dn(e,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=s.version??r.version??e.version,i=s.serverVersion??e.serverVersion??r.serverVersion,c=s.versionMismatch===!0||e.versionMismatch===!0,l=s.versionUpdateRequired===!0||e.versionUpdateRequired===!0,u=s.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),i&&(n.serverVersion=i),u&&(n.versionUpdateReason=u),a&&i&&a===i?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((s.versionMismatch===!0||c&&a&&i&&a!==i)&&(n.versionMismatch=!0),l&&(n.versionUpdateRequired=!0),n)}function ln(e){return Array.isArray(e)?e.map(ln):!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,ln(r)]))}function Id(e,s){try{return JSON.stringify(ln(e))===JSON.stringify(ln(s))}catch{return!1}}function Rr(e,s,r){return Id(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function Ad(e,s,r){var f,d,x,g,w,M,m;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(p=>({...p,_lastUpdate:n}));const i=new Map;for(const p of s)i.set(p.id,p);for(const p of e){const b=i.get(p.id);if(!b){i.set(p.id,{...p,_lastUpdate:n});continue}const h=Ro(p),S=Ro(b);if(h>S){const R=(f=p.chats)!=null&&f.length?p.chats:b.chats,k=Lo(b.childSessions,p.childSessions),I=ha(p.activeChat,b.activeChat),j=Dn(b,p,{...b,...p,chats:R,childSessions:k,activeChat:I,_lastUpdate:n});i.set(p.id,Rr(b,j,n))}else if(h<S){const R={};if(p.status&&p.status!==b.status&&(R.status=p.status),p.cdpConnected!==void 0&&(R.cdpConnected=p.cdpConnected),(d=p.chats)!=null&&d.length&&!((x=b.chats)!=null&&x.length)&&(R.chats=p.chats),p.title!==void 0&&(R.title=p.title),p.workspace!==void 0&&(R.workspace=p.workspace),p.providerSessionId!==void 0&&(R.providerSessionId=p.providerSessionId),p.parentSessionId!==void 0&&(R.parentSessionId=p.parentSessionId),p.sessionKind!==void 0&&(R.sessionKind=p.sessionKind),p.sessionCapabilities!==void 0&&(R.sessionCapabilities=p.sessionCapabilities),p.controlValues!==void 0&&(R.controlValues=p.controlValues),p.providerControls!==void 0&&(R.providerControls=p.providerControls),p.summaryMetadata!==void 0&&(R.summaryMetadata=p.summaryMetadata),p.lastMessagePreview!==void 0&&(R.lastMessagePreview=p.lastMessagePreview),p.lastMessageRole!==void 0&&(R.lastMessageRole=p.lastMessageRole),p.lastMessageAt!==void 0&&(R.lastMessageAt=p.lastMessageAt),p.lastMessageHash!==void 0&&(R.lastMessageHash=p.lastMessageHash),p.lastUpdated!==void 0&&(R.lastUpdated=p.lastUpdated),p.unread!==void 0&&(R.unread=p.unread),p.lastSeenAt!==void 0&&(R.lastSeenAt=p.lastSeenAt),p.inboxBucket!==void 0&&(R.inboxBucket=p.inboxBucket),p.completionMarker!==void 0&&(R.completionMarker=p.completionMarker),p.seenCompletionMarker!==void 0&&(R.seenCompletionMarker=p.seenCompletionMarker),p.surfaceHidden!==void 0&&(R.surfaceHidden=p.surfaceHidden),p.runtimeKey!==void 0&&(R.runtimeKey=p.runtimeKey),p.runtimeDisplayName!==void 0&&(R.runtimeDisplayName=p.runtimeDisplayName),p.runtimeWorkspaceLabel!==void 0&&(R.runtimeWorkspaceLabel=p.runtimeWorkspaceLabel),p.runtimeWriteOwner!==void 0&&(R.runtimeWriteOwner=p.runtimeWriteOwner),p.runtimeAttachedClients!==void 0&&(R.runtimeAttachedClients=p.runtimeAttachedClients),p.machineNickname!==void 0&&p.machineNickname!==b.machineNickname&&(R.machineNickname=p.machineNickname),p.version!==void 0&&(R.version=p.version),p.serverVersion!==void 0&&(R.serverVersion=p.serverVersion),p.versionMismatch===!0&&(R.versionMismatch=!0),Object.keys(R).length>0){const k=Dn(b,p,{...b,...R,_lastUpdate:n});i.set(p.id,Rr(b,k,n))}else Rr(b,{...b,_lastUpdate:n},n)}else{const R=p.timestamp||n,k=b._lastUpdate||b.timestamp||0;if(R>=k){const I=(g=p.chats)!=null&&g.length?p.chats:b.chats,j=Lo(b.childSessions,p.childSessions),v=ha(p.activeChat,b.activeChat),y=Dn(b,p,{...b,...p,chats:I,childSessions:j,activeChat:v,_lastUpdate:n});i.set(p.id,Rr(b,y,n))}else(w=p.chats)!=null&&w.length&&!((M=b.chats)!=null&&M.length)&&i.set(p.id,{...b,chats:p.chats})}}const c=new Set(e.map(p=>p.id)),l=new Set,u=new Set;for(const p of e){const b=p.daemonId||((m=p.id)==null?void 0:m.split(":")[0]);b&&l.add(b),b&&p.type!=="adhdev-daemon"&&u.add(b)}for(const[p,b]of i){const h=b.daemonId||p.split(":")[0];if(!l.has(h))continue;if(a.has(h)&&!c.has(p)){i.delete(p);continue}const S=n-(b._lastUpdate||b.timestamp||0);(b.transport==="pty"&&u.has(h)&&!c.has(p)&&S>1e4||b.transport==="acp"&&u.has(h)&&!c.has(p)&&S>1e4||b.transport==="cdp-page"&&u.has(h)&&!c.has(p)&&S>3e4)&&i.delete(p)}for(const[p,b]of i){const h=b.daemonId||p.split(":")[0];if(l.has(h)&&b.transport&&!u.has(h))continue;n-(b._lastUpdate||b.timestamp||0)>3e5&&b.status!=="online"&&i.delete(p)}return Array.from(i.values())}function Md(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 Td({children:e,connectionOverrides:s}){const[r,n]=o.useState([]),[a,i]=o.useState(!1),[c,l]=o.useState([]),[u,f]=o.useState(void 0),d=o.useRef(r);o.useEffect(()=>{d.current=r},[r]);const x=o.useCallback((b,h)=>{n(S=>{let R=!1;const k=S.map(I=>I.id!==b||I.chats===h?I:(R=!0,{...I,chats:h}));return R?k:S})},[]),g=o.useCallback((b,h)=>{n(S=>{const R=S.length===0?b:Ad(b,S,h),k=!Md(S,R);return k&&Ks.record({kind:"dashboard.entries_applied",payload:{incoming:To(b),next:To(R)}}),k?R:S})},[]),w=o.useCallback(()=>i(!0),[]),M=o.useMemo(()=>({injectEntries:g,markLoaded:w,getIdes:()=>d.current}),[g,w]),m=s,p=o.useMemo(()=>({ides:r,updateRouteChats:x,initialLoaded:a,toasts:c,setToasts:l,wsStatus:(m==null?void 0:m.wsStatus)??"connected",isConnected:(m==null?void 0:m.isConnected)??!0,connectionStates:(m==null?void 0:m.connectionStates)??{},connectionTransports:(m==null?void 0:m.connectionTransports)??{},showReconnected:(m==null?void 0:m.showReconnected)??!1,retryConnection:m==null?void 0:m.retryConnection,isP2PActive:(m==null?void 0:m.isP2PActive)??!1,p2pStates:(m==null?void 0:m.p2pStates)??{},userRole:m==null?void 0:m.userRole,userName:u,setUserName:f}),[r,x,a,c,m==null?void 0:m.wsStatus,m==null?void 0:m.isConnected,m==null?void 0:m.connectionStates,m==null?void 0:m.connectionTransports,m==null?void 0:m.showReconnected,m==null?void 0:m.retryConnection,m==null?void 0:m.isP2PActive,m==null?void 0:m.p2pStates,m==null?void 0:m.userRole,u]);return t.jsx(Ui.Provider,{value:M,children:t.jsx(Fi.Provider,{value:p,children:e})})}function js(){return o.useContext(Fi)}function fr(){return o.useContext(Ui)}function zi(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function a(l){return l.startsWith("http")?l:`${s}${l.startsWith("/")?"":"/"}${l}`}function i(l){const u=r==null?void 0:r(),f=a(l),d=l.startsWith("http")?new URL(f):new URL(f,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!l.startsWith("http")&&!s?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function c(l,u={}){const f={"Content-Type":"application/json",...u.headers||{}},d=r==null?void 0:r();d&&(f.Authorization=`Bearer ${d}`);const x=a(l),g=new AbortController,w=setTimeout(()=>g.abort(),15e3);try{const M=await fetch(x,{...u,headers:f,signal:g.signal});if(M.status===401)throw n==null||n(),new Error("Unauthorized");if(!M.ok){const m=await M.json().catch(()=>({error:M.statusText}));throw new Error(m.error||`API Error: ${M.status}`)}return M.json()}finally{clearTimeout(w)}}return{getDaemons:()=>c("/api/v1/daemons"),getDaemonStatus:l=>c(`/api/v1/daemons/${l}/status`),sendCommand:(l,u,f={})=>c(`/api/v1/daemons/${l}/command`,{method:"POST",body:JSON.stringify({type:u,payload:f})}),execTerminal:(l,u,f)=>c(`/api/v1/daemons/${l}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:f})}),sendAgentMessage:(l,u,f)=>c(`/api/v1/shortcuts/${l}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:f})}),getAgentStatus:l=>c(`/api/v1/shortcuts/${l}/status`),approveAgent:(l,u,f)=>c(`/api/v1/shortcuts/${l}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:f?"approve":"reject"})}),getMuxState:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/state`),getMuxSocketInfo:l=>c(`/api/v1/mux/${encodeURIComponent(l)}/socket-info`),controlMux:(l,u,f={})=>c(`/api/v1/mux/${encodeURIComponent(l)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:f})}),getMuxEventsUrl:l=>i(`/api/v1/mux/${encodeURIComponent(l)}/events`),getRuntimeEventsUrl:l=>i(`/api/v1/runtime/${encodeURIComponent(l)}/events`),request:c}}const Ld=zi({baseUrl:"http://localhost:3847"}),Rd=o.createContext(Ld);function _d({client:e,children:s}){return t.jsx(Rd.Provider,{value:e,children:s})}const Pd={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Vi=o.createContext(Pd);function Dd({value:e,children:s}){return t.jsx(Vi.Provider,{value:e,children:s})}function Tt(){return o.useContext(Vi)}function Ed(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)s^=n.charCodeAt(a),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function $d(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Gi(e){return e?Ed([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),$d(e.content)]):""}const He={size:18};function qi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Da({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 Zt({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 Ea({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 Kd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Bd({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 Yi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"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 Od({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 gn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Xi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Wd({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 es({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 Pt({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 $a({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 Hd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Bs({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function Gs({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"23 4 23 10 17 10"}),t.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function ks({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function 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("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 Ji({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),t.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Qi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),t.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),t.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Zi({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Fd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 yn({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Ud({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Ka({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 zd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function At({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Vd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Gd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"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 qd({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 Yd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 vn({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 Xd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 Jd({size:e=He.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Qd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Zd({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 eu({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 tu({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 su({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("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 ru({size:e=He.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}function nu({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 au({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 ou({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 iu({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 _o(e){return!!e&&typeof e=="object"&&"text"in e}function Ba(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:_o(i)?String(i.text||""):"").join(r):_o(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Os(e){return Ba(e,{normalizeWhitespace:!0})}const En=new Map;function Po(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function cu(e){if(!Array.isArray(e)||e.length===0)return"0:empty";const s=e[e.length-1];return`${e.length}:${Gi(s)}`}function Do(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function ec(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function lu(e,s,r){return Number(e.receivedAt||r[Rs(e,s)]||0)||0}function tc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function du(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function _r(e,s){if(!e)return s;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||s}catch{return e.split(/[\\/]/).filter(Boolean).pop()||s}}function $n(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 Eo(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):tc(e)?t.jsx(Ra,{remarkPlugins:[_a,Wi,Hi],children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function Pr({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:Eo(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=$n(r);return a?t.jsx("img",{src:a,alt:_r(r.uri,"image"),className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):null}if(r.type==="audio"){const a=$n(r);return a?t.jsx("audio",{controls:!0,src:a,className:"max-w-full"},`audio-${n}`):null}if(r.type==="video"){const a=$n(r);return a?t.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"},`video-${n}`):r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:_r(r.uri,"video")},`video-link-${n}`):null}if(r.type==="resource_link")return r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:r.name||_r(r.uri,"resource")},`resource-link-${n}`):null;if(r.type==="resource"&&r.resource){const a=_r(r.resource.uri,"resource");if(r.resource.text)return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[t.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),Eo(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 Rs(e,s){const r=e,n=Ba(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 uu=o.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(Ra,{remarkPlugins:[_a],children:s.text}),t.jsx("span",{className:"action-time",children:ec(s.timestamp)})]})},(e,s)=>e.log===s.log),mu=o.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:i,isTextExpanded:c,onToggleTextExpanded:l}){var I,j,v;const u=(s.role||"").toLowerCase(),f=u==="user"||u==="human",d=s.kind||(u==="tool"?"tool":"standard"),x=du(s.content)?s.content:null,g=!!(x!=null&&x.some(y=>y.type!=="text")),w=Ba(s.content,{joiner:`
|
|
4
|
-
`});if(d==="thought"){const y=typeof((I=s.meta)==null?void 0:I.label)=="string"?s.meta.label:"Thought";return t.jsxs("div",{className:"self-start chat-msg-thought",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx(qd,{size:13}),t.jsx("span",{children:y})]}),t.jsx("div",{className:"chat-msg-body",children:w})]})}if(d==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),g&&x?t.jsx("div",{className:"tool-text w-full",children:t.jsx(Pr,{parts:x,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(d==="terminal"){const y=(j=s.meta)!=null&&j.isRunning?"⏳":"✅",E=typeof((v=s.meta)==null?void 0:v.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal",children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:y}),t.jsx("span",{children:E})]}),g&&x?t.jsx("div",{className:"chat-msg-body",children:t.jsx(Pr,{parts:x,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:w})]})}if(d==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:g&&x?t.jsx(Pr,{parts:x,renderAsPreformatted:!1}):w.slice(0,100)});const M=s.meta,p=(typeof(M==null?void 0:M.renderMode)=="string"?M.renderMode.trim():"")==="preformatted",b=w,h=!1,S=b,R=p,k=!R&&tc(S);return t.jsx("div",{className:`max-w-[88%] min-w-0 flex flex-col gap-1 ${f?"self-end":"self-start"}`,children:(b||g||f)&&t.jsxs("div",{className:`chat-bubble ${f?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${b||g?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:f?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:ec(r)})]}),(b||g)&&t.jsx("div",{className:"chat-markdown",children:g&&x?t.jsx(Pr,{parts:x,renderAsPreformatted:R}):R?t.jsx("pre",{className:"chat-preformatted",children:S}):k?t.jsx(Ra,{remarkPlugins:[_a,Wi,Hi],children:S}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:S})}),h]})})},(e,s)=>e.message===s.message&&e.receivedAt===s.receivedAt&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isTextExpanded===s.isTextExpanded),pu=o.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:i=!1,isWorking:c=!1,contextKey:l="",receivedAtMap:u={},emptyState:f,onLoadMore:d,isLoadingMore:x,hasMoreHistory:g,hiddenLiveCount:w=0,loadError:M,scrollToBottomRequestNonce:m},p){const b=o.useRef(null),h=o.useRef(null),S=o.useRef(null),R=o.useRef(0),k=o.useRef(""),I=o.useRef(!1),j=o.useRef(null),v=o.useRef(!1),y=o.useRef(null),E=o.useRef(!1),[L,A]=o.useState(new Set),_=o.useRef(!1),B=o.useRef(!1),H=()=>{const X=b.current;return X?X.scrollHeight-X.scrollTop-X.clientHeight<200:!0},C=o.useCallback((X="auto")=>{const pe=b.current;pe&&pe.scrollTo({top:pe.scrollHeight,behavior:X})},[]),P=o.useCallback(()=>{var ue;const X=b.current,pe=(ue=window.getSelection)==null?void 0:ue.call(window);if(!X||!pe||pe.rangeCount===0||pe.isCollapsed){E.current=!1;return}const Y=pe.anchorNode,J=pe.focusNode;E.current=!!(Y&&J&&X.contains(Y)&&X.contains(J))},[]),U=cu(s),N=o.useCallback(()=>{const X=b.current;!X||!l||En.set(l,{top:X.scrollTop,fromBottom:Math.max(0,X.scrollHeight-X.scrollTop-X.clientHeight),messageFingerprint:U})},[l,U]),$=o.useCallback((X="auto")=>{j.current!=null&&cancelAnimationFrame(j.current),j.current=requestAnimationFrame(()=>{j.current=null,C(X)})},[C]);o.useEffect(()=>{const X=!I.current,pe=k.current!==l;if(k.current=l,X||pe){if(I.current=!0,_.current=!1,v.current=!0,!E.current){const J=l?En.get(l):null;J&&Po(J,U)?requestAnimationFrame(()=>{const ue=b.current;ue&&(Do(ue,J),B.current=!0)}):$("auto")}R.current=s.length;return}s.length>R.current?!_.current&&!E.current&&$("auto"):H()&&!_.current&&!E.current&&$("auto"),R.current=s.length},[U,l,c,s.length,$]),o.useEffect(()=>{m&&(_.current=!1,v.current=!0,B.current=!0,y.current!=null&&window.clearTimeout(y.current),y.current=window.setTimeout(()=>{v.current=!1,y.current=null},180),E.current||$("auto"))},[$,m]),o.useEffect(()=>()=>{N(),j.current!=null&&cancelAnimationFrame(j.current),y.current!=null&&window.clearTimeout(y.current)},[N]),o.useEffect(()=>{const X=h.current;if(!X)return;const pe=()=>{y.current!=null&&window.clearTimeout(y.current),y.current=window.setTimeout(()=>{v.current=!1,y.current=null},180)},Y=new ResizeObserver(()=>{v.current&&(E.current||($("auto"),pe()))});return Y.observe(X),()=>{Y.disconnect(),y.current!=null&&(window.clearTimeout(y.current),y.current=null)}},[$,l]),o.useImperativeHandle(p,()=>({scrollToBottom:(X="smooth")=>{C(X)}}),[C]),o.useEffect(()=>{const X=b.current;if(!X)return;let pe;const Y=()=>{clearTimeout(pe),pe=setTimeout(()=>{_.current=!H(),N()},50)};return X.addEventListener("scroll",Y,{passive:!0}),()=>{X.removeEventListener("scroll",Y),clearTimeout(pe)}},[N]),o.useEffect(()=>(document.addEventListener("selectionchange",P),()=>document.removeEventListener("selectionchange",P)),[P]);const z=o.useRef(0),q=o.useRef(!1);o.useEffect(()=>{const X=b.current;if(!X||!q.current||z.current===0)return;const pe=X.scrollHeight-z.current;pe>0&&(X.scrollTop=pe),N(),z.current=0,q.current=!1},[s.length,N]),o.useEffect(()=>{if(B.current||!l)return;const X=En.get(l),pe=b.current;if(!(!X||!pe)){if(!Po(X,U)){C("auto"),B.current=!0;return}Do(pe,X),B.current=!0}},[l,U,s.length,C]);const W=()=>{const X=b.current;X&&(z.current=X.scrollHeight),q.current=!0,d==null||d()},ne=o.useMemo(()=>{const X=s.map((ue,le)=>({type:"message",data:ue,index:le,ts:lu(ue,le,u)}));if(!r||r.length===0)return X;const pe=[...r].sort((ue,le)=>ue.timestamp-le.timestamp).map((ue,le)=>({type:"action",data:ue,index:le,ts:ue.timestamp})),Y=[];let J=0;for(const ue of X){for(;J<pe.length&&ue.ts>0&&pe[J].ts<ue.ts;)Y.push(pe[J++]);Y.push(ue)}for(;J<pe.length;)Y.push(pe[J++]);return Y},[s,r,u]),ae=w>0||!!g,ke=w>0?`↑ Show ${Math.min(w,80)} earlier messages${w>80?` (${w} hidden)`:""}`:M?`↻ ${M}`:"↑ Load older messages";return t.jsx("div",{ref:b,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:h,className:"chat-container-content",children:[x&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),ae&&!x&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{onClick:W,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${M&&w===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:ke})}),ne.length===0&&!ae&&(f||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ne.map(X=>{if(X.type==="action"){const ve=X.data;return t.jsx(uu,{log:ve},`action-${X.index}`)}const pe=X.data,Y=X.index,J=Rs(pe,Y),ue=pe.receivedAt||u[J],le=`${l}-${J}`,V=L.has(le);return t.jsx(mu,{message:pe,receivedAt:ue,agentName:n,userName:a,isCliMode:i,isTextExpanded:V,onToggleTextExpanded:()=>A(ve=>{const ie=new Set(ve);return V?ie.delete(le):ie.add(le),ie})},`msg-${J}`)}),c&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:S})]})})}),fu=o.memo(pu,(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),hu="modulepreload",xu=function(e){return"/"+e},$o={},bu=function(s,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),l=(c==null?void 0:c.nonce)||(c==null?void 0:c.getAttribute("nonce"));a=Promise.allSettled(r.map(u=>{if(u=xu(u),u in $o)return;$o[u]=!0;const f=u.endsWith(".css"),d=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const x=document.createElement("link");if(x.rel=f?"stylesheet":hu,f||(x.as="script"),x.crossOrigin="",x.href=u,l&&x.setAttribute("nonce",l),document.head.appendChild(x),f)return new Promise((g,w)=>{x.addEventListener("load",g),x.addEventListener("error",()=>w(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(c){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=c,window.dispatchEvent(l),!l.defaultPrevented)throw c}return a.then(c=>{for(const l of c||[])l.status==="rejected"&&i(l.reason);return s().catch(i)})};let Ko=!1;const sc=o.forwardRef(({onInput:e,fontSize:s=13,readOnly:r=!1,sizingMode:n="measured"},a)=>{const i=o.useRef(null),[c,l]=o.useState(null),u=o.useRef([]),f=o.useRef(!1),d=o.useRef(!1),x=o.useRef(!1),g=()=>{const w=i.current;if(w){f.current&&(w.clear(),f.current=!1);for(const M of u.current)w.write(M);u.current=[],d.current&&(w.fit(),d.current=!1),x.current&&(w.bumpResize(),x.current=!1)}};return o.useImperativeHandle(a,()=>({write:w=>{i.current?i.current.write(w):u.current.push(w)},clear:()=>{i.current?i.current.clear():(u.current=[],f.current=!0)},reset:()=>{i.current&&typeof i.current.reset=="function"?i.current.reset():(u.current=[],f.current=!0)},resize:(w,M)=>{i.current&&typeof i.current.resize=="function"&&i.current.resize(w,M)},fit:()=>{i.current?i.current.fit():d.current=!0},bumpResize:()=>{i.current?i.current.bumpResize():x.current=!0}}),[]),o.useEffect(()=>{if(!c)return;const w=requestAnimationFrame(()=>{g()});return()=>cancelAnimationFrame(w)},[c]),o.useEffect(()=>{let w=!1;return bu(()=>import("./terminal-2SYILvaH.js"),__vite__mapDeps([0,1,2])).then(M=>{Ko||(Ko=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),w||l(()=>M.GhosttyTerminalView)}).catch(M=>{console.error("[CliTerminal] failed to load terminal renderer",M)}),()=>{w=!0}},[]),c?t.jsx(c,{ref:i,onInput:e,fontSize:s,readOnly:r,sizingMode:n,className:"w-full h-full rounded-lg overflow-hidden"}):t.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});sc.displayName="CliTerminal";function Dr({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 Bo({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 gu({cursorPos:e,viewportRef:s,imgRef:r}){var h;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),i=(h=s.current)==null?void 0:h.getBoundingClientRect();if(!i)return null;const c=n.naturalWidth||a.width,l=n.naturalHeight||a.height,u=c/l,f=a.width/a.height;let d,x,g,w;u>f?(d=a.width,x=a.width/u,g=0,w=(a.height-x)/2):(x=a.height,d=a.height*u,g=(a.width-d)/2,w=0);const M=a.left-i.left+g+d*e.nx,m=a.top-i.top+w+x*e.ny,p=Math.max(8,Math.min(i.width-8,M)),b=Math.max(8,Math.min(i.height-8,m));return t.jsxs("div",{style:{position:"absolute",left:p-8,top:b-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 yu({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:i,imeText:c,setImeText:l,handleImeSubmit:u,isConnActive:f,zoom:d,isMobile:x,mobileFillZoom:g,onZoomOut:w,onZoomReset:M,onZoomIn:m,transportType:p,screenshotUsage:b,lastActionStatus:h}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:S=>S.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[t.jsxs("div",{onClick:s,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[t.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),t.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("div",{onClick:()=>{n(S=>!S),i(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&t.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:t.jsx("input",{type:"text",placeholder:"Type & Enter...",value:c,autoFocus:!0,onTouchStart:S=>S.stopPropagation(),onChange:S=>l(S.target.value),onKeyDown:S=>{u(S)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),t.jsx("div",{className:"relative",children:t.jsx("div",{onClick:()=>{i(S=>!S),n(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⚙️"})})}),t.jsx("div",{className:"w-px h-[18px] bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:f?"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:f?"#22c55e":"#eab308",boxShadow:f?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:f?"#22c55e":"#eab308"},children:f?"Connected":"WS"})]}),d>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),p==="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"}),p==="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"}),b&&b.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:b.budgetExhausted?"#ef4444":"#c4b5fd",background:b.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:b.budgetExhausted?"TURN blocked":`TURN ${b.dailyUsedMinutes}/${b.dailyBudgetMinutes}m`}),h&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:h})]})]}),a&&t.jsxs("div",{onTouchStart:S=>S.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",d<=(x?g:1)+.01?x?"FILL":"FIT":`${Math.round(d*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:S=>{S.stopPropagation(),w()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),t.jsx("button",{onClick:S=>{S.stopPropagation(),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:x?"FILL":"FIT"}),t.jsx("button",{onClick:S=>{S.stopPropagation(),m()},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 vu({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 wu(){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 Oo(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 jr(e,s){const r=o.useRef(null),n=o.useRef(0);o.useEffect(()=>{if(!wu())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,Oo(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,Oo(s[c])]))}),r.current=s})}function ju({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:i,zoomRef:c,panXRef:l,panYRef:u,setPanX:f,setPanY:d,setZoom:x,lastWheelTimeRef:g,onAction:w,setLastActionStatus:M,spawnRippleFromNormalized:m,clampPan:p,isMobile:b,mobileFillZoom:h}){const[S,R]=o.useState(null),k=o.useRef(null),I=o.useRef(null),j=o.useRef(null),v=o.useRef(!1),y=o.useRef(null),E=o.useRef(0),L=o.useRef(null),A=o.useRef(1),_=o.useRef({x:0,y:0}),B=o.useRef(!1),H=o.useRef(n),C=o.useRef(w),P=30,U=550,N=18,$=60,z=400,q=12,W=()=>{if(k.current)return;const ke={nx:.5,ny:.5};k.current=ke,R(ke)};return o.useEffect(()=>{H.current=n,n==="mouse"&&W()},[n]),o.useEffect(()=>{C.current=w},[w]),o.useEffect(()=>{const ke=e.current;if(!ke)return;const X=V=>{if(!r.current)return null;const ve=r.current.getBoundingClientRect();return!ve.width||!ve.height?null:{nx:Math.max(0,Math.min(1,(V.clientX-ve.left)/ve.width)),ny:Math.max(0,Math.min(1,(V.clientY-ve.top)/ve.height))}},pe=(V,ve)=>{if(!r.current)return{dnx:0,dny:0};const ie=r.current,ce=ie.getBoundingClientRect(),te=ie.naturalWidth||ce.width,me=ie.naturalHeight||ce.height,re=te/me,je=ce.width/ce.height;let we,Te;return re>je?(we=ce.width,Te=ce.width/re):(Te=ce.height,we=ce.height*re),{dnx:V/we,dny:ve/Te}},Y=(V,ve,ie)=>{if(ie<=1.05)return;const ce=-(V-.5)*100,te=-(ve-.5)*100,me=p(ce,te,ie);(Math.abs(me.x-l.current)>.1||Math.abs(me.y-u.current)>.1)&&(f(me.x),d(me.y),l.current=me.x,u.current=me.y)},J=V=>{const ve=s.current;if(ve&&V.target instanceof Node&&ve.contains(V.target))V.preventDefault();else return;if(V.touches.length===1){const ie=V.touches[0];I.current={x:ie.clientX,y:ie.clientY,time:Date.now()},j.current={x:ie.clientX,y:ie.clientY},B.current||(v.current=!1),y.current=setTimeout(()=>{if(!v.current&&!B.current)if(v.current=!0,H.current==="mouse"){const ce=k.current||{nx:.5,ny:.5};M("Right Click"),m(ce.nx,ce.ny,"right"),C.current("input_click",{...ce,button:"right"}).catch(()=>{})}else{const ce=X(ie);ce&&(M("Right Click"),m(ce.nx,ce.ny,"right"),C.current("input_click",{...ce,button:"right"}).catch(()=>{}))}},500);return}if(V.touches.length===2){y.current&&clearTimeout(y.current),v.current=!0,B.current=!0;const ie=V.touches[1].clientX-V.touches[0].clientX,ce=V.touches[1].clientY-V.touches[0].clientY;L.current=Math.sqrt(ie*ie+ce*ce),A.current=c.current,_.current={x:(V.touches[0].clientX+V.touches[1].clientX)/2,y:(V.touches[0].clientY+V.touches[1].clientY)/2}}},ue=V=>{const ve=s.current;if(ve&&V.target instanceof Node&&ve.contains(V.target)&&V.preventDefault(),V.touches.length===1&&j.current){const ie=V.touches[0],ce=ie.clientX-j.current.x,te=ie.clientY-j.current.y;if(!v.current&&I.current){const me=ie.clientX-I.current.x,re=ie.clientY-I.current.y;Math.sqrt(me*me+re*re)>8&&(v.current=!0,y.current&&clearTimeout(y.current))}if(v.current)if(H.current==="mouse"){const me=pe(ce,te),re=k.current||{nx:.5,ny:.5},je=Math.max(0,Math.min(1,re.nx+me.dnx)),we=Math.max(0,Math.min(1,re.ny+me.dny));k.current={nx:je,ny:we},R({nx:je,ny:we}),M(`Cursor: ${Math.round(je*100)}%, ${Math.round(we*100)}%`),Y(je,we,c.current);const Te=Date.now();Te-g.current>=30&&(g.current=Te,C.current("input_mouseMoved",{nx:je,ny:we}).catch(()=>{}))}else if(c.current>1){const me=s.current;if(me){const re=me.clientWidth,je=me.clientHeight,we=l.current+ce/re*100,Te=u.current+te/je*100,T=p(we,Te,c.current);f(T.x),d(T.y),l.current=T.x,u.current=T.y}}else{const me=X(ie);if(me){const re=Date.now();re-g.current>=40&&(g.current=re,M("Scroll"),C.current("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(-ce*2.5),deltaY:Math.round(-te*2.5)}).catch(()=>{}))}}j.current={x:ie.clientX,y:ie.clientY};return}if(V.touches.length===2&&L.current!==null){const ie=V.touches[1].clientX-V.touches[0].clientX,ce=V.touches[1].clientY-V.touches[0].clientY,me=Math.sqrt(ie*ie+ce*ce)/L.current,re=(V.touches[0].clientX+V.touches[1].clientX)/2,je=(V.touches[0].clientY+V.touches[1].clientY)/2,we=re-_.current.x,Te=je-_.current.y,T=Math.abs(me-1)>.03;if(H.current==="mouse"){if(T){const fe=Math.max(i,Math.min(5,A.current*me));x(fe),c.current=fe}else if(Math.abs(we)>2||Math.abs(Te)>2){const fe=k.current||{nx:.5,ny:.5},be=Date.now();be-g.current>=30&&(g.current=be,M("Scroll"),C.current("input_wheel",{nx:fe.nx,ny:fe.ny,deltaX:Math.round(-we*3),deltaY:Math.round(-Te*3)}).catch(()=>{}))}}else{const fe=Math.max(i,Math.min(5,A.current*me));x(fe),c.current=fe;const be=s.current;if(be&&fe>1){const Q=be.clientWidth,Se=be.clientHeight,De=l.current+we/Q*100,Oe=u.current+Te/Se*100,$e=p(De,Oe,fe);f($e.x),d($e.y),l.current=$e.x,u.current=$e.y}}_.current={x:re,y:je}}},le=V=>{var ve;if(y.current&&clearTimeout(y.current),L.current=null,V.touches.length===1&&B.current){const ie=V.touches[0];I.current={x:ie.clientX,y:ie.clientY,time:Date.now()},j.current={x:ie.clientX,y:ie.clientY},v.current=!0;return}if(V.touches.length===0){if(B.current){B.current=!1,v.current=!1;return}if(V.changedTouches.length===1){const ie=V.changedTouches[0],ce=Date.now(),te=ce-(((ve=I.current)==null?void 0:ve.time)||0),me=I.current?ie.clientX-I.current.x:0,re=I.current?ie.clientY-I.current.y:0,je=Math.sqrt(me*me+re*re);if(H.current==="mouse"){if(te<P||te>U||je>N){v.current=!1;return}const we=k.current||X(ie);we&&(M(`Click: ${Math.round(we.nx*100)}%, ${Math.round(we.ny*100)}%`),m(we.nx,we.ny,"left"),C.current("input_click",{...we}).catch(()=>{}))}else{if(v.current){v.current=!1;return}if(te<$||te>z||je>q){v.current=!1;return}const we=X(ie);if(!we)return;ce-E.current<300?(M("Double tap"),m(we.nx,we.ny,"double"),C.current("input_click",{...we,clickCount:2}).catch(()=>{}),E.current=0):(M(`Tap: ${Math.round(we.nx*100)}%, ${Math.round(we.ny*100)}%`),m(we.nx,we.ny,"left"),C.current("input_click",{...we}).catch(()=>{}),E.current=ce)}}v.current=!1}};return ke.addEventListener("touchstart",J,{passive:!1}),ke.addEventListener("touchmove",ue,{passive:!1}),ke.addEventListener("touchend",le,{passive:!1}),()=>{ke.removeEventListener("touchstart",J),ke.removeEventListener("touchmove",ue),ke.removeEventListener("touchend",le),y.current&&clearTimeout(y.current)}},[e,s,r,i,c,l,u,f,d,x,g,M,m,p]),{cursorPos:S,cursorPosRef:k,handleToggleInputMode:()=>{a(ke=>{const X=ke==="touch"?"mouse":"touch";return X==="mouse"&&W(),X})},handleZoomReset:()=>{const ke=b?h:1;x(ke),c.current=ke,f(0),d(0),l.current=0,u.current=0}}}function rc({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:i}){const c=o.useRef(null),l=o.useRef(null),u=o.useRef(null),[f,d]=o.useState(null),[x,g]=o.useState(""),[,w]=o.useState(!1),[M,m]=o.useState([]),p=o.useRef(0),[b,h]=o.useState(!1),[S,R]=o.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[I,j]=o.useState(k?"mouse":"touch"),[v,y]=o.useState(1),E=o.useRef(!1),[L,A]=o.useState(1),[_,B]=o.useState(0),[H,C]=o.useState(0);jr("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:I,zoom:L,panX:_,panY:H,isMenuOpen:b,isImeOpen:S});const P=o.useRef(0),U=o.useRef(L),N=o.useRef(_),$=o.useRef(H);o.useEffect(()=>{U.current=L},[L]),o.useEffect(()=>{N.current=_},[_]),o.useEffect(()=>{$.current=H},[H]),o.useEffect(()=>{var te;(te=c.current)==null||te.focus()},[]);const z=r==="connected",q=n,W=z?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ne=z?"The remote stream is warming up":"Waiting for the remote stream to catch up";o.useEffect(()=>{if(!k||E.current||!q)return;const te=u.current,me=l.current;if(!te||!me)return;const re=()=>{const je=me.clientWidth,we=me.clientHeight,Te=te.naturalWidth,T=te.naturalHeight;if(!Te||!T||!je||!we)return;const fe=Math.min(je/Te,we/T),Q=Math.max(je/Te,we/T)/fe;Q>1.01&&(y(Q),A(Q),U.current=Q),E.current=!0};te.complete&&te.naturalWidth?re():te.addEventListener("load",re,{once:!0})},[q,k]);const ae=.5;o.useEffect(()=>{L<=ae&&(B(0),C(0))},[L,ae]);const ke=(te,me,re)=>{if(re<=ae)return{x:0,y:0};const je=(re-1)/(2*re)*100,we=(re-1)/(2*re)*100;return{x:Math.max(-je,Math.min(je,te)),y:Math.max(-we,Math.min(we,me))}},X=(te,me)=>{if(!u.current)return null;const re=u.current.getBoundingClientRect();return!re.width||!re.height?null:{nx:Math.max(0,Math.min(1,(te-re.left)/re.width)),ny:Math.max(0,Math.min(1,(me-re.top)/re.height))}},pe=(te,me,re)=>{const je=l.current;if(!je)return;const we=je.getBoundingClientRect(),Te=++p.current;m(T=>[...T,{id:Te,x:te-we.left,y:me-we.top,type:re}]),setTimeout(()=>m(T=>T.filter(fe=>fe.id!==Te)),600)},Y=(te,me,re)=>{const je=u.current,we=l.current;if(!je||!we)return;const Te=je.getBoundingClientRect(),T=we.getBoundingClientRect(),fe=je.naturalWidth||Te.width,be=je.naturalHeight||Te.height,Q=fe/be,Se=Te.width/Te.height;let De,Oe,$e,Ue;Q>Se?(De=Te.width,Oe=Te.width/Q,$e=0,Ue=(Te.height-Oe)/2):(Oe=Te.height,De=Te.height*Q,$e=(Te.width-De)/2,Ue=0);const ze=Te.left-T.left+$e+De*te,mt=Te.top-T.top+Ue+Oe*me,it=++p.current;m(xt=>[...xt,{id:it,x:ze,y:mt,type:re}]),setTimeout(()=>m(xt=>xt.filter(Ve=>Ve.id!==it)),600)},J=async te=>{var re;const me=X(te.clientX,te.clientY);if(me){d(`Click: ${Math.round(me.nx*100)}%, ${Math.round(me.ny*100)}%`),pe(te.clientX,te.clientY,"left"),(re=c.current)==null||re.focus();try{const je=await e("input_click",{nx:me.nx,ny:me.ny});je!=null&&je.success||s(`❌ Click failed: ${je==null?void 0:je.error}`)}catch(je){s(`❌ Click error: ${je.message||je}`)}}},ue=async(te,me,re,je=0)=>{try{await e("input_key",{type:re?"char":"keyDown",key:te,code:me,text:re?te:void 0,unmodifiedText:re?te:void 0,modifiers:je})}catch(we){s(`❌ Key error: ${we.message||we}`)}},le=async te=>{if(te.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(te.key)&&te.preventDefault();let re=0;te.altKey&&(re|=1),te.ctrlKey&&(re|=2),te.metaKey&&(re|=4),te.shiftKey&&(re|=8),d(`Key: ${te.key}`),await ue(te.key,te.code,te.key.length===1,re)},V=async te=>{if(te.key==="Enter"){if(te.nativeEvent.isComposing)return;if(x){const me=x;g(""),d(`IME Sent: ${me}`);try{const re=await e("input_type",{text:me});re!=null&&re.success||s(`❌ IME error: ${re==null?void 0:re.error}`)}catch(re){s(`❌ IME error: ${re.message}`)}}else d("Key: Enter"),await ue("Enter","Enter",!1)}};o.useEffect(()=>{const te=c.current;if(!te)return;const me=re=>{var je;if((je=u.current)!=null&&je.contains(re.target)){re.preventDefault();const we=Date.now();if(we-P.current<40)return;P.current=we;const Te=X(re.clientX,re.clientY);if(!Te)return;d(`Scroll: ${Math.round(re.deltaY)}`),e("input_wheel",{nx:Te.nx,ny:Te.ny,deltaX:Math.round(re.deltaX),deltaY:Math.round(re.deltaY)}).catch(()=>{})}};return te.addEventListener("wheel",me,{passive:!1}),()=>te.removeEventListener("wheel",me)},[e]);const{cursorPos:ve,handleToggleInputMode:ie,handleZoomReset:ce}=ju({containerRef:c,viewportRef:l,imgRef:u,inputMode:I,setInputMode:j,minZoom:ae,zoomRef:U,panXRef:N,panYRef:$,setPanX:B,setPanY:C,setZoom:A,lastWheelTimeRef:P,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:Y,clampPan:ke,isMobile:k,mobileFillZoom:v});return t.jsxs("div",{ref:c,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:le,onContextMenu:te=>te.preventDefault(),onFocus:()=>w(!0),onBlur:()=>w(!1),tabIndex:0,children:[t.jsxs("div",{ref:l,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[q?t.jsx("img",{ref:u,src:q,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${_}%, ${H}%)`,transformOrigin:"center center",cursor:I==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:J,onContextMenu:te=>te.preventDefault(),onDragStart:te=>te.preventDefault()}):t.jsx(vu,{waitingLabel:W,waitingHint:ne,transportType:i}),I==="mouse"&&q&&t.jsx(gu,{cursorPos:ve,viewportRef:l,imgRef:u}),M.map(te=>{const re={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[te.type];return t.jsxs("div",{style:{position:"absolute",left:te.x,top:te.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${re}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${re}, 0.9)`,boxShadow:`0 0 12px rgba(${re}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},te.id)})]}),t.jsx(yu,{inputMode:I,onToggleInputMode:ie,isImeOpen:S,setIsImeOpen:R,isMenuOpen:b,setIsMenuOpen:h,imeText:x,setImeText:g,handleImeSubmit:V,isConnActive:z,zoom:L,isMobile:k,mobileFillZoom:v,onZoomOut:()=>A(te=>Math.max(.5,te-.25)),onZoomReset:ce,onZoomIn:()=>A(te=>Math.min(5,te+.25)),transportType:i,screenshotUsage:a,lastActionStatus:f}),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 Nt(e){return(typeof e=="string"?e.trim():"")||void 0}function Qt(e,s){const r=Nt(s);return r?`${e}:${r}`:void 0}function ss(e,s,r){const n=Qt(s,r),a=Nt(r);n&&e.push(n),a&&e.push(a)}function _s(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function nc(e){return Nt(e.providerSessionId)||Nt(e.sessionId)||Nt(e.tabKey)||Nt(e.routeId)}function Oa(e){return _s([Nt(e.providerSessionId),Nt(e.sessionId)])}function rs(e){const s=[];return ss(s,"provider",e.providerSessionId),ss(s,"session",e.sessionId),ss(s,"tab",e.tabKey),ss(s,"route",e.routeId),_s(s)}function ku(e){const s=[];return Nt(e.providerSessionId)?(ss(s,"provider",e.providerSessionId),_s(s)):Nt(e.sessionId)?(ss(s,"session",e.sessionId),_s(s)):Nt(e.tabKey)?(ss(s,"tab",e.tabKey),_s(s)):Nt(e.routeId)?(ss(s,"route",e.routeId),_s(s)):[]}function Wa(e){return Qt("provider",e.providerSessionId)||Qt("session",e.sessionId)||Qt("tab",e.tabKey)||Qt("route",e.routeId)||"unknown:"}function kr(e){return Oa(e)[0]}function ac(e){const s=Nt(e.providerSessionId),r=Nt(e.sessionId),n=Nt(e.tabKey),a=Nt(e.routeId),i=[Qt("provider",s),Qt("session",r),Qt("tab",n),Qt("route",a)].filter(u=>typeof u=="string"),c=rs({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),l=Wa({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:l,targetKey:l,targetValue:nc({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:kr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:i,lookupKeys:c}}function xr(e,s){const r=ac(e);return ku(s).some(n=>r.lookupKeys.includes(n))}function wn(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=s,i=Date.now()-e,c=Math.floor(i/1e3);if(c<a)return n;const l=Math.floor(c/60);if(l<60)return`${l}m${r}`;const u=Math.floor(l/60);if(u<24)return`${u}h${r}`;const f=Math.floor(u/24);return f<7?`${f}d${r}`:new Date(e).toLocaleDateString()}const oc=e=>wn(e);function Su(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function qs(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:a}}function Nu(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...Su(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 dn(e,s){if(e.sessionId){const r=s.get(e.sessionId);if(r)return r}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,completionMarker:"",seenCompletionMarker:""}}function jn(e,s,r){const n=dn(e,s),a=qs(e),i=rs(e).map(M=>{var m;return(m=r==null?void 0:r.notificationStateBySessionId)==null?void 0:m.get(M)}).find(M=>!!M),c=a.isReconnecting,l=a.isConnecting,u=a.isGenerating,f=a.isWaiting,d=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||f,x=n.inboxBucket==="working"||u,w=!!(n.inboxBucket==="task_complete"&&(i?i.unreadCount>0:n.unread)&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:w,requiresAction:d,isWorking:x,isReconnecting:c,isConnecting:l,isGenerating:u,isWaiting:f,inboxBucket:d?"needs_attention":x?"working":w?"task_complete":"idle"}}function Cu(e,s,r){return jn(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation,notificationStateBySessionId:r==null?void 0:r.notificationStateBySessionId}).unread}function ic({activeConv:e,onModalButton:s}){const[r,n]=o.useState(null);if(o.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!qs(e).isWaiting||!e.modalButtons)return null;const i=l=>{r||(n(l),s(l))},c=l=>l.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return t.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&t.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[t.jsx(ks,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((l,u)=>{const f=c(l).toLowerCase(),d=/^(run|approve|accept|yes|allow|always)/.test(f),x=/^(reject|deny|delete|remove|abort)/.test(f),g=r===l,w=r!==null;return t.jsx("button",{onClick:()=>i(l),disabled:w,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${d?"font-extrabold":x?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!g?"opacity-40":"opacity-100"} ${w?"cursor-not-allowed":"cursor-pointer"}`,style:d?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:x?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:g?"⏳ ...":c(l)},u)})})]})]})}const Ha="adhdev_controls_bar_visible",xa="adhdev:controlsbarvisibilitychange";function Kn(e){if(!e)return!1;try{return e.getItem(Ha)==="1"}catch{return!1}}function Wo(e,s){if(s)try{s.setItem(Ha,e?"1":"0")}catch{}}function Ho(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(xa,{detail:{visible:e}}))}function cc(){const[e,s]=o.useState(()=>typeof window>"u"?!1:Kn(window.localStorage));o.useEffect(()=>{const a=c=>{const l=c.detail;if(typeof(l==null?void 0:l.visible)=="boolean"){s(l.visible);return}s(Kn(window.localStorage))},i=c=>{c.key===Ha&&s(Kn(window.localStorage))};return window.addEventListener(xa,a),window.addEventListener("storage",i),()=>{window.removeEventListener(xa,a),window.removeEventListener("storage",i)}},[]);const r=o.useCallback(a=>{s(a),typeof window<"u"&&Wo(a,window.localStorage),Ho(a)},[]),n=o.useCallback(()=>{s(a=>{const i=!a;return typeof window<"u"&&Wo(i,window.localStorage),Ho(i),i})},[]);return{isVisible:e,setVisibility:r,toggleVisibility:n}}var Iu=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Au(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function St(e,s){if(Au(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Iu.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 lc(e){return St(e)==="generating"}function ot(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function Mu(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 Bn(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function kn(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 Tu(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 Lu(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Ru(e){return Tu(e.trim().replace(/\.local$/i,""))}function _u(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function dc(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&&!Lu(c));if(r&&r!=="Unknown")return Ru(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function _t(e,s={}){return _u(e)||dc(e,s)}function uc(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 mc(e,s,r={}){const n=String(s).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(i=>String((i==null?void 0:i.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function Ss(e,s){return uc(e).join(" · ")}function br(e){return e.transport==="pty"}function Ps(e){return e.transport==="acp"}function Pu(e,s){var r,n;return(r=s==null?void 0:s.providerLabels)!=null&&r[e]?s.providerLabels[e]:(n=s==null?void 0:s.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?s.providerLabels[e.toLowerCase()]:s!=null&&s.agentName&&s.agentName!==e?s.agentName:ot(e)}function Fo(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),i=(r||"").trim().toLowerCase(),c=ot(r||"").trim().toLowerCase();return n===a||n===i||n===c}function Du(e){return St(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Eu(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=St(n.status);if(!i){s.set(a,{...n,status:c});continue}const l=r.indexOf(i.status||"idle"),u=r.indexOf(c||"idle");u>=0&&(l<0||u<l)&&s.set(a,{...n,status:c})}return Array.from(s.values())}function $u(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function Ku(e){var r,n;const s=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&$u(s.receivedAt)||0}function Bu(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function ba(e){return Math.max(Bu(e),Ku(e.activeChat))}function Ou(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 Fa(e,s){return Ou(ba(e),ba(s),_t(e,{fallbackId:e.id}),_t(s,{fallbackId:s.id}),e.id,s.id)}const pc="adhdev_notification_prefs",Uo={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Wu(){try{const e=localStorage.getItem(pc);if(e){const s=JSON.parse(e);return{...Uo,...s}}}catch{}return{...Uo}}function Hu(e){try{localStorage.setItem(pc,JSON.stringify(e))}catch{}}let Jt=Wu(),Zr=[];function Fu(){Zr.forEach(e=>e())}function Uu(e){Jt={...Jt,...e},Hu(Jt),Fu()}function zu(){const[,e]=o.useState(0);o.useEffect(()=>{const r=()=>e(n=>n+1);return Zr.push(r),()=>{Zr=Zr.filter(n=>n!==r)}},[]);const s=o.useCallback(r=>{Uu(r)},[]);return[{...Jt},s]}function ir(e){if(!Jt.globalEnabled)return!1;switch(e){case"disconnect":return Jt.disconnectAlert;case"completion":return Jt.completionAlert;case"approval":return Jt.approvalAlert;case"browser":return Jt.browserNotifications;default:return!0}}const Vu={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function fc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function hc(){return"Notification"in window&&Notification.permission==="granted"}let ls=null;async function Gu(){if(ls!==null)return ls;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ls=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ls=!!await e.pushManager.getSubscription(),ls):(ls=!1,!1)}catch{return ls=!1,!1}}function ga(e,s,r){if(hc())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 qu(e,s={}){const r={...Vu,...s},n=o.useRef(new Map),a=o.useRef(0),i=o.useRef(null);o.useEffect(()=>{Gu().then(l=>{i.current=l})},[]);const c=o.useCallback((l,u,f)=>{const d=Date.now();d-a.current<r.throttleMs||(a.current=d,ga(l,u,f))},[r.throttleMs]);o.useEffect(()=>{var l;if(!(!r.enabled||!hc())&&ir("browser")&&i.current!==!0){if(document.hasFocus()){for(const u of e)n.current.set(u.id,St(u.status,{activeModal:u.activeModal}));return}for(const u of e){const f=n.current.get(u.id),d=St(u.status,{activeModal:u.activeModal}),x=u.name||u.id;if(r.onApproval&&ir("approval")&&d==="waiting_approval"&&f!=="waiting_approval"){const g=((l=u.activeModal)==null?void 0:l.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,g.slice(0,120),`approval-${u.id}`)}r.onComplete&&ir("completion")&&lc(f)&&d==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${u.id}`),r.onError&&d==="error"&&f!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${u.id}`),n.current.set(u.id,d)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,c])}const Yu=/^(run|approve|accept|yes|allow|always)/,Xu=/^(run|approve|accept|yes|allow|always|proceed|save)/,Ju=/^(reject|deny|delete|remove|abort|cancel|no)/;function Ua(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Qu(e){const s=Ua(e).toLowerCase();return Yu.test(s)?"primary":Ju.test(s)?"danger":"default"}function Zu(e){return Xu.test(Ua(e).toLowerCase())?"approve":"reject"}function em(e){return e.map((s,r)=>({label:Ua(s),variant:Qu(s),action:Zu(s),button:s,buttonIndex:r}))}function tm(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 sm(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function rm(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 nm{constructor(){qe(this,"dedupMap",new Map);qe(this,"DEDUP_WINDOW_MS",5e3);qe(this,"DEDUP_MAX_SIZE",50);qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);qe(this,"toastCallbacks",[]);qe(this,"systemMessageCallbacks",[]);qe(this,"clearSystemMessageCallbacks",[]);qe(this,"resolveActionFn",null);qe(this,"viewRequestRespondFn",null);qe(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,m;const n=this.resolveConversationKey(s),a=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),i=n||s.daemonId||"",c=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(a),l=`${i}:${s.event}:${c}`;if(this.isDuplicate(l))return;const u=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,f=(u==null?void 0:u.type)||"";let d=ot(f);const x=this.resolveOwningDaemon(s);if(x){const p=_t(x,{fallbackId:x.id});p&&(d=!f||f==="adhdev-daemon"?p:`${p}/${d}`)}let g="",w="info";if(s.event==="agent:generating_completed"){const p=s.duration?` (${s.duration}s)`:"";g=`✅ ${d} agent task completed${p}`,w="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(g=`⚡ ${d} approval needed`,w="warning",n&&!((M=s.modalButtons)!=null&&M.length)&&this.emitSystemMessage(n,{role:"system",timestamp:a,content:tm(s.modalMessage,s.modalButtons),_localId:`sys_approval_${a}`}),(m=s.modalButtons)!=null&&m.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(s);if(!p)return;const b=this.resolveActionFn,h=em(s.modalButtons).map(k=>({label:k.label,variant:k.variant,onClick:()=>{b(p,"resolve_action",{action:k.action,button:k.button,buttonIndex:k.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),S=sm(d,s.modalMessage,g),R=Date.now();this.emitToast({id:R,message:S,type:w,timestamp:R,targetKey:n||p,actions:h,duration:15e3}),g=""}}else if(s.event==="monitor:long_generating"){const p=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";g=`⚠️ ${d} agent is taking a long time${p}`,w="warning",ir("browser")&&!document.hasFocus()&&ga(`⚠️ ${d} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const p=s.requesterName||"A team member",b=s.requestId,h=s.orgId;if(g=`👁️ ${p} wants to view your session`,w="warning",b&&h&&this.viewRequestRespondFn){const S=Date.now(),R=rm(h,b,this.viewRequestRespondFn,(k,I)=>console.error(`[EventManager] ${k} view request failed:`,I));this.emitToast({id:S,message:g,type:w,timestamp:S,actions:R,duration:3e4}),g=""}ir("browser")&&!document.hasFocus()&&ga("👁️ View Request",`${p} wants to view your session`,`view-request-${b}`)}else s.event==="team:view_request_approved"?(g="✅ View request approved",w="success"):s.event==="team:view_request_rejected"&&(g=`❌ ${s.targetName||"Team member"} declined your view request`,w="warning");if(g){const p=Date.now();this.emitToast({id:p,message:g,type:w,timestamp:p,targetKey:n||s.daemonId,duration:5e3})}}}const st=new nm,zo=new Map;function Ws(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ds(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function am(e){return!Ws(e)||!Ws(e.controlResult)||!Array.isArray(e.controlResult.options)?null:e.controlResult}function Er(e){return!Ws(e)||!Ws(e.controlResult)||typeof e.controlResult.ok!="boolean"?null:e.controlResult}function Qs(e){if(!(!Ws(e)||typeof e.error!="string"||!e.error.trim()))return e.error}function $r(e){return Ws(e)&&e.success===!1}function om(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";st.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";st.showToast(n.notification.body,a)}}}function im(e,s){return e&&Ds(e.currentValue)?e.currentValue:s}function cm(e,s){return Ds(s)?Ds(e)?typeof e=="string"&&e.trim()==="":!0:!1}function lm(e,s){var i,c;if((s.now??Date.now())<s.localOverrideUntil){const l=s.localValues[e];if(Ds(l))return l}const n=(i=s.controlValues)==null?void 0:i[e];if(Ds(n))return n;const a=(c=s.defaultValues)==null?void 0:c[e];return Ds(a)?a:void 0}function en(e,s){return e.options||s[e.id]||[]}const dm=new Set(["antigravity","claude-code-vscode","codex"]);function um(e,s,r){return r.id==="new_session"&&dm.has(s)}function za(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!um(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function On(e,s){return{value:s}}function mm(e,s,r){var a;return r?((a=en(e,s).find(i=>i.value===r))==null?void 0:a.label)||r:""}const pm={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function fm({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:i,controlValues:c}){const{sendCommand:l}=Tt(),u=`${e}:${s||n}`,f=pm[n]||"#94a3b8",[d,x]=o.useState({}),g=o.useRef({}),w=o.useRef(c);g.current=d,w.current=c;const M=o.useRef(0),m={};for(const P of i||[])P.defaultValue!==void 0&&(m[P.id]=P.defaultValue);const p={...m,...c||{},...Date.now()<M.current?d:{}};o.useEffect(()=>{c&&Date.now()>M.current&&x({})},[c]);const[b,h]=o.useState(zo.get(u)||{}),[S,R]=o.useState(null),[k,I]=o.useState(null),j=o.useCallback(async(P,U={})=>{const N={...U,...s&&{targetSessionId:s}};return await l(e,P,N)},[e,s,l]),v=o.useCallback(async(P,U={})=>{const N=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await j("invoke_provider_script",{...N,scriptName:P,...U})},[j,n,r,s]),y=o.useCallback((P,U,N)=>{const $=im(N,U);x(z=>({...z,[P.id]:$})),om(N==null?void 0:N.effects)},[]),E=o.useCallback((P,U)=>{x(N=>{const $={...N};return U===void 0?delete $[P.id]:$[P.id]=U,$}),M.current=0},[]);if(!i||i.length===0)return null;const L=za(i,{hostIdeType:r,providerType:n});if(L.length===0)return null;const A=async P=>{if(S===P.id){R(null);return}if(en(P,b).length>0){R(P.id);return}if(P.dynamic&&P.listScript){I(P.id);try{const N=await v(P.listScript,{}),$=am(N);if(!$){const W=Qs(N);W&&st.showToast(W,"warning");return}const z=$.options;h(W=>{const ne={...W,[P.id]:z};return zo.set(u,ne),ne});const q=lm(P.id,{localOverrideUntil:M.current,localValues:g.current,controlValues:w.current,defaultValues:m});if(cm(q,$.currentValue)){const W=$.currentValue;x(ne=>({...ne,[P.id]:W}))}R(P.id)}catch(N){const $=N instanceof Error?N.message:`Could not load ${P.label}`;st.showToast($,"warning")}finally{I(null)}}},_=async(P,U)=>{R(null);const N=(c==null?void 0:c[P.id])??m[P.id];x($=>({...$,[P.id]:U})),M.current=Date.now()+5e3;try{if(!P.setScript)return;const $=await v(P.setScript,On(P,U)),z=Er($);if(z&&!z.ok||$r($))throw new Error((z==null?void 0:z.error)||Qs($)||`Could not update ${P.label}`);y(P,U,z)}catch($){E(P,N);const z=$ instanceof Error?$.message:`Could not update ${P.label}`;st.showToast(z,"warning")}},B=async P=>{const U=en(P,b).map(ne=>ne.value);if(U.length===0)return;const N=String(p[P.id]||""),z=(U.indexOf(N)+1)%U.length,q=U[z];if(typeof q!="string")return;const W=(c==null?void 0:c[P.id])??m[P.id];x(ne=>({...ne,[P.id]:q})),M.current=Date.now()+5e3;try{if(!P.setScript)return;const ne=await v(P.setScript,On(P,q)),ae=Er(ne);if(ae&&!ae.ok||$r(ne))throw new Error((ae==null?void 0:ae.error)||Qs(ne)||`Could not update ${P.label}`);y(P,q,ae)}catch(ne){E(P,W);const ae=ne instanceof Error?ne.message:`Could not update ${P.label}`;st.showToast(ae,"warning")}},H=async P=>{const N=!p[P.id],$=(c==null?void 0:c[P.id])??m[P.id];x(z=>({...z,[P.id]:N})),M.current=Date.now()+5e3;try{if(!P.setScript)return;const z=await v(P.setScript,On(P,N)),q=Er(z);if(q&&!q.ok||$r(z))throw new Error((q==null?void 0:q.error)||Qs(z)||`Could not update ${P.label}`);y(P,N,q)}catch(z){E(P,$);const q=z instanceof Error?z.message:`Could not update ${P.label}`;st.showToast(q,"warning")}},C=async P=>{if(!P.invokeScript)return;if(P.confirmMessage){const N=[P.confirmTitle,P.confirmMessage,P.confirmLabel].filter(z=>typeof z=="string"&&z.trim().length>0);if(!window.confirm(N.join(`
|
|
29
|
-
|
|
30
|
-
`)))return}const U=(c==null?void 0:c[P.id])??m[P.id];try{const N=await v(P.invokeScript),$=Er(N);if($&&!$.ok||$r(N))throw new Error(($==null?void 0:$.error)||Qs(N)||`Could not run ${P.label}`);$&&y(P,U??!0,$)}catch(N){E(P,U);const $=N instanceof Error?N.message:`Could not run ${P.label}`;st.showToast($,"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:f},children:a}),t.jsx("span",{className:"text-border-subtle text-[10px]",children:"│"}),L.map(P=>{const U=String(p[P.id]||""),N=mm(P,b,U),$=S===P.id,z=k===P.id,q=en(P,b);switch(P.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:$?`${f}55`:"transparent",border:"1px solid",color:U?"var(--text-primary)":"var(--text-muted)"},onClick:()=>A(P),children:[P.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),z?"...":N||P.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"▼"})]}),$&&q.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>R(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:P.label.toUpperCase()}),q.map(W=>t.jsx("div",{className:"px-3 py-[7px] text-[11px] cursor-pointer whitespace-nowrap overflow-hidden text-ellipsis",style:{background:W.value===U?`${f}18`:"transparent",color:W.value===U?f:"var(--text-secondary)",fontWeight:W.value===U?600:400,borderLeft:W.value===U?`2px solid ${f}`:"2px solid transparent"},title:W.description||W.label,onMouseEnter:ne=>{ne.currentTarget.style.background=`${f}12`},onMouseLeave:ne=>{ne.currentTarget.style.background=W.value===U?`${f}18`:"transparent"},onClick:()=>_(P,W.value),children:W.label},W.value))]})]})]},P.id);case"cycle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all bg-[var(--surface-tertiary)] whitespace-nowrap",style:{border:"1px solid transparent",color:U?"var(--text-primary)":"var(--text-muted)"},onClick:()=>B(P),title:`Click to cycle: ${q.map(W=>W.label).join(" → ")}`,children:[P.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),N||P.label,t.jsx("span",{className:"text-[7px] opacity-50",children:"⟳"})]},P.id);case"toggle":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all whitespace-nowrap",style:{border:"1px solid",borderColor:U?`${f}44`:"transparent",background:U?`${f}14`:"var(--surface-tertiary)",color:U?f:"var(--text-muted)"},onClick:()=>H(P),children:[P.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),P.label]},P.id);case"action":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium cursor-pointer transition-all hover:bg-[var(--surface-tertiary-hover)] whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>C(P),children:[P.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),P.resultDisplay==="inline"&&U?`${P.label}: ${U}`:P.label]},P.id);case"display":return t.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-xl text-[10px] font-medium whitespace-nowrap",style:{border:"1px solid var(--border-default)",background:"var(--surface-tertiary)",color:U?"var(--text-primary)":"var(--text-muted)"},children:[P.icon&&t.jsx("span",{className:"text-[9px] opacity-60",children:P.icon}),U?`${P.label}: ${U}`:P.label]},P.id);default:return null}})]})}function hm({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:l,controlValues:u}){const{isVisible:f}=cc(),d=za(l,{hostIdeType:a,providerType:i});return!e||s||d.length===0||!f?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(fm,{routeId:r,sessionId:n,hostIdeType:a,providerType:i,displayLabel:c,controls:d,controlValues:u})})}function xc({hasDraft:e,isBusy:s=!1}){return!e||s}const xm=o.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:i=null,onSend:c,isActive:l=!0,showControlsToggle:u=!1}){const f=o.useRef(null),[d,x]=o.useState(""),{isVisible:g,toggleVisibility:w}=cc();o.useEffect(()=>{x("")},[s]),o.useEffect(()=>{var m;l&&((m=f.current)==null||m.focus())},[s,l]);const M=async()=>{const m=d.trim();if(!m||a)return;await c(m)!==!1&&x("")};return t.jsxs("div",{className:"dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden transition-all duration-200 ease-out",style:{borderTop:l?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:l?72:0,opacity:l?1:0,transform:l?"translateY(0)":"translateY(10px)",padding:l?"10px 12px":"0 12px",pointerEvents:l?"auto":"none"},"aria-hidden":!l,children:[t.jsxs("div",{className:"flex gap-2 items-center",title:l?`Send message to ${r}`:void 0,children:[u&&t.jsx("button",{type:"button",onClick:w,"aria-label":g?"Hide controls":"Show controls","aria-pressed":g,title:g?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:t.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[t.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:f,type:"text",placeholder:i||`Send message to ${r}...`,value:d,onChange:m=>x(m.target.value),onPaste:m=>{const p=m.clipboardData.getData("text");p&&x(b=>b+p),m.preventDefault()},onKeyDown:m=>{if(m.key==="Enter"){if(m.nativeEvent.isComposing){m.preventDefault();return}m.preventDefault(),M()}},onBlur:m=>{if(window.innerWidth<768){const p=m.relatedTarget;if((p==null?void 0:p.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:()=>{M()},disabled:xc({hasDraft:!!d.trim(),isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${d.trim()&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:d.trim()&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:d.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),i&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),tt=e=>e.transport==="pty",Hs=(e,s)=>tt(e)?e.mode||"terminal":"chat",bc=(e,s)=>tt(e)&&Hs(e)==="terminal",Qe=e=>e.transport==="acp";function ns(e){return e.streamSource!=="agent-stream"}function is(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function gc(e){return e.machineName||""}function Sr(e){return is(e)}function Ot(e){return e.agentType||""}function un(e){return e.hostIdeType||""}function Va(e){return e.displayPrimary||e.agentName||"Agent"}function yc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function bm(e){return e.lastMessagePreview||e.displaySecondary||""}function vc(e){return[e.displaySecondary,gc(e)].filter(Boolean)}function Fs(e){return e.agentName||ot(Ot(e))}function gm(e){var s,r;if(!ns(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return ot(un(e)||Ot(e))}function wc(e){return ns(e)?e.sessionId:e.nativeSessionId}function Vo(e){return ns(e)?"native":e.tabKey}function ym(e){return e.sessionId}function vm(e,s){if(s)return ns(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function wm(e,s){const r=Ot(e),n=ns(e),a=tt(e)||Qe(e),i=n?a?Fs(e)||(s==null?void 0:s.cliName)||ot(un(e)||r):s!=null&&s.type?ot(s.type):ot(un(e)||r):Fs(e);return{isNativeConversation:n,isCli:tt(e),isAcp:Qe(e),isCliTerminal:bc(e),providerType:r,displayLabel:i,targetEntry:vm(e,s)}}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 ps(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 ya(e,s=0){return ps(e)||e.lastUpdated||s||0}function jc(e){return ps(e)||e.lastUpdated||0}function kc(e,s,r=jc){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 va(e){var r;const s=St(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)&&!va(e)&&!e.title.trim()}function Sm(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(va(r))-Number(va(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:kc(s,r)})[0]||null}function Ht(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 as(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ga(e){return kr(e)||e.tabKey||e.routeId||null}function Sc(e){const s=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"";if(s)return s;const r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"";if(r)return r;const n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"";if(!n)return null;const a=Ht(e.conversations,n)||e.conversations.find(i=>i.routeId===n);return a?Ga(a):null}function Nc({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0}){const i=Vs(),c=is(e),l=gc(e),u=e.transport==="cdp-page"||e.transport==="cdp-webview",f=e.streamSource==="agent-stream"&&!!e.agentName,d=!f&&(e.transport==="pty"||e.transport==="acp"),x=Fs(e),g=gm(e),w=o.useCallback(()=>{if(n){n();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,n]),M=o.useCallback(()=>{if(r){r();return}const m=Ga(e);m&&i(as(m))},[e,i,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[u&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:M,title:g,children:[t.jsx(Pt,{size:12}),t.jsx("span",{children:g})]}):t.jsxs("span",{className:"conversation-meta-chip",title:g,children:[t.jsx(Pt,{size:12}),t.jsx("span",{children:g})]})),f&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(hr,{size:12}),t.jsx("span",{children:x})]}),d&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[t.jsx(hr,{size:12}),t.jsx("span",{children:x})]}),l&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:w,title:l,children:[t.jsx(Zt,{size:12}),t.jsx("span",{children:l})]}):t.jsxs("span",{className:"conversation-meta-chip",title:l,children:[t.jsx(Zt,{size:12}),t.jsx("span",{children:l})]}))]})}function Wn(e,s){return`${e}:${s}`}function Nm(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function Kr(e,s){Nm()&&console.debug(`[subscription-manager] ${e}`,s)}class Cm{constructor(){qe(this,"active",new Map)}subscribe(s,r,n,a){var f;const i=Wn(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 d={daemonId:r,request:n,handlers:new Set([a])};this.active.set(i,d),Kr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),l=((f=s.sendData)==null?void 0:f.call(s,r,n))??!1}const u=()=>{var g;const d=this.active.get(i);if(!d||(d.handlers.delete(a),d.handlers.size>0))return;this.active.delete(i);const x={type:"unsubscribe",topic:n.topic,key:n.key};Kr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(g=s.sendData)==null||g.call(s,r,x)};return u.initialSendAccepted=l,u}publish(s){const r=Wn(s.topic,s.key),n=this.active.get(r);n&&(n.lastUpdate=s,Ks.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(a=>{a(s),Ks.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}updateParams(s,r,n){const a=Wn(s,r),i=this.active.get(a);i&&(i.request={...i.request,params:{...i.request.params,...n}})}resubscribeAll(s){var r;Kr("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);Kr("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(i=>({topic:i.request.topic,key:i.request.key}))});for(const i of n)(a=r.sendData)==null||a.call(r,i.daemonId,i.request)}}const os=new Cm;function Im(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker});for(const i of n.childSessions||[]){if(!(i!=null&&i.id))continue;const c=r.get(i.id)||{};r.set(i.id,{...c,...i})}}return r}function Am(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 mn(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:i,timestamp:c}=s,l=c||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:f,childrenByParent:d}=Am(u),x=Im(i,n),g=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=f.filter(p=>p.kind==="workspace"&&p.transport==="cdp-page"),M=f.filter(p=>p.kind==="agent"&&p.transport==="pty"),m=f.filter(p=>p.kind==="agent"&&p.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:l,...e.version&&{version:e.version},...g&&{machine:g,platform:g.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},cdpConnected:w.some(p=>!!p.cdpConnected)});for(const p of w){const b=x.get(p.id),h=ar(p,b),S=(d.get(p.id)||[]).map(R=>ar(R,x.get(R.id)));r.push({id:`${n}:ide:${p.id}`,sessionId:p.id,providerSessionId:p.providerSessionId??(b==null?void 0:b.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:p.id,workspace:h.workspace,terminals:0,childSessions:S,agents:S.map(R=>({id:R.id,name:R.providerName||R.providerType,type:R.providerType,status:R.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l})}for(const p of M){const b=x.get(p.id),h=ar(p,b);r.push({id:`${n}:cli:${p.id}`,sessionId:p.id,providerSessionId:p.providerSessionId??(b==null?void 0:b.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:p.id,cliName:h.providerName||h.providerType,mode:h.mode||(b==null?void 0:b.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isCli:!0})}for(const p of m){const b=x.get(p.id),h=ar(p,b);r.push({id:`${n}:acp:${p.id}`,sessionId:p.id,providerSessionId:p.providerSessionId??(b==null?void 0:b.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:p.id,cliName:h.providerName||h.providerType,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},timestamp:l,_isAcp:!0})}return r}const Mm=15e3,Tm=15e3,Lm=6e4,Rm=1200,Go=12,_m=8e3,Pm=4e3,Hn=new Map,Fn=new Map,Br=new Set,cr=new Map;function Dm(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 qo(e,s){const r=cr.get(e);!r||r.size===0||(cr.delete(e),r.forEach(n=>n(s)))}function Em(e,s){return new Promise(r=>{const n=cr.get(e)||new Set;cr.set(e,n);const a=c=>{clearTimeout(i),n.delete(a),n.size===0&&cr.delete(e),r(c)},i=setTimeout(()=>a(!1),s);n.add(a)})}function Nr(){const{sendCommand:e,sendData:s}=Tt(),{injectEntries:r,getIdes:n}=fr();return o.useCallback(async(a,i)=>{if(!a)return;const c=(i==null?void 0:i.minFreshMs)??Lm,l=Fn.get(a)||0;if(!(i!=null&&i.force)&&Br.has(a)&&l>0||!(i!=null&&i.force)&&l>0&&Date.now()-l<c)return;const u=Hn.get(a);if(u)return u;const f=(async()=>{if(s&&!Br.has(a)){const m=os.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},p=>{const b=n(),h=b.find(R=>R.id===a),S=mn(p.status,{daemonId:a,existingDaemon:h,existingEntries:b,timestamp:p.timestamp});S.length>0&&r(S),Fn.set(a,Date.now()),qo(a,!0)});if(m.initialSendAccepted?Br.add(a):Br.delete(a),!(i!=null&&i.force)&&m.initialSendAccepted&&await Em(a,Rm))return}const d=await e(a,"get_status_metadata"),x=Dm(d);if(!x)return;const g=n(),w=g.find(m=>m.id===a),M=mn(x,{daemonId:a,existingDaemon:w,existingEntries:g,timestamp:x.timestamp||Date.now()});M.length>0&&r(M,{authoritativeDaemonIds:[a]}),Fn.set(a,Date.now()),qo(a,!0)})().finally(()=>{Hn.delete(a)});return Hn.set(a,f),f},[n,r,e,s])}function Gt(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}function qa(e,s){if(!e||!s)return!1;if(e===s||e.id&&s.id&&String(e.id)===String(s.id)||e._localId&&s._localId&&String(e._localId)===String(s._localId))return!0;const r=String(e.role||"").toLowerCase(),n=String(s.role||"").toLowerCase();if(r!==n)return!1;const a=Os(e.content),i=Os(s.content);if(!a||!i||!(a===i||gr(a,i)||gr(i,a)))return!1;const l=Gt(e),u=Gt(s);return l&&u?Math.abs(l-u)<=15e3:!!e._localId!=!!s._localId}function Yo(e){let s=0;return e!=null&&e._localId||(s+=4),e!=null&&e.id&&(s+=3),e!=null&&e._turnKey&&(s+=2),Gt(e)&&(s+=1),s}function Ns(e){return Os(e==null?void 0:e.content)}function gr(e,s){if(!e||!s||e.length<=s.length)return!1;const r=Math.max(12,Math.min(80,Math.floor(e.length*.4)));return s.length<r?!1:e.startsWith(s)||e.includes(s)}function $m(e,s){const r=Ns(e),n=Ns(s);return!r||!n||r===n?null:gr(r,n)?e:gr(n,r)?s:null}function Km(e,s){const r=$m(e,s);if(r)return r;const n=Yo(e),a=Yo(s);return a!==n?a>n?s:e:Ns(s).length>=Ns(e).length?s:e}function Bm(e){return!!e&&!!(e.id||e._localId||e._turnKey)}function lr(e){if(!e)return[];const s=[],r=l=>{l&&s.push(l)};e.id&&r(`id:${String(e.id)}`),e._localId&&r(`local:${String(e._localId)}`),e._turnKey&&r(`turn:${String(e._turnKey)}`);const n=String(e.role||"").toLowerCase(),a=Ns(e),i=Gt(e),c=i?Math.round(i/15e3):0;return n&&a&&(r(`content:${n}:${a}`),r(`preview:${n}:${a.slice(0,120)}:${c}`)),s}function fs(e,s=qa){const r=[],n=new Map,a=(c,l)=>{for(const u of lr(c)){const f=n.get(u);f?f.push(l):n.set(u,[l])}},i=(c,l)=>{for(const u of lr(c)){const f=n.get(u);if(!f)continue;const d=f.filter(x=>x!==l);d.length>0?n.set(u,d):n.delete(u)}};for(const c of e){const l=new Set;for(const d of lr(c)){const x=n.get(d);x&&x.forEach(g=>l.add(g))}const u=l.size>0?Array.from(l).sort((d,x)=>d-x).find(d=>s(r[d],c)):Bm(c)?-1:r.findIndex(d=>s(d,c));if(u!==void 0&&u>=0){const d=Km(r[u],c);d!==r[u]&&(i(r[u],u),r.splice(u,1,d),a(d,u));continue}const f=r.length;r.push(c),a(c,f)}return r}function Om(e,s){const r=Array.isArray(e)?e:[],n=Array.isArray(s)?s:[];return r.length===0?n:n.length===0?r:fs([...r,...n])}function Xo(e){return[...e].sort((s,r)=>{const n=Gt(s),a=Gt(r);return n&&a&&n!==a?n-a:0})}function Jo(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=>qa(i,n));return a>=0?(r.splice(a,1),!1):!0})}function Wm(e,s,r=qa){const n=new Map,a=i=>{for(const c of lr(i)){const l=n.get(c);l?l.push(i):n.set(c,[i])}};return s.forEach(a),e.filter(i=>{const c=Ns(i),l=String((i==null?void 0:i.role)||"").toLowerCase(),u=Gt(i),f=new Set;for(const x of lr(i)){const g=n.get(x);g&&g.forEach(w=>f.add(w))}return!(f.size>0?Array.from(f):s).some(x=>{if(r(i,x))return!0;const g=String((x==null?void 0:x.role)||"").toLowerCase();if(!c||!l||l!==g)return!1;const w=Ns(x);if(!gr(w,c)&&w!==c)return!1;const M=Gt(x);return u&&M?Math.abs(u-M)<=15e3:!0})})}function Es(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:tt(e)||Qe(e)?{agentType:Ot(e)}:e.streamSource==="agent-stream"?{agentType:Ot(e)}:s}function yr(e){return e?Sr(e):""}function Zs(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Ya(e){if(!e)return null;if(Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return"Resolve the pending approval prompt before sending another message.";switch(e.status){case"waiting_approval":case"waiting_for_user_input":return"Resolve the pending approval prompt before sending another message.";default:return null}}function Hm(e){const s=e instanceof Error?e.message:String(e||""),r=s.toLowerCase();return r.includes("still processing the previous prompt")?"Wait for the current reply to finish before sending another message.":r.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":r.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":r.includes("not running")?"Runtime is not available right now.":s||"Unable to send message right now."}const Fm=60,Um=1e3;function Cc(e={}){return e.isCliLike?Um:Fm}function zm(e={}){return Cc(e)}const Cr=60,Vm=1e3,Xa=12e4,Gm=new Set(["generating","waiting_approval","starting","streaming","working"]),Qo=new Map;function Ic(e,s){return`${e}::${s}`}function wa(e=Cr){return{liveMessages:[],cursor:Mc([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Ac(e){return Gi(e)}function Mc(e,s=Cr){return{knownMessageCount:e.length,lastMessageSignature:Ac(e[e.length-1]),tailLimit:s}}function Or(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 qm(e,s){const r=Array.isArray(s.messages)?s.messages:[];switch(s.syncMode){case"noop":return e;case"append":return fs([...e,...r]);case"replace_tail":{const n=Math.max(0,Math.min(Number(s.replaceFrom??e.length),e.length));return fs([...e.slice(0,n),...r])}case"full":{const n=Math.max(Number(s.totalMessages||0),r.length);if(n>r.length&&e.length>r.length){const a=Math.max(0,n-r.length);return fs([...e.slice(0,a),...r])}return r}default:return r}}class Ym{constructor(s){qe(this,"manager");qe(this,"sendData");qe(this,"daemonId");qe(this,"sessionId");qe(this,"historySessionId");qe(this,"subscriptionKey");qe(this,"snapshot");qe(this,"transportSubscription",null);qe(this,"listeners",new Set);qe(this,"retainCount",0);qe(this,"loadHistoryPromise",null);qe(this,"pendingDisconnectTimer",null);qe(this,"pendingSubscribeRetryTimer",null);this.manager=s.manager||os,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.snapshot=wa(Math.max(0,s.tailLimit??Cr))}updateOptions(s){if(s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId),s.tailLimit!==void 0){const r=Math.max(0,s.tailLimit);if(r!==this.snapshot.cursor.tailLimit){const n=Math.min(this.snapshot.cursor.knownMessageCount,this.snapshot.liveMessages.length);this.snapshot={...this.snapshot,cursor:{...this.snapshot.cursor,knownMessageCount:n,tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect())}}}getSnapshot(){return this.snapshot}hydrateLiveMessages(s){const r=Array.isArray(s)?s:[];if(r.length===0)return;const n=fs([...r,...this.snapshot.liveMessages]);if(n.length<r.length)return;const a=Mc(n,this.snapshot.cursor.tailLimit);Or(this.snapshot.liveMessages)===Or(n)&&this.snapshot.cursor.knownMessageCount===a.knownMessageCount&&this.snapshot.cursor.lastMessageSignature===a.lastMessageSignature||(this.snapshot={...this.snapshot,liveMessages:n,cursor:a},this.emit())}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=await s(),a=Array.isArray(n.messages)?n.messages:[];this.snapshot={...this.snapshot,historyMessages:[...a,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+a.length,hasMoreHistory:n.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{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}:{}}}}clearPendingSubscribeRetry(){this.pendingSubscribeRetryTimer&&(clearTimeout(this.pendingSubscribeRetryTimer),this.pendingSubscribeRetryTimer=null)}scheduleSubscribeRetry(){this.pendingSubscribeRetryTimer||!this.sendData||!this.daemonId||!this.sessionId||this.retainCount===0||(this.pendingSubscribeRetryTimer=setTimeout(()=>{if(this.pendingSubscribeRetryTimer=null,!this.sendData||!this.daemonId||!this.sessionId||this.retainCount===0)return;this.sendData(this.daemonId,this.buildSubscribeRequest())||this.scheduleSubscribeRetry()},Vm))}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),s=>{this.handleUpdate(s)}),this.transportSubscription.initialSendAccepted||this.scheduleSubscribeRetry())}disconnect(){var s;this.clearPendingSubscribeRetry(),(s=this.transportSubscription)==null||s.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){this.clearPendingSubscribeRetry();const r=qm(this.snapshot.liveMessages,s),n={knownMessageCount:r.length,lastMessageSignature:typeof s.lastMessageSignature=="string"?s.lastMessageSignature:Ac(r[r.length-1]),tailLimit:this.snapshot.cursor.tailLimit};Or(this.snapshot.liveMessages)===Or(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 Tc(e){const s=Ic(e.daemonId,e.sessionId),r=Qo.get(s);if(r)return r.updateOptions(e),r;const n=new Ym(e);return Qo.set(s,n),n}function Xm(e,s){return{...e,loadHistoryPage:s}}function Jm(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function Qm(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(Gm.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=s.now??Date.now(),a=Math.max(0,Number(s.recentActivityMs??Xa)),i=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return i>0?n-i<=a:Array.isArray(e.messages)&&e.messages.length>0}function Zm(e=Xa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function ep(e,s={}){const r=new Set,n=[];for(const a of e){if(!Qm(a,s))continue;const i=Sr(a),c=a.sessionId||"";if(!i||!c)continue;const l=Ic(i,c);if(r.has(l))continue;r.add(l);const u=kr(a);n.push({daemonId:i,sessionId:c,historySessionId:u||c,subscriptionKey:`daemon:${i}:session:${c}`})}return n.sort(Jm),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function tp(e,s){const{sendData:r,sendCommand:n}=Tt(),a=(s==null?void 0:s.enabled)!==!1,i=Sr(e),c=e.sessionId||"",l=kr(e)||c,u=`daemon:${i}:session:${c}`,f=Math.max(0,(s==null?void 0:s.tailLimit)??Cr),d=o.useMemo(()=>!a||!i||!c?null:Tc({daemonId:i,sessionId:c,historySessionId:l,subscriptionKey:u,sendData:r,tailLimit:f}),[i,a,l,r,c,u,f]),[x,g]=o.useState(()=>(d==null?void 0:d.getSnapshot())||wa(f));o.useEffect(()=>{if(!d){g(wa(f));return}d.retain(),g(d.getSnapshot());const M=d.subscribe(m=>{g(m)});return()=>{M(),d.release()}},[d,f]),o.useEffect(()=>{d&&(d.hydrateLiveMessages(e.messages),g(d.getSnapshot()))},[e.messages,d]);const w=o.useCallback(async()=>{!d||!i||!c||await d.loadHistoryPage(async()=>{const M=e.agentType,m=await n(i,"chat_history",{agentType:M,offset:d.getSnapshot().historyOffset,limit:30,targetSessionId:c,historySessionId:l}),p=m&&typeof m=="object"&&"result"in m?m.result||{}:m||{};return{messages:Array.isArray(p.messages)?p.messages:[],hasMore:p.hasMore===!0}})},[e.agentType,d,i,l,n,c]);return o.useMemo(()=>Xm(x,w),[w,x])}function sp(e,s){const{sendData:r}=Tt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??Cr),i=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??Xa)),c=Zm(i),[l,u]=o.useState(0);o.useEffect(()=>{if(!n||e.length===0)return;const d=setInterval(()=>{u(x=>x+1)},c);return()=>{clearInterval(d)}},[e.length,n,c]);const f=o.useMemo(()=>ep(e,{recentActivityMs:i}),[e,i,l]);o.useEffect(()=>{if(!n||!r||f.descriptors.length===0)return;const d=f.descriptors.map(x=>Tc({...x,sendData:r,tailLimit:a}));return d.forEach(x=>x.retain()),()=>{d.forEach(x=>x.release())}},[f.signature,n,r,a])}function rp(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function np(e){return rp(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const ap=60;function ja({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:l,userName:u,showMetaChips:f=!1,scrollToBottomRequestNonce:d,isInputActive:x=!0}){var ae,ke,X,pe,Y;const g=o.useRef(new Map),w=Nr();jr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:l.length,isSendingChat:n});const M=at.useMemo(()=>qs(e),[e.status,e.connectionState]),m=o.useMemo(()=>wm(e,s),[e,s]),p=o.useMemo(()=>{var J;return za((J=m.targetEntry)==null?void 0:J.providerControls,{hostIdeType:e.hostIdeType,providerType:m.providerType})},[e.hostIdeType,m.providerType,(ae=m.targetEntry)==null?void 0:ae.providerControls]),b=Cc({isCliLike:m.isCli||m.isAcp}),h=zm({isCliLike:m.isCli||m.isAcp}),S=tp(e,{enabled:!!e.sessionId,tailLimit:h}),[R,k]=o.useState(b),I=e.tabKey,j=S.historyMessages,v=S.hasMoreHistory,y=S.historyError,E=Om(S.liveMessages,e.messages);o.useEffect(()=>{k(b)},[b,I]);const L=Math.max(0,E.length-R),A=Va(e),_=Sr(e),B=np(e),H=Ya(e),C=a||H,P=!!H,[U,N]=o.useState(!1);o.useEffect(()=>{const J=m.targetEntry;_&&(!J||J.providerControls===void 0||J.controlValues===void 0)&&w(_,{minFreshMs:3e4}).catch(()=>{})},[_,m.isAcp,(ke=m.targetEntry)==null?void 0:ke.providerControls,(X=m.targetEntry)==null?void 0:X.controlValues,w]);const $=o.useCallback(async()=>{if(!U){if(E.length>R){k(J=>Math.min(E.length,J+ap));return}N(!0);try{await S.loadHistoryPage()}finally{N(!1)}}},[S,U,E.length,R]),{allMessages:z,receivedAtMap:q}=o.useMemo(()=>{const J=L>0?E.slice(-R):E;if(j.length===0){const ve=Xo(fs(J)),ie={};return ve.forEach((ce,te)=>{const me=`${e.tabKey}:${Rs(ce,te)}`;let re=Gt(ce)||g.current.get(me)||0;re||(re=Date.now(),g.current.set(me,re)),ie[Rs(ce,te)]=re}),{allMessages:ve,receivedAtMap:ie}}const ue=Wm(j,J),le=Xo(fs([...ue,...J])),V={};return le.forEach((ve,ie)=>{const ce=`${e.tabKey}:${Rs(ve,ie)}`;let te=Gt(ve)||g.current.get(ce)||0;te||(te=Date.now(),g.current.set(ce,te)),V[Rs(ve,ie)]=te}),{allMessages:le,receivedAtMap:V}},[e.tabKey,L,j,E,R]),W=o.useMemo(()=>l.filter(J=>J.routeId===e.tabKey).sort((J,ue)=>J.timestamp-ue.timestamp),[l,e.tabKey]),ne=o.useMemo(()=>{if(E.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((M.isGenerating||e.status==="streaming")&&N(!1),e.status==="not_monitored"&&B)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(hr,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bs,{size:14})," Open ",A," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&B)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Ji,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Bs,{size:14})," Open ",A," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Open the agent panel or chat view in the app you are using to start viewing messages"})]});if(e.status==="idle"&&!U)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,B,i,c,U,E.length,A,M.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[f&&t.jsx(Nc,{conversation:e,className:"chat-pane-meta-row"}),t.jsx(fu,{messages:z,actionLogs:W,agentName:Fs(e)||A||"Agent",userName:u,isCliMode:m.isCli||m.isAcp,isWorking:M.isGenerating,contextKey:e.tabKey,receivedAtMap:q,onLoadMore:$,isLoadingMore:U,hasMoreHistory:v,hiddenLiveCount:L,loadError:y??void 0,emptyState:ne,scrollToBottomRequestNonce:d}),t.jsx(hm,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:m.providerType,displayLabel:m.displayLabel,controls:(pe=m.targetEntry)==null?void 0:pe.providerControls,controlValues:(Y=m.targetEntry)==null?void 0:Y.controlValues,isActive:x,isCliTerminal:m.isCliTerminal}),!m.isCliTerminal&&t.jsx(xm,{contextKey:e.tabKey,panelLabel:A,isSending:n,isBusy:P,statusMessage:C,onSend:r,isActive:x,showControlsToggle:p.length>0})]})}let Lc=js;function Rc(){return Lc()}class op{constructor(){qe(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 _c=new op;class ip{sendPtyInput(s,r,n){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r){return()=>{}}requestRuntimeSnapshot(s,r){return Promise.resolve()}}let ht=new ip;function cp(e){e.dashboardWS&&(_c=e.dashboardWS),e.connectionManager&&(ht=e.connectionManager),e.useDaemonsHook&&(Lc=e.useDaemonsHook)}const Pc=.6,lp=1.15;function dp(e,s={}){const r=typeof s.minScale=="number"?s.minScale:Pc;return!Number.isFinite(e)||e<=0?1:e<=480?r:1}function lt(e){return Va(e)}function Cs(e){return vc(e).join(" · ")}function Dc(e){if(e.lastMessagePreview)return e.lastMessagePreview;const s=[...e.messages].reverse().find(n=>!(n!=null&&n._localId))||e.messages[e.messages.length-1],r=Os(s==null?void 0:s.content);return r||(e.title?e.title:Cs(e)||"No messages yet")}function Ec(e,s){const{isReconnecting:r,isConnecting:n}=qs(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function up(e,s){const r=["Chat",...vc(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function hs(e){return Ec(e)||Cs(e)}function mp(e){return`${lt(e)} · ${Dc(e)}`}function pp(e){const s=un(e),r=s?ot(s):Fs(e);return`${lt(e)} — ${r||"Agent"}`}function fp(e){return Fs(e)||"CLI"}function $c(e){return yc(e)}function Kc(e){return e?`Remote · ${lt(e)||e.workspaceName||"Session"}`:"Remote"}function hp({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:i=null,isVisible:c=!0}){var q;const{ides:l}=js(),u=o.useRef(null),{sendData:f}=Tt(),[d,x]=o.useState(""),[g,w]=o.useState(!1),[M,m]=o.useState(1),p=o.useRef(!1),b=o.useRef(0),h=o.useRef(!1),S=o.useRef(""),R=o.useRef(null),k=o.useRef(!1),I=o.useRef(null),j=e.tabKey,v=e.sessionId||"",y=e.daemonId||((q=e.routeId)==null?void 0:q.split(":")[0])||e.routeId||"",E=l.find(W=>W.id===y&&W.type==="adhdev-daemon"),L=(E==null?void 0:E.terminalSizingMode)==="fit"?"fit":"measured",A=Ya(e),_=i||A,B=Pc,H=lp,C=()=>typeof window>"u"?1:dp(window.innerWidth||0,{minScale:B}),P=()=>{var W,ne;b.current=0,h.current=!1,S.current="",R.current=null,k.current=!1,I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),w(!1),(ne=(W=r.current)==null?void 0:W.reset)==null||ne.call(W)},U=()=>{var W,ne;b.current=0,h.current=!1,S.current="",R.current=null,k.current=!1,I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),w(!0),(ne=(W=r.current)==null?void 0:W.reset)==null||ne.call(W)},N=()=>{var ne;if(I.current=null,!c)return;const W=S.current;W&&(S.current="",(ne=r.current)==null||ne.write(W))},$=W=>{W&&(S.current+=W,c&&I.current===null&&(I.current=requestAnimationFrame(N)))},z=(W,ne=0,ae,ke)=>{var X,pe,Y,J,ue;ne>0&&b.current>=ne||ne===0&&h.current||(b.current=ne,w(!0),typeof ae=="number"&&typeof ke=="number"&&ae>0&&ke>0&&((pe=(X=r.current)==null?void 0:X.resize)==null||pe.call(X,ae,ke)),(J=(Y=r.current)==null?void 0:Y.reset)==null||J.call(Y),W&&((ue=r.current)==null||ue.write(W)))};return o.useEffect(()=>{P()},[v]),o.useEffect(()=>{var ne;if(!v)return;const W=((ne=ht.onRuntimeEvent)==null?void 0:ne.call(ht,v,ae=>{if(!(!ae||ae.sessionId!==v)){if(ae.type==="runtime_snapshot"){if(!c){R.current={text:ae.text||"",seq:ae.seq||0,cols:ae.cols,rows:ae.rows};return}z(ae.text||"",ae.seq||0,ae.cols,ae.rows);return}if(ae.type==="session_output"){h.current=!0,typeof ae.seq=="number"&&(b.current=Math.max(b.current,ae.seq)),g||w(!0),typeof ae.data=="string"&&$(ae.data);return}if(ae.type==="session_cleared"){if(!c){k.current=!0,S.current="",R.current=null;return}U()}}}))||(()=>{});return()=>{W()}},[y,v,r,c,g]),o.useEffect(()=>{var ne,ae,ke;if(!v)return;y&&((ne=ht.getState)==null?void 0:ne.call(ht,y))==="connected"&&(w(!0),(ae=ht.requestRuntimeSnapshot)==null||ae.call(ht,y,v).catch(()=>{}));const W=(ke=ht.onStateChange)==null?void 0:ke.call(ht,(X,pe)=>{var Y;X!==y||pe!=="connected"||(w(!0),(Y=ht.requestRuntimeSnapshot)==null||Y.call(ht,y,v).catch(()=>{}))});return()=>{W==null||W()}},[y,v,r]),o.useEffect(()=>{s&&P()},[s,j,r]),o.useEffect(()=>{x("")},[e.tabKey]),o.useEffect(()=>{const W=()=>{p.current||m(C())};return W(),window.addEventListener("resize",W),()=>window.removeEventListener("resize",W)},[]),o.useEffect(()=>{var ne;if(!c){(ne=u.current)==null||ne.blur();return}k.current&&(k.current=!1,U());const W=R.current;W&&(R.current=null,z(W.text,W.seq,W.cols,W.rows)),S.current&&I.current===null&&(I.current=requestAnimationFrame(N)),requestAnimationFrame(()=>{var ae;(ae=r.current)==null||ae.bumpResize()})},[c]),o.useEffect(()=>()=>{I.current!==null&&(cancelAnimationFrame(I.current),I.current=null)},[]),o.useEffect(()=>{const W=ne=>{var ke;const ae=ne.detail;ae!=null&&ae.sessionId&&ae.sessionId!==v||g&&((ke=r.current)==null||ke.bumpResize())};return window.addEventListener("adhdev:fit-cli-terminal",W),()=>{window.removeEventListener("adhdev:fit-cli-terminal",W)}},[g,v,r]),t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{p.current=!0,m(W=>Math.max(B,Number((W-.1).toFixed(2))))},title:"Shrink terminal viewport",children:"-"}),t.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{p.current=!0,m(W=>Math.min(H,Number((W+.1).toFixed(2))))},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{className:"w-full h-full overflow-x-auto overflow-y-hidden rounded-lg overscroll-contain",children:t.jsx("div",{style:{width:`${100/M}%`,height:`${100/M}%`,transform:`scale(${M})`,transformOrigin:"top left"},children:t.jsx(sc,{ref:r,readOnly:!g||!c,sizingMode:L,onInput:W=>{g&&(f==null||f(y,{type:"pty_input",sessionId:v,targetSessionId:v,data:W}))}})})}),!g&&t.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:"Runtime terminal unavailable"})]}),t.jsxs("div",{className:"px-3 py-2 bg-[var(--surface-primary)] border-t border-border-subtle shrink-0",children:[t.jsxs("div",{className:"flex gap-2.5 items-center",children:[t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:u,type:"text",placeholder:_||`Send message to ${lt(e)}...`,value:d,disabled:!g||!c,onChange:W=>x(W.target.value),onPaste:W=>{const ne=W.clipboardData.getData("text");ne&&x(ae=>ae+ne),W.preventDefault()},onKeyDown:W=>{if(W.key!=="Enter")return;if(W.nativeEvent.isComposing){W.preventDefault();return}W.preventDefault();const ne=d.trim();!g||!ne||A||n(ne).then(ae=>{ae!==!1&&x("")})},className:"w-full h-9 rounded-[18px] px-4 bg-bg-secondary text-[13px] text-text-primary",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))"}})}),t.jsx("button",{onClick:()=>{const W=d.trim();!g||!W||A||n(W).then(ne=>{ne!==!1&&x("")})},disabled:!g||!c||xc({hasDraft:!!d.trim(),isBusy:!!A}),className:`w-9 h-9 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${d.trim()&&!A?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:d.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:d.trim()?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),_&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:_})]})]})}function xp({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 bp({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const a=o.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[i,c]=o.useState(!1);if(o.useEffect(()=>{if(!a){c(!1);return}try{c(localStorage.getItem(a)==="1")}catch{c(!1)}},[a]),!s||!e||e.backend!=="xterm"||i)return null;const l=(r==null?void 0:r.trim())||"This machine",u=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}c(!0)};return t.jsxs("div",{className:"py-2.5 px-5 text-[13px] font-semibold flex items-center gap-2.5",style:{background:"linear-gradient(90deg, rgba(245,158,11,0.12), rgba(245,158,11,0.04))",borderBottom:"1px solid rgba(245,158,11,0.2)",color:"#d97706"},children:[t.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[t.jsxs("span",{children:[l," is using `xterm` fallback."]}),t.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),t.jsx("button",{type:"button",onClick:u,className:"shrink-0 text-[12px] font-semibold px-2 py-1 rounded-md transition-colors",style:{color:"#b45309",background:"rgba(245,158,11,0.1)",border:"1px solid rgba(245,158,11,0.18)"},"aria-label":"Dismiss terminal backend warning",title:"Dismiss",children:"Dismiss"})]})}function Ja({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(yn,{size:n}):t.jsx(es,{size:n})})}function Zo({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function ei({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:i}){const c=wn(e.updatedAt),l=!e.readAt;return t.jsxs("div",{className:`dashboard-header-inbox-item ${l?"is-attention":""}`.trim(),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[s?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",s]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",c].filter(Boolean).join(" · ")]}),e.preview?t.jsx("span",{className:"dashboard-header-inbox-item-meta",children:e.preview}):null]}),t.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[l?t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:u=>{u.stopPropagation(),i()},children:"Delete"})]})]})}function gp({activeConv:e,agentCount:s,wsStatus:r,isConnected:n,conversations:a,onOpenHistory:i,onOpenRemote:c,onStopCli:l,activeCliViewMode:u,onSetCliViewMode:f,onHideConversation:d,hiddenConversations:x=[],onShowConversation:g,onShowAllHidden:w,onResetPanelsToMain:M,inboxOpen:m,onInboxOpenChange:p,hiddenOpen:b,onHiddenOpenChange:h,onOpenNewSession:S,actionShortcuts:R,notifications:k,notificationUnreadCount:I,onOpenNotification:j,onMarkNotificationRead:v,onMarkNotificationUnread:y,onDeleteNotification:E}){const{ides:L,p2pStates:A={}}=js(),_=!!e&&tt(e)&&!Qe(e),B=!!e&&Qe(e),H=u||(e?bc(e)?"terminal":"chat":null),[C,P]=o.useState(!1),U=o.useRef(null),N=o.useRef(null),$=n?"#22c55e":r==="connected"?"#eab308":"#ef4444",z=n?"0 0 4px #22c55e80":r==="connected"?"0 0 4px #eab30880":"0 0 4px #ef444480",q=L.filter(V=>V.type==="adhdev-daemon"),W=Object.values(A),ne=W.filter(V=>V==="connected").length,ae=W.filter(V=>V==="connecting"||V==="new"||V==="checking").length,X=r!=="connected"||q.length===0?null:ae>0&&ne===0?"P2P connecting...":ne>0&&s===0?"Waiting for IDE...":null,pe=o.useMemo(()=>k.filter(V=>!V.readAt),[k]),Y=o.useMemo(()=>k.filter(V=>!!V.readAt),[k]),J=o.useMemo(()=>pe.slice(0,9),[pe]),ue=I;o.useEffect(()=>{if(!m)return;const V=ve=>{var ie;(ie=U.current)!=null&&ie.contains(ve.target)||p(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[m,p]),o.useEffect(()=>{if(!b)return;const V=ve=>{var ie;(ie=N.current)!=null&&ie.contains(ve.target)||h(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[b,h]),o.useEffect(()=>{if(!b&&!m)return;const V=ve=>{if(!ve.altKey)return;const ie=ve.code.match(/^Digit([1-9])$/);if(!ie)return;const ce=Number(ie[1])-1,te=b?x[ce]:void 0,me=m?J[ce]:void 0;if(!(!te&&!me)){if(ve.preventDefault(),ve.stopPropagation(),te){g==null||g(te),h(!1);return}me&&(j(me),p(!1))}};return window.addEventListener("keydown",V,!0),()=>window.removeEventListener("keydown",V,!0)},[x,b,m,J,h,p,j,g]);const le=V=>{if(!V)return;const ve=a.find(ie=>ie.tabKey===V);ve&&(d==null||d(ve))};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(es,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?lt(e):"Dashboard"}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:$,boxShadow:z}})})]}),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:$,boxShadow:z}}),X&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",X]}),S&&t.jsx("button",{type:"button",onClick:S,className:"btn btn-secondary btn-sm ml-2",title:"Start or recover a session","aria-label":"Start or recover a session",children:t.jsx(zd,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[e&&(_||B||!Qe(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:Cs(e)||lt(e),children:lt(e)}),(_||B)&&l&&t.jsxs(t.Fragment,{children:[_&&f&&H&&t.jsx(Ja,{mode:H,onChange:f,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:B?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(At,{size:14})})]}),!Qe(e)&&t.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx($a,{size:14})}),!_&&!Qe(e)&&t.jsx("button",{onClick:c,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Pt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:U,children:[t.jsxs("div",{className:`dashboard-header-hidden${C?" is-drop-target":""}`,ref:N,onDragEnter:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),P(!0))},onDragOver:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),V.dataTransfer.dropEffect="move",P(!0))},onDragLeave:V=>{V.currentTarget.contains(V.relatedTarget)||P(!1)},onDrop:V=>{const ve=V.dataTransfer.getData("text/tab-key");V.preventDefault(),P(!1),le(ve)},children:[t.jsxs("button",{type:"button",onClick:()=>h(!b),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${R!=null&&R.toggleHiddenTabs?` (${R.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(Qi,{size:16}),x.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:x.length})]}),b&&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(Zo,{value:R==null?void 0:R.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"}),x.length>0&&w&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{w(),h(!1)},children:"Restore all"})]})]}),e&&d&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>d(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(Zo,{value:R==null?void 0:R.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:lt(e)})]}),x.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:x.map(V=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{g==null||g(V),h(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:lt(V)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[x.indexOf(V)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",x.indexOf(V)+1]}):null,Cs(V)]})]},V.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>p(!m),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(vn,{size:16}),ue>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:ue})]}),m&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[pe.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),pe.map(V=>t.jsx(ei,{notification:V,shortcutIndex:J.indexOf(V)>=0?J.indexOf(V)+1:void 0,onOpen:()=>j(V),onMarkRead:()=>v(V.id),onMarkUnread:()=>y(V.id),onDelete:()=>E(V.id)},V.id))]}),Y.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),Y.map(V=>t.jsx(ei,{notification:V,onOpen:()=>j(V),onMarkRead:()=>v(V.id),onMarkUnread:()=>y(V.id),onDelete:()=>E(V.id)},V.id))]}),k.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function wt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function yp(e,s){return String(e||"")!==String(s||"")}function vp(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),i=!!s.resumableOnly;return!r&&!n&&!a&&!i?e:e.filter(c=>!(i&&!c.canResume||r&&![c.title,c.preview].map(u=>String(u||"").toLowerCase()).join(`
|
|
31
|
-
`).includes(r)||n&&!String(c.workspace||"").toLowerCase().includes(n)||a&&!uc(c.summaryMetadata).map(u=>u.toLowerCase()).join(`
|
|
32
|
-
`).includes(a)))}function wp(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 Bc(e,s={}){return wp(vp(e,s),s.sortMode||"recent")}function pn(e){return e?"Resume saved history":"Start fresh"}function Qa(e){return e?"Resuming saved history…":"Starting fresh…"}function jp(){return"Start fresh"}function Oc(e,s=!1){return e==="cli"?pn(s):e==="ide"?"Start IDE":"Start ACP session"}function Wc(e,s=!1){return e==="cli"?Qa(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function kp(){return"Recover hosted runtime"}function Sp(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Np(){return"Open saved history"}function Cp(){return"Saved History"}function Za(){return"Use saved history when you want continuity in the same provider conversation."}function Ip(){return"No saved history found yet."}function Ap(){return"Refresh saved history"}function Mp(){return"Refreshing saved history…"}function xs(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function bs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Us(e){return e==="start-fresh"?"Start fresh":"Restart"}function zs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function eo(e){return`Resume saved history with ${e}?`}function to(){return"Review or change the target workspace before resuming saved history."}function Tp(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 so({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:i=!1,isResumingSavedSessionId:c=null,savedHistoryFilters:l,onSavedHistoryFiltersChange:u,onClose:f,onNewChat:d,onSwitchSession:x,onRefreshHistory:g,onResumeSavedSession:w}){var v;const M=s.find(y=>y.id===e.routeId),m=(M==null?void 0:M.chats)||[],p=(v=M==null?void 0:M.activeChat)==null?void 0:v.id,b=tt(e)&&!Qe(e),[h,S]=o.useState(()=>wt()),R=l||h,k=y=>{if(u){u(y);return}S(y)},I=o.useMemo(()=>Bc(a,{textQuery:R.textQuery,workspaceQuery:R.workspaceQuery,modelQuery:R.modelQuery,resumableOnly:R.resumableOnly,sortMode:R.sortMode}),[R.modelQuery,R.resumableOnly,R.sortMode,R.textQuery,R.workspaceQuery,a]),j=t.jsxs("div",{className:"fixed inset-0 z-[1300] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[t.jsx("div",{onClick:f,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:b?Cp():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:pp(e)}),b&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Za()})]}),t.jsx("button",{onClick:f,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:t.jsx(At,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!b&&t.jsx("button",{onClick:d,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),b?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:R.textQuery,onChange:y=>k({...R,textQuery:y.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:R.workspaceQuery,onChange:y=>k({...R,workspaceQuery:y.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:R.modelQuery,onChange:y=>k({...R,modelQuery:y.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:R.sortMode,onChange:y=>k({...R,sortMode:y.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:R.resumableOnly,onChange:y=>k({...R,resumableOnly:y.target.checked})}),"Resume-ready only"]})]}),I.map(y=>{const E=e.providerSessionId===y.providerSessionId,L=E||!y.canResume||!!c;return t.jsxs("button",{type:"button",onClick:()=>{L||!w||w(y)},disabled:L,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${E?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${L?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${E?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:y.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:y.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Tp(y.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:y.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:[y.workspace||"Workspace unknown",Ss(y.summaryMetadata)?` · ${Ss(y.summaryMetadata)}`:"",y.messageCount>0?` · ${y.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:E?"ACTIVE":y.canResume?c===y.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},y.id)})]}):m.map(y=>t.jsxs("div",{onClick:()=>{x(e.routeId,y.id),f()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${p===y.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 ${p===y.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:y.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:[y.id.substring(0,12),"..."]}),p===y.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},y.id)),(b&&!i&&I.length===0||!b&&m.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(Yd,{size:32})}),t.jsx("div",{className:"text-[13px]",children:b?a.length>0?"No saved history matches these filters.":Ip():"No recent chat sessions found."})]}),b&&i&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:Mp()})})]}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:t.jsx("button",{onClick:g,disabled:n||i,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||i?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Gs,{size:13})," ",b?Ap():"Refresh History"]})})})]})]});return typeof document>"u"?j:pr.createPortal(j,document.body)}const ti={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 Hc({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=ti[n.type]||ti.info;return t.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=n.actions)!=null&&i.length||r&&r(n)},children:[t.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),t.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(At,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:a.label})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((i,c)=>t.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:l=>{l.stopPropagation(),i.onClick(),s(n.id)},children:i.label},c))})]})]},n.id)})})}const Lp=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function Rp(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function _p(e){return e.sessionId||e.instanceId||e.agentType}function Un(e,s){return e||s}function si(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 Fc(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=_t(r,{fallbackId:r.id}));return s}function Uc(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 ro(e,s,r={}){return Pp(e,s,Uc(e,r))}function Pp(e,s,r={}){var x,g,w,M,m,p;const n=[],a=r.machineName,i=r.connectionState,c=Rp(e),l=Pu(e.type,{agentName:e.cliName}),u=tt(e)||Qe(e)?l:ot(e.type),f=Array.isArray(e.childSessions)?e.childSessions.map(b=>{var h,S;return{sessionId:b.id,instanceId:b.id,providerSessionId:b.providerSessionId,transport:b.transport,sessionCapabilities:b.capabilities,agentType:b.providerType,agentName:b.providerName||ot(b.providerType),status:b.status,title:b.title,lastMessagePreview:b.lastMessagePreview,lastMessageRole:b.lastMessageRole,lastMessageAt:b.lastMessageAt,lastMessageHash:b.lastMessageHash,messages:((h=b.activeChat)==null?void 0:h.messages)||[],activeModal:((S=b.activeChat)==null?void 0:S.activeModal)||void 0,unread:b.unread,lastSeenAt:b.lastSeenAt,lastUpdated:b.lastUpdated,inboxBucket:b.inboxBucket,surfaceHidden:b.surfaceHidden}}):[],d=Lp(e);if(d){const b=e.sessionId||e.instanceId,h=l,S=(x=e.activeChat)==null?void 0:x.activeModal,R=S&&Array.isArray(S.buttons)&&S.buttons.length>0,k=St((g=e.activeChat)==null?void 0:g.status,{activeModal:(w=e.activeChat)==null?void 0:w.activeModal})||St((m=(M=e.agents)==null?void 0:M[0])==null?void 0:m.status)||"idle",I=e.activeChat||{title:"",messages:[]};let j=I.title&&String(I.title).trim()?String(I.title).trim():"";const v=(p=e.activeChat)==null?void 0:p.id,y=e.chats;if(v&&Array.isArray(y)&&y.length>0){const H=y.find(C=>C.id===v||C.id&&String(C.id)===String(v));H!=null&&H.title&&String(H.title).trim()&&(j=String(H.title).trim())}const E=(tt(e)||Qe(e),e.type),L=(tt(e)||Qe(e))&&Fo(j,h,E)?"":j,A=I.messages||[],_=si(s,[e.id,b]),B=Jo(A,_);n.push({routeId:e.id,sessionId:b,providerSessionId:e.providerSessionId,nativeSessionId:b,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:tt(e)?e.mode||"terminal":"chat",agentName:h,agentType:E,status:k,title:L,messages:[...A,...B],resume:e.resume,hostIdeType:!tt(e)&&!Qe(e)?e.type:void 0,workspaceName:c,displayPrimary:L||c||(tt(e)?e.mode==="chat"?h:"Terminal":h),displaySecondary:u,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,modalButtons:R?S.buttons:void 0,modalMessage:R?S.message:void 0,streamSource:"native",tabKey:Un(b,e.id),machineName:a,connectionState:i})}if(d&&(tt(e)||Qe(e)))return n;for(const b of f){const h=b.activeModal&&Array.isArray(b.activeModal.buttons)&&b.activeModal.buttons.length>0,S=Du(b),R=_p(b),k=`${e.id}:${R}`,I=b.title&&String(b.title).trim()||"",j=Fo(I,b.agentName,b.agentType)?"":I,v=b.messages||[],y=si(s,[k,b.sessionId,b.instanceId]),E=Jo(v,y);(b.transport==="cdp-webview"||b.sessionId||b.providerSessionId||v.length>0||E.length>0||h||j||!["idle","panel_hidden","disconnected","not_monitored"].includes(S))&&n.push({routeId:e.id,sessionId:b.sessionId||b.instanceId,providerSessionId:b.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:b.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:b.sessionCapabilities,mode:"chat",agentName:b.agentName,agentType:b.agentType,status:S,title:j,messages:[...v,...E],hostIdeType:e.type,workspaceName:c,displayPrimary:j||c||b.agentName||u,displaySecondary:`${u} · ${b.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:b.lastMessagePreview,lastMessageRole:b.lastMessageRole,lastMessageAt:b.lastMessageAt,lastMessageHash:b.lastMessageHash,lastUpdated:b.lastUpdated||e.lastUpdated,modalButtons:h?b.activeModal.buttons:void 0,modalMessage:h?b.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Un(b.sessionId||b.instanceId,k),machineName:a,connectionState:i})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:l,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:c,displayPrimary:c||u,displaySecondary:u,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Un(e.sessionId||e.instanceId,e.id),connectionState:i}),n}function Dp(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 Ep(e,s){const r=Dp(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const zc=[{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:"🏄"}],Vc=[{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:"🧩"}],Gc=[{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:"🟠"}],$p=zc,Kp=Vc,Bp=Gc;function Is(...e){return bd(gd(e))}function Op({icon:e,title:s,subtitle:r,badge:n,actions:a,className:i}){return t.jsxs("div",{className:Is("dashboard-header",i),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[n.count!==void 0?n.count:""," ",n.text]})]}),r&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&t.jsx("div",{className:"flex gap-2",children:a})]})}function qc({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(Op,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:Is("mx-auto flex w-full flex-col gap-4",i,c),children:l})})]})}function Rt({title:e,icon:s,description:r,accentColor:n,className:a,children:i}){return t.jsxs("div",{className:Is("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),i]})}function Yc({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:Is("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Wp={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"},Hp={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Wr({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:Is("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Wp[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:Hp[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 Fp={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"},Up={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function zp({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:Is("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Fp[e],r),children:[t.jsx("span",{className:Is("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Up[e])}),n]})}const ka="adhdev:themechange";function Vp(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ts(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ls(e){return e==="system"?Vp():e}function Xc(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function tn(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(ka,{detail:{preference:e,theme:s}}))}function Gp(){const e=Ts(),s=Ls(e);Xc(s),tn(e,s)}function no(){const[e,s]=o.useState(Ts),[r,n]=o.useState(()=>Ls(Ts()));o.useEffect(()=>{Xc(r)},[r]),o.useEffect(()=>{const c=window.matchMedia("(prefers-color-scheme: light)"),l=u=>{if(e==="system"){const f=u.matches?"light":"dark";n(f),tn("system",f)}};return c.addEventListener("change",l),()=>c.removeEventListener("change",l)},[e]),o.useEffect(()=>{const c=u=>{const f=u.detail||{},d=f.preference,x=f.theme;s(d==="dark"||d==="light"||d==="system"?d:Ts()),n(x==="dark"||x==="light"?x:Ls(Ts()))},l=u=>{if(u.key!=="theme")return;const f=Ts(),d=Ls(f);s(f),n(d)};return window.addEventListener(ka,c),window.addEventListener("storage",l),()=>{window.removeEventListener(ka,c),window.removeEventListener("storage",l)}},[]);const a=o.useCallback(c=>{const l=Ls(c);s(c),n(l);try{localStorage.setItem("theme",c)}catch{}tn(c,l)},[]),i=o.useCallback(()=>{s(c=>{const l=c==="dark"?"light":c==="light"?"system":"dark",u=Ls(l);n(u);try{localStorage.setItem("theme",l)}catch{}return tn(l,u),l})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:i,isDark:r==="dark"}}const ri={dark:"Dark",light:"Light",system:"System"};function qp({collapsed:e}){const{preference:s,cycleTheme:r}=no(),n=s==="dark"?t.jsx(Jd,{size:16}):s==="light"?t.jsx(Xd,{size:16}):t.jsx(Qd,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${ri[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:ri[s]})]})}function us({label:e,description:s,checked:r,disabled:n,onChange:a,extra:i}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[i,t.jsxs("button",{type:"button",role:"switch","aria-checked":r,"aria-disabled":n,disabled:n,onClick:()=>a(!r),className:`relative inline-flex items-center ${n?"cursor-not-allowed":"cursor-pointer"}`,children:[t.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:r?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),t.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${r?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Yp({onPrefChange:e}){const[s,r]=zu(),[n,a]=o.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);o.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,l)=>{r({[c]:l}),e==null||e(c,l)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(vn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:c=>i("globalEnabled",c)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Pt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:c=>i("browserNotifications",c)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),n==="default"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{fc().then(a)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),n==="denied"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),n==="unsupported"&&t.jsx("div",{className:"text-[11px] text-amber-300",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Zd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:c=>i("completionAlert",c)}),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(eu,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:c=>i("approvalAlert",c)}),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(hr,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!s.globalEnabled&&t.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function fn(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Xp(e,s){const r=fn(e),n=fn(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 Jc(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function dr(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Xp(r,s)>=0)return!1;const n=fn(r),a=fn(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Jp(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function zn(e,s){return e instanceof Error?e.message:s}function Qp({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(Yc,{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(ef,{ide:c,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},c.id))})}function ni({title:e,message:s,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:i}){const c=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return pr.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:i,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:l=>l.stopPropagation(),children:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick:i,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),t.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:n==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:r})]})]})}),document.body)}function Zp(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...$p,...Kp,...Bp].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 ef({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var B,H;const[i,c]=o.useState("idle"),[l,u]=o.useState(""),[f,d]=o.useState(null),[x,g]=o.useState("idle"),[w,M]=o.useState(""),m=e.version||null,p=((B=e.machine)==null?void 0:B.platform)||((H=e.system)==null?void 0:H.platform)||"",b=_t(e,{fallbackId:e.id}),h=p==="win32"?"🪟":p==="darwin"?"🍎":"🐧",S=s.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),R=s.filter(C=>C.daemonId===e.id&&C.transport==="pty"),k=s.filter(C=>C.daemonId===e.id&&C.transport==="acp"),I=e.p2p,j=async()=>{if(r){c("upgrading"),u("Starting upgrade...");try{const C=Jp(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(c("done"),u(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(c("done"),u(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(c("error"),u(C.error||"Upgrade failed"))}catch(C){c("error"),u(zn(C,"Connection lost during upgrade"))}}},v=async()=>{if(d(null),!!n){g("loading");try{await n(e.id),g("done"),M("Machine disconnected.")}catch(C){g("error"),M(zn(C,"Failed to disconnect"))}}},y=async()=>{if(d(null),!!a){g("loading");try{await a(e.id),g("done"),M("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){g("error"),M(zn(C,"Failed to revoke token"))}}},E="0.8.93",L=Jc(e,E),A=dr(e,E),_=S.length+R.length+k.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-xl",children:h}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:b}),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),"…"]}),m&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",m,!L&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&t.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${E}`,children:i==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):i==="done"?"✓ Updated":`${A?"↑ Update now":`↑ Update${` to v${E}`}`}`}),n&&t.jsx("button",{onClick:()=>d("disconnect"),disabled:x==="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:()=>d("revoke"),disabled:x==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(zp,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[I&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${I.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${I.state==="connecting"||I.state==="new"?"animate-pulse":""}`,style:I.state==="connecting"||I.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",I.state==="connected"?"connected":I.state==="connecting"||I.state==="new"?"connecting...":I.state||"off"]}),I.peers!==void 0&&I.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",I.peers," peer",I.peers!==1?"s":"",")"]})]}),I&&_>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),_>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[S.map(C=>{const P=Zp(C.type),U=C.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:P.icon}),t.jsx("span",{children:P.name}),U!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${U?"bg-green-400":"animate-pulse"}`,style:U?void 0:{background:"var(--status-warning)"},title:U?"CDP connected":"CDP connecting..."})]},C.id)}),R.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:C.cliName||"CLI"})]},C.id)),k.map(C=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:C.cliName||"ACP"})]},C.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(l||w)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||x==="error"?"text-red-400":i==="done"||x==="done"?"text-green-400":"text-text-muted"}`,children:w||l})]}),f==="disconnect"&&t.jsx(ni,{title:"🔌 Disconnect Machine",message:`Disconnect "${b}" 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:v,onCancel:()=>d(null)}),f==="revoke"&&t.jsx(ni,{title:"⚠️ Remove Machine",message:`Remove "${b}" 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:y,onCancel:()=>d(null)})]})}const tf=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function sf(){const{preference:e,setPreference:s}=no();return t.jsx("div",{className:"flex gap-2",children:tf.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 rf(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 nf(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function Vn(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function ai(e){const{r:s,g:r,b:n}=nf(e);return .2126*Vn(s)+.7152*Vn(r)+.0722*Vn(n)}function oi(e,s){const r=ai(e),n=ai(s),a=Math.max(r,n),i=Math.min(r,n);return(a+.05)/(i+.05)}function Qc(e){const s=rf(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return oi(s,r)>=oi(s,n)?r:n}const Sa={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},Na={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},af=[{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"}}}],Zc="adhdev-chat-theme",el="adhdev-chat-theme-custom";function sn(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Zc)||"ember"}catch{return"ember"}}function Wt(e){try{const s=localStorage.getItem(el);if(s){const r=JSON.parse(s);return{...e==="dark"?Sa:Na,...r[e]}}}catch{}return e==="dark"?Sa:Na}function Hr(e,s){try{localStorage.setItem(el,JSON.stringify({dark:e,light:s}))}catch{}}function Kt(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 hn(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 of={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function ur(e,s){var a;const r=(a=of[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",hn(r,24)),n.style.setProperty("--accent-on-primary",Qc(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${hn(r,18)})`),n.style.setProperty("--border-accent",Kt(r,.35)),n.style.setProperty("--nav-active-bg",Kt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Kt(r,.06)}`)}function gs(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Kt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Kt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Kt(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",Kt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Kt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",hn(e.accentColor,30)),s.style.setProperty("--accent-on-primary",Qc(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${hn(e.accentColor,40)})`),s.style.setProperty("--border-accent",Kt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Kt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Kt(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 ${Kt(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 ao(){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 cf(e){try{localStorage.setItem(Zc,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ys()?"dark":"light";gs(Wt(s))}else ao(),ur(e,ys()?"dark":"light")}function lf(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=sn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ys()?"dark":"light";gs(Wt(s))}else ao(),ur(e,ys()?"dark":"light")}function ys(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function kt({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,onChange:n=>{/^#[0-9a-fA-F]{0,6}$/.test(n.target.value)&&r(n.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function er({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function df({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=o.useState(()=>Wt(r));o.useEffect(()=>{a(Wt(r))},[r]);const i=o.useCallback((c,l)=>{a(u=>{const f={...u,[c]:l},x=Wt(r==="dark"?"light":"dark");return r==="dark"?Hr(f,x):Hr(x,f),gs(f),s(f),f})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:["🎨 Custom Theme Editor",t.jsxs("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:[e?"🌙 Dark":"☀️ Light"," mode"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(er,{title:"App Background",children:[t.jsx(kt,{label:"Background",value:n.bgPrimary,onChange:c=>i("bgPrimary",c)}),t.jsx(kt,{label:"Surface",value:n.bgSecondary,onChange:c=>i("bgSecondary",c)}),t.jsx(kt,{label:"Card",value:n.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),t.jsxs(er,{title:"App Text",children:[t.jsx(kt,{label:"Primary",value:n.textPrimary,onChange:c=>i("textPrimary",c)}),t.jsx(kt,{label:"Secondary",value:n.textSecondary,onChange:c=>i("textSecondary",c)}),t.jsx(kt,{label:"Muted",value:n.textMuted,onChange:c=>i("textMuted",c)})]}),t.jsxs(er,{title:"Borders & Accent",children:[t.jsx(kt,{label:"Border subtle",value:n.borderSubtle,onChange:c=>i("borderSubtle",c)}),t.jsx(kt,{label:"Border default",value:n.borderDefault,onChange:c=>i("borderDefault",c)}),t.jsx(kt,{label:"Accent",value:n.accentColor,onChange:c=>i("accentColor",c)})]})]}),t.jsxs("div",{children:[t.jsxs(er,{title:"Chat Bubbles",children:[t.jsx(kt,{label:"User bubble",value:n.userBubble,onChange:c=>i("userBubble",c)}),t.jsx(kt,{label:"User text",value:n.userText,onChange:c=>i("userText",c)}),t.jsx(kt,{label:"Agent bubble",value:n.assistantBubble,onChange:c=>i("assistantBubble",c)}),t.jsx(kt,{label:"Agent text",value:n.assistantText,onChange:c=>i("assistantText",c)})]}),t.jsxs(er,{title:"Chat Layout",children:[t.jsx(kt,{label:"Chat BG",value:n.containerBg,onChange:c=>i("containerBg",c)}),t.jsx(kt,{label:"Send button",value:n.sendButton,onChange:c=>i("sendButton",c)}),t.jsx(kt,{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?Sa:Na,u=Wt(e?"light":"dark");e?Hr(c,u):Hr(u,c),a(c),gs(c),s(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:"Reset to defaults"})]})}function uf(){const[e,s]=o.useState(sn),[r,n]=o.useState(!0),[a,i]=o.useState(()=>Wt("dark"));o.useEffect(()=>{n(ys());const u=new MutationObserver(()=>{const x=ys();n(x);const g=sn();g==="custom"?gs(Wt(x?"dark":"light")):ur(g,x?"dark":"light")});u.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const f=window.matchMedia("(prefers-color-scheme: dark)"),d=()=>{const x=ys();n(x);const g=sn();g==="custom"?gs(Wt(x?"dark":"light")):ur(g,x?"dark":"light")};return f.addEventListener("change",d),()=>{u.disconnect(),f.removeEventListener("change",d)}},[]),o.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?gs(Wt(r?"dark":"light")):(ao(),ur(e,r?"dark":"light"))},[e,r]),o.useEffect(()=>{i(Wt(r?"dark":"light"))},[r]);const c=u=>{s(u),cf(u)},l=[...af,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:l.map(u=>{const f=e===u.id,d=r?u.preview.dark:u.preview.light,x=u.id==="honey"||u.id==="ember"?"#1a1a1a":u.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>c(u.id),className:"text-left rounded-xl p-3 transition-all",style:{background:f?"var(--bg-glass-hover)":"var(--bg-glass)",border:f?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:f?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:d.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:d.userBubble,color:x},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:d.assistantBubble,border:d.assistantBorder,color:d.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[f&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:u.id==="custom"?"🎨 Custom":u.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:u.description})]})]})]},u.id)})}),e==="custom"&&t.jsx(df,{dark:r,onColorsChange:u=>i(u)})]})}const oo="adhdev_mobileDashboardMode_v1",Ca="adhdev:mobile-dashboard-mode-change";function io(){try{return localStorage.getItem(oo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function mf(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??io())},r=a=>{const i=a.detail;s(i)},n=a=>{a.key&&a.key!==oo||s()};return window.addEventListener(Ca,r),window.addEventListener("storage",n),()=>{window.removeEventListener(Ca,r),window.removeEventListener("storage",n)}}function pf(e){try{localStorage.setItem(oo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ca,{detail:e}))}function ff(){const[e,s]=o.useState(!0);return o.useEffect(()=>{s(io()==="chat")},[]),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(es,{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),pf(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const Gn=new Map,ii=new Map;function hf(e){if(!e||typeof e!="object")return null;const s=e,r=s.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof s.timestamp=="number"?s.timestamp:void 0}}function xf(e,s,r,n){return{...e||{},id:s,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n,platform:r.platform,machine:r}}function tl(){const{sendCommand:e}=Tt(),{injectEntries:s,getIdes:r}=fr();return o.useCallback(async(n,a)=>{if(!n)return;const i=(a==null?void 0:a.minFreshMs)??Tm,c=ii.get(n)||0;if(!(a!=null&&a.force)&&c>0&&Date.now()-c<i)return;const l=Gn.get(n);if(l)return l;const u=(async()=>{const f=await e(n,"get_machine_runtime_stats"),d=hf(f);if(!d)return;const x=r().find(w=>w.id===n),g=xf(x,n,d.machine,d.timestamp||Date.now());s([g]),ii.set(n,Date.now())})().finally(()=>{Gn.delete(n)});return Gn.set(n,u),u},[r,s,e])}function bf(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 gf(e,s){const{sendData:r}=Tt(),{injectEntries:n,getIdes:a}=fr(),i=Array.from(new Set(e.filter(Boolean))).join("|");o.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const c=i?i.split("|"):[];if(c.length===0)return;const l=c.map(u=>os.subscribe({sendData:r},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:s==null?void 0:s.intervalMs}},d=>{const x=a().find(w=>w.id===u),g=bf(x,u,d);n([g])}));return()=>{l.forEach(u=>u())}},[i,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function sl(e,s){const{sendData:r}=Tt(),[n,a]=o.useState(null),[i,c]=o.useState(!1);return o.useEffect(()=>{if(!e){a(null),c(!1);return}if(!(s!=null&&s.enabled)||!r){c(!1);return}a(null),c(!0);let l=null;const u=os.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},f=>{l&&(clearTimeout(l),l=null),a(f.diagnostics),c(!1)});return u.initialSendAccepted?l=setTimeout(()=>{c(!1)},Pm):c(!1),()=>{l&&clearTimeout(l),u()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:i,applyDiagnostics:a}}function yf(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function rl(e){const{sendData:s}=Tt(),[r,n]=o.useState({});return o.useEffect(()=>{const a=yf(e);if(!a||!e.sessionId||!s){n({});return}const i=os.subscribe({sendData:s},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},c=>{n({status:c.status,modalMessage:c.modalMessage,modalButtons:c.modalButtons}),Ks.record({interactionId:c.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:c.status,modalButtonCount:Array.isArray(c.modalButtons)?c.modalButtons.length:0}})});return i.initialSendAccepted||n({}),()=>{i()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const nl="adhdev_hiddenTabs";function vf(){try{const e=localStorage.getItem(nl);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function As(e){try{localStorage.setItem(nl,JSON.stringify([...e]))}catch{}}function Fr(e){return Wa(e)}function co(e,s){return rs(s).some(r=>e.has(r))}function wf(){const[e,s]=o.useState(vf),r=o.useCallback(f=>{s(d=>{const x=new Set(d);return x.has(f)?x.delete(f):x.add(f),As(x),x})},[]),n=o.useCallback(f=>{s(d=>{if(d.has(f))return d;const x=new Set(d);return x.add(f),As(x),x})},[]),a=o.useCallback(f=>{s(d=>{if(!d.has(f))return d;const x=new Set(d);return x.delete(f),As(x),x})},[]),i=o.useCallback(()=>{s(f=>{if(f.size===0)return f;const d=new Set;return As(d),d})},[]),c=o.useCallback((f,d)=>{s(x=>{const g=new Set(x);for(const w of d)g.add(w);return As(g),g})},[]),l=o.useCallback((f,d)=>{s(x=>{const g=new Set(x);for(const w of d)g.delete(w);return As(g),g})},[]),u=o.useCallback(f=>co(e,f),[e]);return{hiddenTabs:e,toggleTab:r,hideTab:n,showTab:a,showAllTabs:i,hideAllForDaemon:c,showAllForDaemon:l,isHidden:u}}function al(e){return e instanceof Error?e.message:String(e||"")}function lo(e){const s=al(e);return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("P2P channel not open")||s.includes("P2P not available")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function uo(e){const s=al(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function ci(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 jf(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=ci(a,s),c=Array.isArray(a.childSessions)?a.childSessions.map(u=>ci(u,s)):a.childSessions,l=c!==a.childSessions;return i!==a||l?(r=!0,{...i,...l?{childSessions:c}:{}}):a});return r?n:e}function ol(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 kf(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))ol(s,a)===i&&(delete n[a],r=!0);return r?n:e}function Sf({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){o.useEffect(()=>{fc()},[]);const a=o.useMemo(()=>e.map(i=>({id:i.tabKey,name:$c(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null})),[e]);return qu(a),o.useEffect(()=>{if(Object.keys(s).length===0)return;const c=setTimeout(()=>{r(l=>{const u=Date.now(),f={};for(const[d,x]of Object.entries(l))u-x<5e3&&(f[d]=x);return Object.keys(f).length===Object.keys(l).length?l:f})},5500);return()=>clearTimeout(c)},[s,r]),o.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;n(l=>{const u=l.filter(f=>f.timestamp>c).slice(-100);return u.length===l.length?l:u})},6e4);return()=>clearInterval(i)},[n]),null}function Nf(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 qn(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 Cf(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 li(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?Cf(Os(r.content)):"";return[e.id||"",e.title||"",e.status||"",s.length,String((r==null?void 0:r.id)||""),String((r==null?void 0:r.index)??""),String((r==null?void 0:r.receivedAt)??(r==null?void 0:r.timestamp)??""),n].join(":")}function If(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||""),li(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastUpdated||""),li(r.activeChat)].join(":"))].join("|")}function Af(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 Mf(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 Tf(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 Lf(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const i of rs({routeId:n.routeId}))r.set(i,a);for(const i of rs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(i,n.streamSource==="native"?a:n);for(const i of rs({tabKey:n.tabKey}))r.set(i,n)}return r}function Rf(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function _f(e){const s=Rf(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=Os(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Pf({ides:e,connectionStates:s,localUserMessages:r,clearedTabs:n,hiddenTabs:a}){const i=o.useMemo(()=>Nf(e),[e]),c=o.useMemo(()=>Fc(e),[e]),l=o.useRef([]),u=o.useRef([]),f=o.useRef([]),d=o.useRef(new Map),x=o.useRef(new Map),g=o.useMemo(()=>{const k=new Map,I=[];for(const E of i){const{connectionState:L="new",machineName:A}=Uc(E,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),_=Mf(E,r),B=If(E),H=d.current.get(E.id);if(H&&H.ide===E&&H.sourceSignature===B&&H.connectionState===L&&H.machineName===A&&Tf(H.localRefs,_)){k.set(E.id,H),I.push(...H.conversations);continue}const C=ro(E,r,{machineNames:c,connectionStates:s,defaultConnectionState:"new"}),P={ide:E,sourceSignature:B,connectionState:L,machineName:A,localRefs:_,conversations:C};k.set(E.id,P),I.push(...C)}d.current=k;const j=new Map,v=E=>{const L=_f(E),A=x.current.get(E.tabKey);if(A&&A.signature===L)return j.set(E.tabKey,A),A.timestamp;const _={signature:L,timestamp:jc(E)||(A==null?void 0:A.timestamp)||0};return j.set(E.tabKey,_),_.timestamp},y=[...I].sort((E,L)=>kc(E,L,v));return x.current=j,y},[i,r,s,c]),w=o.useMemo(()=>{const k=Af(g,n);return qn(l.current,k)?l.current:(l.current=k,k)},[g,n]),M=o.useMemo(()=>{const k=new Map,I=Array.from(new Set(w.map(j=>j.routeId)));for(const j of I){const v=Ht(w,j);v&&k.set(j,v)}return k},[w]),m=o.useMemo(()=>{const k=new Map;for(const I of w){const j=M.get(I.routeId),v=I.streamSource==="native"&&j?j:I;for(const y of rs({providerSessionId:I.providerSessionId,sessionId:I.sessionId}))k.set(y,v)}return k},[w,M]),p=o.useMemo(()=>Lf(w,M),[w,M]),b=o.useCallback(k=>{if(k)return m.get(k)},[m]),h=o.useCallback(k=>{if(k)return p.get(k)},[p]),S=o.useMemo(()=>{const k=w.filter(I=>!co(a,I));return qn(u.current,k)?u.current:(u.current=k,k)},[w,a]),R=o.useMemo(()=>{const k=S.map(I=>I.tabKey);return qn(f.current,k)?f.current:(f.current=k,k)},[S]);return{chatIdes:i,conversations:w,visibleConversations:S,visibleTabKeys:R,resolveConversationBySessionId:b,resolveConversationByTarget:h}}function Df({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const a=o.useMemo(()=>{var l;return e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),i=o.useMemo(()=>{var l;return!e||!s?null:((l=r(s))==null?void 0:l.tabKey)??null},[e,r,s]),c=o.useCallback(()=>{s&&n(l=>{const u=new URLSearchParams(l);return u.delete("activeTab"),u},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:i,consumeRequestedActiveTab:c}}function Ef({ides:e,sendDaemonCommand:s,setToasts:r,setLocalUserMessages:n,resolveConversationByTarget:a}){o.useEffect(()=>{st.setIdes(e)},[e]),o.useEffect(()=>{st.setResolveAction((i,c,l)=>{s(i,c,l).catch(()=>{})})},[s]),o.useEffect(()=>{const i=st.onToast(u=>{r(d=>d.some(g=>g.message===u.message&&u.timestamp-g.timestamp<3e3)?d:[...d.slice(-4),{id:u.id,message:u.message,type:u.type,timestamp:u.timestamp,targetKey:u.targetKey,actions:u.actions}]);const f=u.duration||5e3;setTimeout(()=>r(d=>d.filter(x=>x.id!==u.id)),f)}),c=st.onSystemMessage((u,f)=>{var w,M;const d=a(u),x=(w=f._localId)==null?void 0:w.startsWith("sys_approval_"),g=!!(d&&(d.status==="waiting_approval"||(M=d.modalButtons)!=null&&M.length||d.modalMessage));x&&g||n(m=>({...m,[u]:[...m[u]||[],f]}))}),l=st.onClearSystemMessage((u,f)=>{n(d=>{var x;return(x=d[u])!=null&&x.length?{...d,[u]:d[u].filter(g=>{var w;return!(g.role==="system"&&((w=g._localId)!=null&&w.startsWith(f)))})}:d})});return()=>{i(),c(),l()}},[r,n]),o.useEffect(()=>{const i=_c.on("status_event",c=>{st.handleRawEvent(c,"ws")});return()=>{i()}},[]),o.useEffect(()=>{var c;const i=l=>{var p;const u=l.data;if((u==null?void 0:u.type)!=="notification_action"||typeof u.action!="string"||!u.action.startsWith("approval_")||!(u.daemonId||u.targetSessionId||u.targetKey))return;const f=u.targetSessionId||u.targetKey||u.daemonId,d=a(f),x=(d==null?void 0:d.routeId)||u.daemonId;if(!x)return;const g=Number(u.buttonIndex),w=u.button||((p=d==null?void 0:d.modalButtons)==null?void 0:p[g])||"Approve",M=String(w).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),m=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(M);s(x,"resolve_action",{action:m?"approve":"reject",button:w,...Number.isFinite(g)&&{buttonIndex:g},...(d==null?void 0:d.sessionId)&&{targetSessionId:d.sessionId},...u.targetSessionId&&{targetSessionId:u.targetSessionId}}).catch(b=>console.error("[SW Action] approval failed:",b))};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 $f="adhdev_dashboardLayout_v1",Kf="adhdev_dashboardDockview_v1",Bf="adhdev_dashboardDockviewHiddenRestore_v1",tr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function mo(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function il(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function cl(e){return`${$f}:${e}`}function Of(e){const s=cl(e);return mo(s,null)}function Wf(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=cl(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function ll(e){return`${Kf}:${e}`}function Hf(e){const s=ll(e);return mo(s,null)}function Ff(e,s){try{const r=ll(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function dl(e){return`${Bf}:${e}`}function Uf(e){const s=dl(e);return mo(s,{})}function zf(e,s){try{const r=dl(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Vf(){return{groupAssignments:[...tr.groupAssignments],focusedGroup:tr.focusedGroup,groupActiveTabIds:{...tr.groupActiveTabIds},groupTabOrders:{...tr.groupTabOrders},groupSizes:[...tr.groupSizes]}}function Gf(){const[e]=o.useState(()=>il(typeof window<"u"?window.innerWidth:1280)),[s,r]=o.useState(()=>new Map),[n,a]=o.useState(0),[i,c]=o.useState({}),[l,u]=o.useState({}),[f,d]=o.useState([]),[x,g]=o.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,M]=o.useState(!1),m=o.useCallback(()=>{if(w)return;const p=Of(e)??Vf();r(new Map(p.groupAssignments)),a(p.focusedGroup),c(p.groupActiveTabIds),u(p.groupTabOrders),d(p.groupSizes),M(!0)},[w,e]);return o.useEffect(()=>{w&&Wf(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:i,groupTabOrders:l,groupSizes:f})},[w,e,s,n,i,l,f]),o.useEffect(()=>{const p=window.matchMedia("(max-width: 767px)"),b=h=>g(h.matches);return p.addEventListener("change",b),()=>p.removeEventListener("change",b)},[]),{groupAssignments:s,setGroupAssignments:r,focusedGroup:n,setFocusedGroup:a,groupActiveTabIds:i,setGroupActiveTabIds:c,groupTabOrders:l,setGroupTabOrders:u,groupSizes:f,setGroupSizes:d,isMobile:x,hasHydratedStoredLayout:w,hydrateStoredLayout:m}}function qf(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Oa(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Yf({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:i,setGroupActiveTabIds:c,setFocusedGroup:l,setSearchParams:u,historyModalOpen:f,activeConv:d,isRefreshingHistory:x,ides:g,handleRefreshHistory:w}){const M=o.useRef(!1),m=o.useRef(!1),p=o.useRef(null),b=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 S=n.get(h.tabKey)??0;c(R=>({...R,[S]:h.tabKey})),l(S),M.current=!0,m.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),u(R=>{const k=new URLSearchParams(R);return k.delete("activeTab"),k},{replace:!0})},[e,s,r,n,a,i,c,l,u]),o.useEffect(()=>{if(!(m.current||a)&&s.length!==0){if(!e){i(),m.current=!0;return}if(M.current){m.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(m.current||a)&&(i(),m.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,s.length,a,i]),o.useEffect(()=>{if(!f){b.current=!1;return}if(!d||b.current||x)return;const h=g.find(S=>S.id===d.routeId);h&&(!h.chats||h.chats.length===0||qf(h.chats,d))&&(b.current=!0,w())},[f,d,x,g,w]),o.useEffect(()=>{if(!d)return;let h=null,S=0,R=-1,k=0;const I=()=>{h=null;const j=Array.from(document.querySelectorAll("[data-chat-scroll]")).filter(y=>y.offsetParent!==null);if(j.length===0){S<18&&(S+=1,h=requestAnimationFrame(I));return}let v=0;for(const y of j)y.scrollTop=y.scrollHeight,v+=y.scrollHeight;v===R?k+=1:(k=0,R=v),S+=1,!(k>=2||S>=18)&&(h=requestAnimationFrame(I))};return h=requestAnimationFrame(I),()=>{h!=null&&cancelAnimationFrame(h)}},[d==null?void 0:d.tabKey])}function Xf({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:i,ides:c,resolveConversationByTarget:l}){const[u,f]=o.useState(null),[d,x]=o.useState(null),g=o.useMemo(()=>{if(e||!n)return null;const b=l(n);return b&&!tt(b)&&!Qe(b)?b:null},[e,n,l]),w=o.useMemo(()=>{const b=u==null?void 0:u.routeId;if(!b)return null;const h=u!=null&&u.tabKey?i.find(S=>S.tabKey===u.tabKey):a?i.find(S=>S.tabKey===a):null;return(h==null?void 0:h.routeId)===b?h:Ht(i,b)},[i,u,a]),M=o.useMemo(()=>{if(w)return c.find(b=>b.id===w.routeId)},[c,w]);o.useEffect(()=>{g&&(f({routeId:g.routeId,tabKey:Vo(g)}),x(g),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,g]);const m=o.useCallback(b=>{b&&(f({routeId:b.routeId,tabKey:Vo(b)}),x(b))},[]),p=o.useCallback(()=>{f(null),x(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:M,remoteDialogActiveConv:d,setRemoteDialogActiveConv:x,openRemoteDialog:m,closeRemoteDialog:p}}function Yn(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=Oa(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function di({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setLocalUserMessages:i,setClearedTabs:c}){const[l,u]=o.useState(!1),[f,d]=o.useState(!1),x=o.useCallback(async m=>{try{await e("standalone","launch_ide",{ideType:m,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),g=o.useCallback(async(m,p)=>{try{const b=m||(s==null?void 0:s.daemonId)||"",h=await e(b,"switch_chat",{id:p,sessionId:p,...Es(s)}),S=h==null?void 0:h.result;if((h==null?void 0:h.success)===!0||S==="switched"||S==="switched-by-title")return;S===!1||S==="not_found"?Zs(a,"⚠️ Session tab not found — try refreshing history"):typeof S=="string"&&S.startsWith("error:")?Zs(a,`⚠️ Switch error: ${S}`):Zs(a,"⚠️ Session switch failed")}catch(b){console.error("Switch failed",b),Zs(a,`❌ Switch failed: ${b.message||"connection error"}`)}},[s,e,a]),w=o.useCallback(async()=>{if(!(!s||l)){u(!0);try{const m=yr(s);await e(m,"new_chat",{...Es(s)}),c(p=>({...p,[s.tabKey]:Date.now()})),i(p=>({...p,[s.tabKey]:[]}))}catch(m){console.error("New chat failed",m)}finally{u(!1)}}},[s,l,e,c,i]),M=o.useCallback(async()=>{var m,p;if(!(!s||f)){d(!0);try{const b=yr(s),h=async()=>e(b,"list_chats",{forceExpand:!0,...Es(s)});let S=await h(),R=(S==null?void 0:S.chats)||((m=S==null?void 0:S.result)==null?void 0:m.chats);Yn(R,s)&&(await new Promise(k=>setTimeout(k,450)),S=await h(),R=(S==null?void 0:S.chats)||((p=S==null?void 0:S.result)==null?void 0:p.chats)),S!=null&&S.success&&Array.isArray(R)&&(n(s.routeId,R),Yn(R,s)&&!Yn(r,s)&&Zs(a,"⚠️ History dialog did not fully open — try once more"))}catch(b){console.error("Refresh history failed",b)}finally{d(!1)}}},[s,r,f,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:f,handleLaunchIde:x,handleSwitchSession:g,handleNewChat:w,handleRefreshHistory:M}}function Jf(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 Qf(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function ui(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 Ur(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[c,l]of e)!r.has(c)||l<=0||n.includes(l)||n.push(l);n.sort((c,l)=>c-l);const a={};n.forEach((c,l)=>{a[c]=l}),n.length===0&&(a[0]=0);const i=new Map;for(const[c,l]of e){if(!r.has(c)||l<=0)continue;const u=a[l];typeof u=="number"&&u>0&&i.set(c,u)}return{assignments:i,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function mi(e,s){const r={};for(const[n,a]of Object.entries(e)){const i=s[Number(n)];typeof i=="number"&&(r[i]=a)}return r}function Zf(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(a=>a<e)??s[0];return r[n]??0}function eh(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 pi(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 fi(e){return Array(e).fill(100/e)}function th({groupAssignments:e,setGroupAssignments:s,setFocusedGroup:r,setGroupActiveTabIds:n,setGroupTabOrders:a,groupSizes:i,setGroupSizes:c,isMobile:l,visibleConversations:u,visibleTabKeys:f}){const d=o.useRef(null),x=o.useMemo(()=>Ur(e,f),[e,f]),g=x.assignments,w=o.useMemo(()=>l?1:x.groupCount,[x.groupCount,l]),M=w>1,m=o.useCallback((k,I)=>{s(j=>{const v=new Map(Ur(j,f).assignments);return I===0?v.delete(k):v.set(k,I),v}),n(j=>({...j,[I]:k})),r(I)},[s,f,n,r]),p=o.useCallback(k=>{s(I=>{const j=Ur(I,f).assignments,v=new Map;for(const[y,E]of j)E!==k&&(E>k?v.set(y,E-1):v.set(y,E));return v}),c(I=>{if(I.length<=1)return[];const j=[...I];j.splice(k,1);const v=j.reduce((y,E)=>y+E,0);return v>0?j.map(y=>y/v*100):[]}),r(0)},[s,f,c,r]),b=o.useCallback((k,I)=>{I.preventDefault();const j=d.current;if(!j)return;const v=I.clientX,y=j.offsetWidth,E=i.length===w?[...i]:fi(w),L=_=>{const H=(_.clientX-v)/y*100,C=[...E];C[k]=Math.max(15,E[k]+H),C[k+1]=Math.max(15,E[k+1]-H),c(C)},A=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",A),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",A)},[i,w,c]),h=o.useCallback((k,I,j)=>{if(w>=4)return;const v=j==="left"?I:I+1;s(y=>{const E=Ur(y,f).assignments,L=new Map;for(const A of u){const _=E.get(A.tabKey)??0,B=_>=v?_+1:_;B>0&&L.set(A.tabKey,B)}return v>0&&L.set(k,v),L}),c(y=>{const E=y.length===w?[...y]:fi(w),L=E[I]??100/w,A=Math.max(15,L/2),_=Math.max(15,L/2),B=[...E];B[I]=A,B.splice(v,0,_);const H=B.reduce((C,P)=>C+P,0);return B.map(C=>C/H*100)}),n(y=>{const E=pi(y,v);return E[v]=k,E}),a(y=>{const E=pi(y,v);return E[v]=[k],E}),r(v)},[w,s,f,u,c,n,a,r]);o.useEffect(()=>{Jf(e,g)||s(g)},[e,g,s]),o.useEffect(()=>{const{mapping:k,usedGroups:I}=x;n(j=>{const v=mi(j,k);return ui(j,v)?j:v}),a(j=>{const v=mi(j,k);return ui(j,v)?j:v}),r(j=>{const v=l?0:Zf(j,I,k);return j===v?j:v}),c(j=>{const v=l?[]:eh(j,I,x.groupCount);return Qf(j,v)?j:v})},[x,l,n,a,r,c]);const S=o.useMemo(()=>{const k=Array.from({length:w},()=>[]);for(const I of u){const j=g.get(I.tabKey)??0,v=Math.min(j,w-1);k[v].push(I)}return k},[u,g,w]),R=o.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:d,normalizedGroupAssignments:g,numGroups:w,isSplitMode:M,groupedConvs:S,moveTabToGroup:m,closeGroup:p,handleResizeStart:b,splitTabRelative:h,clearAllSplits:R}}function sh({ides:e,sendDaemonCommand:s}){const r="0.8.93",n=o.useMemo(()=>e.filter(d=>d.type!=="adhdev-daemon"?!1:Jc(d,r)).sort((d,x)=>Number(dr(x,r))-Number(dr(d,r))),[r,e]),a=o.useMemo(()=>n.some(d=>dr(d,r)),[r,n]),[i,c]=o.useState(!1),[l,u]=o.useState({}),f=o.useCallback(async d=>{var x,g;u(w=>({...w,[d]:"upgrading"}));try{const w=await s(d,"daemon_upgrade",{});(x=w==null?void 0:w.result)!=null&&x.upgraded||(g=w==null?void 0:w.result)!=null&&g.success?u(M=>({...M,[d]:"done"})):u(M=>({...M,[d]:"error"}))}catch{u(w=>({...w,[d]:"error"}))}},[s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,appVersion:r,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:l,handleBannerUpgrade:f}}const Ia="adhdev_dashboard_notifications_v2",Aa="adhdev_dashboard_notifications_v1",Ir=80;function rn(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function po(e){return{...e,createdAt:rn(e.createdAt),updatedAt:rn(e.updatedAt,e.createdAt),lastEventAt:rn(e.lastEventAt,e.updatedAt||e.createdAt)}}function rh(e){const s=Wa(e);return s==="unknown:"?e.id:s}function hi(e){return[e.type,nc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function nh(e,s,r,n){var c;const a=Date.now(),i=[];for(const l of e){const u=l.sessionId?s.get(l.sessionId):void 0;if(u!=null&&u.surfaceHidden)continue;const f=hi({type:"task_complete",sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated}),d=!!((c=n==null?void 0:n.get(f))!=null&&c.forceUnread),x=jn(l,s,{notificationStateBySessionId:r}),g=x.inboxBucket==="needs_attention"?"needs_attention":x.inboxBucket==="task_complete"&&x.unread||(u==null?void 0:u.inboxBucket)==="task_complete"&&d?"task_complete":null;if(!g)continue;const w=rn(l.lastMessageAt||(u==null?void 0:u.lastUpdated)||l.lastUpdated,a),M=g==="task_complete"?f:hi({type:g,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,lastMessageHash:l.lastMessageHash,lastMessageAt:l.lastMessageAt,lastUpdated:(u==null?void 0:u.lastUpdated)||l.lastUpdated});i.push(po({id:M,dedupKey:M,type:g,routeId:l.routeId,machineId:l.daemonId||l.routeId,sessionId:l.sessionId,providerSessionId:l.providerSessionId,tabKey:l.tabKey,title:yc(l),preview:bm(l),createdAt:w,updatedAt:w,lastEventAt:w}))}return i.sort((l,u)=>u.updatedAt-l.updatedAt)}function ah(e,s=Ir){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=rh(n),i=r.get(a);if(!i){r.set(a,n);continue}(n.updatedAt>i.updatedAt||n.updatedAt===i.updatedAt&&n.createdAt>i.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const i=a.updatedAt-n.updatedAt;return i!==0?i:a.createdAt-n.createdAt}).slice(0,Math.max(0,s))}function oh(e){return e.filter(s=>typeof s.readAt=="number"||typeof s.deletedAt=="number").map(s=>({id:s.id,...typeof s.readAt=="number"?{readAt:s.readAt}:{},...typeof s.deletedAt=="number"?{deletedAt:s.deletedAt}:{}}))}function ih(e){return new Map(e.map(s=>[s.id,s]))}function ul(e,s,r=Ir){const n=new Map;for(const i of s)n.set(i.id,i);const a=e.map(i=>{const c=po(i),l=n.get(c.id);return{...c,...typeof(l==null?void 0:l.readAt)=="number"?{readAt:l.readAt}:{},...typeof(l==null?void 0:l.deletedAt)=="number"?{deletedAt:l.deletedAt}:{}}});return ah(a,r)}function ch(e,s,r=Ir){const n=new Set(ul(s,[],r).map(a=>a.id));return e.filter(a=>n.has(a.id)).slice(0,Math.max(0,r))}function lh(e,s,r=Date.now()){const n=e.filter(a=>a.id!==s);return n.push({id:s,readAt:r}),n}function dh(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,forceUnread:!0}),r}function uh(e,s,r,n=Date.now()){const a=e.filter(i=>{const c=s.find(l=>l.id===i.id);return!c||!xr(c,r)});for(const i of s)xr(i,r)&&a.push({id:i.id,readAt:n});return a}function mh(e,s){const r=e.filter(n=>n.id!==s);return r.push({id:s,deletedAt:Date.now()}),r}function ph(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function fh(e){const s=new Map;for(const r of e){if(r.deletedAt)continue;const n=rs(r);if(n.length===0)continue;const a=r.readAt?0:1;for(const i of n){const c=s.get(i);if(!c){s.set(i,{unreadCount:a,latestNotificationAt:r.updatedAt,latestRecordId:r.id});continue}s.set(i,{unreadCount:c.unreadCount+a,latestNotificationAt:Math.max(c.latestNotificationAt,r.updatedAt),latestRecordId:c.latestNotificationAt>=r.updatedAt?c.latestRecordId:r.id})}}return s}function hh(){if(typeof window>"u")return[];const e=s=>{if(!s||typeof s!="object")return null;const r=s;if(typeof r.id!="string"||r.id.length===0)return null;const n=typeof r.readAt=="number"&&Number.isFinite(r.readAt)?r.readAt:void 0,a=typeof r.deletedAt=="number"&&Number.isFinite(r.deletedAt)?r.deletedAt:void 0,i=r.forceUnread===!0;return typeof n!="number"&&typeof a!="number"&&!i?null:{id:r.id,...typeof n=="number"?{readAt:n}:{},...typeof a=="number"?{deletedAt:a}:{},...i?{forceUnread:!0}:{}}};try{const s=window.localStorage.getItem(Ia),r=s?JSON.parse(s):[];if(Array.isArray(r))return r.map(e).filter(n=>!!n)}catch{}try{const s=window.localStorage.getItem(Aa),r=s?JSON.parse(s):[];return Array.isArray(r)?oh(r.map(n=>po(n)).filter(n=>!n.deletedAt)):[]}catch{return[]}}function xh(e){if(!(typeof window>"u"))try{const s=e.filter(r=>typeof r.readAt=="number"||typeof r.deletedAt=="number"||r.forceUnread===!0).slice(0,Ir);if(s.length===0){window.localStorage.removeItem(Ia),window.localStorage.removeItem(Aa);return}window.localStorage.setItem(Ia,JSON.stringify(s)),window.localStorage.removeItem(Aa)}catch{}}function bh(e,s){return e===s?!0:e.length!==s.length?!1:e.every((r,n)=>{const a=s[n];return a?r.id===a.id&&r.readAt===a.readAt&&r.deletedAt===a.deletedAt&&r.forceUnread===a.forceUnread:!1})}function gh(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=Ir}=e,[a,i]=o.useState(()=>hh()),c=o.useMemo(()=>ih(a),[a]),l=o.useMemo(()=>nh(s,r,void 0,c),[s,r,c]),u=o.useMemo(()=>ul(l,a,n),[l,a,n]),f=o.useMemo(()=>fh(u),[u]);o.useEffect(()=>{i(m=>{const p=ch(m,l,n);return bh(m,p)?m:p})},[l,n]),o.useEffect(()=>{xh(a)},[a]);const d=o.useMemo(()=>ph(u),[u]),x=o.useCallback((m,p)=>{i(b=>lh(b,m,p))},[]),g=o.useCallback(m=>{i(p=>dh(p,m))},[]),w=o.useCallback((m,p)=>{i(b=>uh(b,u,m,p))},[u]),M=o.useCallback(m=>{i(p=>mh(p,m))},[]);return{notifications:u,unreadCount:d,notificationStateBySessionId:f,markRead:x,markUnread:g,markTargetRead:w,deleteNotification:M}}function ml(){return"select_session"}function yh(){return"open_panel"}function vh({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function wh(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function xi(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function bi(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function fo(e){return e instanceof Error?e.message:String(e||"")}function gi(e){const s=fo(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function yi(e,s){const r=fo(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Sn({sendDaemonCommand:e,activeConv:s,setLocalUserMessages:r,setActionLogs:n,isStandalone:a}){const[i,c]=o.useState(!1),[l,u]=o.useState(!1),[f,d]=o.useState(null),x=o.useRef(!1),g=o.useRef(null);o.useEffect(()=>{d(null)},[s==null?void 0:s.tabKey]);const w=o.useCallback(async b=>{if(!s)return!1;const h=b.trim(),S=Ya(s);if(vh({hasMessage:!!h,blockedMessage:S,sendInFlight:x.current}))return S&&d(S),!1;const R=Date.now(),k={tabKey:s.tabKey,message:h,timestamp:R};if(wh(g.current,k))return d(null),!0;x.current=!0,u(!0),d(null),g.current=k;const I=`${R}-${Math.random().toString(36).slice(2,8)}`,j={role:"user",content:h,timestamp:R,_localId:I},v=!0;r(y=>({...y,[k.tabKey]:[...y[k.tabKey]||[],j]}));try{const y=yr(s);if(!y)return g.current=xi(g.current,k),v&&r(A=>({...A,[k.tabKey]:(A[k.tabKey]||[]).filter(_=>_._localId!==I)})),d("Unable to send message right now."),!1;const E=await e(y,"send_chat",{message:h,...Es(s)}),L=bi(E);if(v&&(L!=null&&L.deduplicated))return r(A=>({...A,[k.tabKey]:(A[k.tabKey]||[]).filter(_=>_._localId!==I)})),d(null),!0;if((L==null?void 0:L.sent)===!1)throw new Error((L==null?void 0:L.error)||"Send failed");if((L==null?void 0:L.success)===!1)throw new Error((L==null?void 0:L.error)||"Send failed");return setTimeout(()=>{const A=Date.now()-6e4;r(_=>{const B=_[k.tabKey];if(!B)return _;const H=B.filter(C=>C.timestamp>A);return H.length===B.length?_:{..._,[k.tabKey]:H}})},6e4),d(null),!0}catch(y){const E=fo(y);return E.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",E):console.warn("Send blocked/failed",y),g.current=xi(g.current,k),r(L=>({...L,[k.tabKey]:(L[k.tabKey]||[]).filter(A=>A._localId!==I)})),d(Hm(y)),!1}finally{x.current=!1,u(!1)}},[s,e,n,r]),M=o.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(b){console.error("Relaunch failed",b)}},[s,e]),m=o.useCallback(async b=>{if(s)try{const S=(s.modalButtons||[]).indexOf(b),R=b.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),k=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(R),I=yr(s);if(!I)return;const j=await e(I,"resolve_action",{button:b,action:k?"approve":"reject",...S>=0&&{buttonIndex:S},...Es(s)}),v=bi(j);v.success||n(y=>[...y,{routeId:s.tabKey,text:yi(b,v==null?void 0:v.error),timestamp:Date.now()}])}catch(h){gi(h)||console.error("[ModalButton] Error:",h),n(S=>[...S,{routeId:s.tabKey,text:gi(h)?yi(b,h):`❌ **${b}** error`,timestamp:Date.now()}])}},[s,e,n]),p=o.useCallback(async()=>{if(!(!s||i)){c(!0);try{await e(s.routeId,yh(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(b){console.error("Focus agent failed",b)}finally{c(!1)}}},[s,i,e]);return{isSendingChat:l,sendFeedbackMessage:f,isFocusingAgent:i,handleSendChat:w,handleRelaunch:M,handleModalButton:m,handleFocusAgent:p}}const ho=o.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:i,handleModalButton:c,handleRelaunch:l,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d=null,handleFocusAgent:x,isFocusingAgent:g,actionLogs:w,userName:M,scrollToBottomRequestNonce:m,isInputActive:p=!0}){const b=rl(s),h=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(ic,{activeConv:h,onModalButton:c}),h.transport!=="pty"&&h.transport!=="acp"&&h.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[t.jsx("span",{className:"text-sm",children:t.jsx(ks,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:l,children:"Relaunch with CDP"})]})}):null,h.transport==="pty"?t.jsxs(t.Fragment,{children:[t.jsx("div",{style:{display:n?"flex":"none",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(hp,{activeConv:h,clearToken:r,terminalRef:i,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,isVisible:n})}),!n&&t.jsx("div",{style:{display:"flex",minHeight:0,flex:"1 1 0%",width:"100%",flexDirection:"column"},children:t.jsx(ja,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:x,isFocusingAgent:g,actionLogs:w,userName:M,scrollToBottomRequestNonce:m,isInputActive:p})})]}):t.jsx(ja,{activeConv:h,ideEntry:a,handleSendChat:u,isSendingChat:f,sendFeedbackMessage:d,handleFocusAgent:x,isFocusingAgent:g,actionLogs:w,userName:M,scrollToBottomRequestNonce:m,isInputActive:p})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive);function jh({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:i,isSendingChat:c,sendFeedbackMessage:l=null,isFocusingAgent:u,onBack:f,onOpenNativeConversation:d,onOpenMachine:x,onOpenHistory:g,onOpenRemote:w,onHideConversation:M,onStopCli:m,cliViewMode:p,onSetCliViewMode:b,handleSendChat:h,handleFocusAgent:S,handleModalButton:R,handleRelaunch:k}){const I=o.useRef(null),j=tt(e)&&!s,v=j&&p==="terminal",y=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 ${y} 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(Da,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:lt(e)}),t.jsx("div",{className:"min-w-0 overflow-hidden text-xs text-text-secondary",children:t.jsx(Nc,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>x(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&p&&t.jsx(Ja,{mode:p,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(At,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:t.jsx($a,{size:14})}),!s&&!j&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:t.jsx(Pt,{size:14})}),M&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>M(e),type:"button",title:"Close chat",children:t.jsx(At,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(ho,{activeConv:e,clearToken:0,isCliTerminal:v,ideEntry:n,terminalRef:I,handleModalButton:R,handleRelaunch:k,handleSendChat:h,isSendingChat:c,sendFeedbackMessage:l,handleFocusAgent:S,isFocusingAgent:u,actionLogs:a,userName:i})})]})}const Xn={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function kh(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function pl(){const[e,s]=o.useState("unix"),[r,n]=o.useState("powershell"),[a,i]=o.useState(!1),c=e==="unix"?"unix":r;o.useEffect(()=>{s(kh())},[]);const l=o.useCallback(()=>{navigator.clipboard.writeText(Xn[c].cmd).catch(()=>{}),i(!0),setTimeout(()=>i(!1),2e3)},[c]);return t.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),t.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>s("windows"),children:"🪟 Windows"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("powershell"),children:"⚡ PowerShell"}),t.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${r==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>n("cmd"),children:">_ CMD"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:l,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:Xn[c].prompt}),t.jsx("span",{className:"flex-1 break-all",children:Xn[c].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function fl({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Pt},{key:"chats",label:"Chats",icon:es}];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 zr({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Ms({children:e,className:s=""}){return t.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${s}`,children:e})}function sr({icon:e,title:s,subtitle:r,children:n}){return t.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[t.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Vr({item:e,type:s,getAvatarText:r,onOpenConversation:n}){const a=s==="needs_attention"||s==="task_complete",i=s==="working",c=s==="earlier",l=s==="task_complete",{isReconnecting:u,isConnecting:f}=qs(e.conversation),d=lt(e.conversation),x=Cs(e.conversation),g=Ec(e.conversation,{requiresAction:s==="needs_attention"}),w=a?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":i?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",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",m=c?"text-text-secondary":"text-text-primary",p=c?"text-text-muted":"text-text-secondary",b=c?"text-text-secondary opacity-80":"text-text-muted",h=c?"text-text-muted opacity-80":"text-text-muted",S="text-[color:var(--status-warning)]";return t.jsxs("button",{className:`group flex items-start gap-3.5 px-4 py-3.5 w-full text-left relative overflow-hidden transition-colors active:scale-[0.995] ${w}`,onClick:()=>n(e.conversation),type:"button",children:[a||i?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${M}`,style:a?{color:"var(--accent-on-primary)"}:void 0,children:r(d)}),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 ${m}`,children:d}),!i&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${h}`,children:oc(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${p}`,children:[x,u?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${S} animate-pulse`,children:"Reconnecting…"})]}):f?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):g==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:S,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${b}`,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 vi({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 Sh({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:i,machineCards:c,getAvatarText:l,onOpenConversation:u,onShowConversation:f,onShowAllHidden:d,onOpenNewSession:x,onOpenMachine:g,onOpenSettings:w,onSectionChange:M,wsStatus:m="connected",isStandalone:p=!1}){const b=m==="disconnected"||m==="reconnecting"||m==="offline"||m==="auth_failed",h=c.length>0,S=s.length>0||r.length>0||n.length>0||a.length>0,R=e==="machines"?"Machines":"Chats",k=p?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",I=p?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]";return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${k}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:R}),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(vn,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:w,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:t.jsx(gn,{size:18})})]})]})}),t.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${I}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:b?t.jsx(sr,{icon:t.jsx(vi,{label:"Reconnecting…"}),title:"Connecting to server",subtitle:m==="offline"?"Your device appears to be offline. Waiting for network…":m==="auth_failed"?"Session expired. Please log in again.":"Establishing connection to the server. This usually takes a moment."}):c.length===0?t.jsx(sr,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:p?"Waiting for your daemon":"Connect your machines",subtitle:p?"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:!p&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(pl,{})})}):t.jsx(Ms,{children:c.map((j,v)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>g(j.id),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:l(j.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:j.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:j.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[j.unread," new"]}):j.total>0?`${j.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:j.subtitle}),j.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j.total," chat",j.total!==1?"s":"",j.unread>0?` · ${j.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},j.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(zr,{title:"Needs attention",className:"mb-0"}),t.jsx(Ms,{children:s.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Vr,{item:j,type:"needs_attention",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(zr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(Ms,{children:r.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Vr,{item:j,type:"task_complete",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(zr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(Ms,{children:n.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Vr,{item:j,type:"working",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(zr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(Ms,{children:a.map((j,v)=>t.jsx("div",{className:v>0?"border-t border-border-subtle/70":"",children:t.jsx(Vr,{item:j,type:"earlier",getAvatarText:l,onOpenConversation:u})},j.conversation.tabKey))}):S?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):b?t.jsx(sr,{icon:t.jsx(vi,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):h?t.jsx(sr,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(es,{size:20})}),title:"No conversations yet",subtitle:"Your machines are available. Open a machine, wait for P2P to connect, then launch your first IDE, CLI, or ACP session."}):t.jsx(sr,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&i.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsxs("div",{className:"mx-1 mt-4 mb-1 flex items-center justify-between gap-2 px-1 py-1 text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:[t.jsx("span",{children:"Hidden"}),t.jsx("button",{type:"button",className:"text-accent-primary normal-case font-semibold hover:underline",onClick:d,children:"Restore all"})]}),t.jsx(Ms,{className:"bg-bg-secondary/25",children:i.map((j,v)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] opacity-50 saturate-0 ${v>0?"border-t border-border-subtle/70":""}`,onClick:()=>f(j),type:"button",children:[t.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-bg-primary border border-border-subtle text-text-secondary",children:l(lt(j))}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:lt(j)}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:"Hidden"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate flex items-center",children:Cs(j)}),t.jsx("div",{className:"text-[13px] text-text-muted truncate mt-0.5 opacity-90",children:"Tap to restore and open"})]})]},j.tabKey))})]})]}),e==="chats"&&x&&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:x,"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(fl,{section:e,onSectionChange:M})]})}function Nh(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 hl(e){const s=[e.workspace||"Workspace unknown"],r=Ss(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=Nh(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Nn(...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 Ch(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 Cn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=Ch(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 Ih(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 Ah(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function In(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=Ah(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=(f,d)=>/^[A-Za-z]:\\?$/.test(f)?`${f.replace(/\\?$/,"\\")}${d}`:f==="/"||f==="\\"?`${c}${d}`:`${f.replace(/[\\/]+$/,"")}${c}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(f=>(f==null?void 0:f.type)==="directory"&&typeof(f==null?void 0:f.name)=="string").map(f=>({name:f.name,path:typeof(f==null?void 0:f.path)=="string"&&f.path.trim()?f.path:l(i,f.name)})).sort((f,d)=>f.name.localeCompare(d.name)):[];return{path:i,directories:u}}function An({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:i="",confirmLabel:c="Use this folder",onClose:l,onNavigate:u,onConfirm:f}){const[d,x]=o.useState(r);o.useEffect(()=>{x(r)},[r]);const g=Ih(r),w=d.trim();return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:l,"aria-label":"Close folder browser",children:t.jsx(At,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||a||u(g)},disabled:!g||a,children:[t.jsx(Da,{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:d,onChange:M=>x(M.target.value),onKeyDown:M=>{M.key!=="Enter"||!w||a||(M.preventDefault(),u(w))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!w||a||u(w)},disabled:!w||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):i?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:i}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(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:()=>u(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(Bs,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children: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:()=>f(w||r),disabled:!w&&!r||a,children:c})]})]})})}function xo({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:i,confirmLabel:c="Launch",busyLabel:l="Launching…",busy:u=!1,showArgsInput:f,argsValue:d,onArgsChange:x,showModelInput:g,modelValue:w,onModelChange:M,historyProviderNode:m,onConfirm:p,onCancel:b}){const h=n==null?void 0:n.find(S=>S.key===a);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:b,"aria-label":"Close launch confirmation",children:t.jsx(At,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&i&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:a||"",onChange:S=>i(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:n.map(S=>t.jsx("option",{value:S.key,children:S.label},S.key))}),(h==null?void 0:h.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),m,r.map(S=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:S.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:S.value})]},`${S.label}:${S.value}`)),g&&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:w||"",onChange:S=>M(S.target.value),placeholder:"Auto-detect or default",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),f&&x&&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:d||"",onChange:S=>x(S.target.value),placeholder:"e.g. --experimental",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:b,disabled:u,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:p,disabled:u,children:[t.jsx(Ka,{size:14}),u?l:c]})]})]})})}function wi(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function vs(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,i=[];a&&i.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of s.workspaces||[])i.push({key:`saved:${u.id}`,label:`${u.id===s.defaultWorkspaceId?"⭐ ":""}${wi(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const c=(r==null?void 0:r.trim())||"",l=c?(s.workspaces||[]).find(u=>u.path===c):null;if(c&&!l&&i.push({key:`custom:${c}`,label:wi(c),description:c,workspaceId:null,workspacePath:c}),n){const u=`saved:${n}`;if(i.some(f=>f.key===u))return{options:i,selectedKey:u}}return l?{options:i,selectedKey:`saved:${l.id}`}:c?{options:i,selectedKey:`custom:${c}`}:{options:i,selectedKey:"__home__"}}function Mh(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Th(e){return[Mh(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Lh(e){return e.lastLaunchedAt?wn(e.lastLaunchedAt):""}function xl(e){return{metaText:Th(e),updatedLabel:Lh(e)}}function Jn(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function Rh({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:i}){var Ve,pt,bt,ct;const c=Nr(),[l,u]=o.useState(!1),f=(((Ve=e.detectedIdes)==null?void 0:Ve.length)||0)>0,d=o.useMemo(()=>(e.workspaces||[]).map(Me=>({id:Me.id,path:Me.path,label:Me.label})),[e]),x=e.defaultWorkspaceId||null,[g,w]=o.useState(x||((pt=d[0])==null?void 0:pt.id)||""),[M,m]=o.useState(""),[p,b]=o.useState(""),[h,S]=o.useState([]),[R,k]=o.useState(!1),[I,j]=o.useState(""),[v,y]=o.useState(!1),[E,L]=o.useState(Jn(f,s.length,r.length)),A=o.useRef(null),[_,B]=o.useState(null),H=o.useRef("__home__"),[C,P]=o.useState("__home__"),[U,N]=o.useState(""),[$,z]=o.useState(""),[q,W]=o.useState(""),[ne,ae]=o.useState([]),[ke,X]=o.useState(()=>wt().textQuery),[pe,Y]=o.useState(()=>wt().workspaceQuery),[J,ue]=o.useState(()=>wt().modelQuery),[le,V]=o.useState(()=>wt().resumableOnly),[ve,ie]=o.useState(()=>wt().sortMode),[ce,te]=o.useState(!1),[me,re]=o.useState(!1),je=o.useRef(null),we=o.useRef(null);o.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&c(e.id,{minFreshMs:3e4}).catch(()=>{})},[c,e]);const Te=g==="__custom__"?M.trim():((bt=d.find(Me=>Me.id===g))==null?void 0:bt.path)||"",T=g==="__custom__"&&!!Te&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),fe=g!=="__custom__"&&((ct=d.find(Me=>Me.id===g))==null?void 0:ct.path)||"",be=o.useMemo(()=>(e.recentLaunches||[]).map(Me=>Me.workspace),[e]),Q=o.useCallback(async Me=>{k(!0),j("");try{const Je=await a(Me);b(Je.path),m(Je.path),S(Je.directories)}catch(Je){j(Je instanceof Error?Je.message:"Could not load folder")}finally{k(!1)}},[a]),Se=o.useCallback(()=>{var Je;w("__custom__"),y(!0);const Me=Cn(e.platform,Nn(M.trim(),fe,be,e.defaultWorkspacePath,(Je=d.find(Ye=>Ye.id===x))==null?void 0:Je.path,d.map(Ye=>Ye.path)));Q(Me)},[M,x,Q,be,fe,e.platform,d]),De=o.useCallback(Me=>{if(Me!=null&&Me.workspaceId){w(Me.workspaceId),m("");return}if(Me!=null&&Me.workspacePath){w("__custom__"),m(Me.workspacePath);return}w(""),m("")},[]),Oe=o.useCallback(Me=>{if(w(Me),Me==="__custom__"){Se();return}m("")},[Se]),$e=o.useCallback(Me=>{w("__custom__"),m(Me)},[]),Ue=o.useCallback((Me,Je)=>{A.current=Je,H.current=Me.selectedWorkspaceKey||"__home__",P(Me.selectedWorkspaceKey||"__home__"),N(Me.initialArgs||""),z(Me.initialModel||""),W(""),ae([]);const Ye=Me.providerType?`${e.id}:${Me.providerType}`:null;if(yp(we.current,Ye)){const Fe=wt();X(Fe.textQuery),Y(Fe.workspaceQuery),ue(Fe.modelQuery),V(Fe.resumableOnly),ie(Fe.sortMode)}we.current=Ye,B(Me),Me.providerType&&i&&(te(!0),i(Me.providerType).then(Fe=>ae(Fe||[])).catch(Fe=>console.warn("Failed to load saved sessions",Fe)).finally(()=>te(!1)))},[i,e.id]),ze=o.useMemo(()=>Bc(ne,{textQuery:ke,workspaceQuery:pe,modelQuery:J,resumableOnly:le,sortMode:ve}),[J,le,ne,ve,ke,pe]);o.useEffect(()=>{q&&(ze.some(Me=>Me.providerSessionId===q)||W(""))},[ze,q]);const mt=o.useCallback(()=>{A.current&&(re(!0),A.current().finally(()=>{A.current=null,re(!1),B(null)}))},[]),it=o.useCallback(()=>{A.current=null,B(null)},[]),xt=o.useCallback(Me=>{H.current=Me,P(Me)},[]);return o.useEffect(()=>{var Me;je.current!==e.id&&(je.current=e.id,w(x||((Me=d[0])==null?void 0:Me.id)||"__custom__"),m(""),b(""),S([]),j(""),y(!1),X(wt().textQuery),Y(wt().workspaceQuery),ue(wt().modelQuery),V(wt().resumableOnly),ie(wt().sortMode),we.current=null,L(Jn(f,s.length,r.length)))},[r.length,s.length,x,f,e.id,d]),o.useEffect(()=>{var Me;g!=="__custom__"&&(g&&d.some(Je=>Je.id===g)||w(x||((Me=d[0])==null?void 0:Me.id)||"__custom__"))},[x,g,d]),o.useEffect(()=>{E==="ide"&&f||E==="cli"&&s.length>0||E==="acp"&&r.length>0||L(Jn(f,s.length,r.length))},[E,r.length,s.length,f]),{showAllRecent:l,setShowAllRecent:u,hasIdeOptions:f,workspaceRows:d,defaultWorkspaceId:x,workspaceChoice:g,customWorkspacePath:M,browseCurrentPath:p,browseDirectories:h,browseBusy:R,browseError:I,browseDialogOpen:v,activeLauncherKind:E,launchConfirm:_,launchConfirmWorkspaceKeyRef:H,launchConfirmWorkspaceKey:C,launchConfirmArgs:U,launchConfirmModel:$,launchConfirmResumeId:q,launchConfirmSavedSessions:ne,launchConfirmTextFilter:ke,launchConfirmWorkspaceFilter:pe,launchConfirmModelFilter:J,launchConfirmResumableOnly:le,launchConfirmSortMode:ve,filteredLaunchConfirmSavedSessions:ze,launchConfirmSessionsLoading:ce,launchConfirmBusy:me,resolvedWorkspacePath:Te,canCreateMissingWorkspace:T,openBrowseDialog:Se,loadBrowsePath:Q,handleWorkspaceChoiceChange:Oe,chooseCustomWorkspacePath:$e,setCustomWorkspacePath:m,setBrowseDialogOpen:y,setActiveLauncherKind:L,openLaunchConfirm:Ue,handleConfirmLaunch:mt,closeLaunchConfirm:it,setWorkspaceSelectionFromOption:De,setLaunchConfirmWorkspaceKeyAndSync:xt,setLaunchConfirmArgs:N,setLaunchConfirmModel:z,setLaunchConfirmResumeId:W,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:Y,setLaunchConfirmModelFilter:ue,setLaunchConfirmResumableOnly:V,setLaunchConfirmSortMode:ie}}function _h({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:i,appVersion:c,machineAction:l,isStandalone:u,section:f,showBottomNav:d,onBack:x,onSectionChange:g,onOpenConversation:w,onOpenRecent:M,onOpenMachineDetails:m,onMachineUpgrade:p,onLaunchDetectedIde:b,onAddWorkspace:h,onBrowseDirectory:S,onLaunchWorkspaceProvider:R,onListSavedSessions:k}){const I=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",j=r.slice(0,4),v=s.slice(0,3),y=Rh({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:l,onBrowseDirectory:S,onListSavedSessions:k}),E=o.useMemo(()=>j.map(C=>{const{metaText:P,updatedLabel:U}=xl(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:P,updatedLabel:U,onClick:()=>{const{options:N,selectedKey:$}=vs({machine:{workspaces:y.workspaceRows,defaultWorkspaceId:y.defaultWorkspaceId},currentWorkspacePath:C.workspace});y.openLaunchConfirm({title:C.kind==="ide"?xs("restart-ide",C.label):C.providerSessionId?eo(C.label):xs("start-fresh",C.label),description:C.kind==="ide"?bs("restart-ide"):C.providerSessionId?to():bs("start-fresh"),confirmLabel:C.kind==="ide"?Us("restart-ide"):C.providerSessionId?pn(!0):Us("start-fresh"),busyLabel:C.kind==="ide"?zs("restart-ide"):C.providerSessionId?Qa(!0):zs("start-fresh"),workspaceOptions:N,selectedWorkspaceKey:$,details:[{label:"Mode",value:I(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const z=N.find(q=>q.key===y.launchConfirmWorkspaceKeyRef.current);y.setWorkspaceSelectionFromOption(z),await M({...C,workspace:(z==null?void 0:z.workspacePath)??null})})}}}),[y,M,j]),L=o.useMemo(()=>v.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:lt(C.conversation),secondary:up(C.conversation,{timestampLabel:C.timestamp?oc(C.timestamp):null}),unread:C.unread,onClick:()=>w(C.conversation)})),[w,v]),A=y.showAllRecent?E:E.slice(0,4),_=E.length>0,B=L.length>0,H=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${H} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:x,type:"button","aria-label":"Back",children:t.jsx(Da,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:_t(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[B&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.map(C=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),_&&t.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:A.map(C=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:C.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:C.primary}),C.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),E.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>y.setShowAllRecent(C=>!C),children:y.showAllRecent?"Show fewer":`Show ${E.length-4} more`})})]}),(y.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:y.workspaceChoice,onChange:C=>y.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:y.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[y.workspaceRows.map(C=>t.jsxs("option",{value:C.id,children:[C.id===y.defaultWorkspaceId?"⭐ ":"",kn(C.path,C.label)||C.path]},C.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),y.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Bs,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:y.resolvedWorkspacePath||y.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:y.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:()=>{y.resolvedWorkspacePath&&h(y.resolvedWorkspacePath)},disabled:!y.resolvedWorkspacePath||y.browseBusy,children:"Save as workspace"})]})]}),y.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:y.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[y.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${y.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:()=>y.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${y.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:()=>y.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${y.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:()=>y.setActiveLauncherKind("acp"),children:"ACP"})]}),y.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:y.activeLauncherKind==="ide"?"Choose an IDE":y.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:y.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const{options:P,selectedKey:U}=vs({machine:{workspaces:y.workspaceRows,defaultWorkspaceId:y.defaultWorkspaceId},currentWorkspaceId:y.workspaceChoice!=="__custom__"?y.workspaceChoice:null,currentWorkspacePath:y.resolvedWorkspacePath});y.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:P,selectedWorkspaceKey:U,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const N=P.find($=>$.key===y.launchConfirmWorkspaceKeyRef.current);y.setWorkspaceSelectionFromOption(N),b(C.type,{workspacePath:(N==null?void 0:N.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:y.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(y.activeLauncherKind==="cli"?n:a).map(C=>t.jsxs("button",{type:"button",className:"flex flex-col items-start gap-1 w-full text-left p-3 rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",onClick:()=>{const P=y.activeLauncherKind==="cli"?"cli":"acp",{options:U,selectedKey:N}=vs({machine:{workspaces:y.workspaceRows,defaultWorkspaceId:y.defaultWorkspaceId},currentWorkspaceId:y.workspaceChoice!=="__custom__"?y.workspaceChoice:null,currentWorkspacePath:y.resolvedWorkspacePath});y.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${P.toUpperCase()}`,workspaceOptions:U,selectedWorkspaceKey:N,details:[{label:"Mode",value:P.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:P==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const $=U.find(z=>z.key===y.launchConfirmWorkspaceKeyRef.current);y.setWorkspaceSelectionFromOption($),R(P,C.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:y.launchConfirmArgs,model:y.launchConfirmModel,resumeSessionId:y.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:y.resolvedWorkspacePath||"Use selected workspace"})]},C.type))})]}),l.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${l.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[l.message,y.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(y.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:p,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:m,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"})]})]})]})]}),y.browseDialogOpen&&t.jsx(An,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:y.browseCurrentPath,directories:y.browseDirectories,busy:y.browseBusy,error:y.browseError,confirmLabel:"Use this folder",onClose:()=>y.setBrowseDialogOpen(!1),onNavigate:C=>{y.loadBrowsePath(C)},onConfirm:C=>{y.chooseCustomWorkspacePath(C),y.setBrowseDialogOpen(!1)}}),y.launchConfirm&&t.jsx(xo,{title:y.launchConfirm.title,description:y.launchConfirm.description,details:y.launchConfirm.details,workspaceOptions:y.launchConfirm.workspaceOptions,selectedWorkspaceKey:y.launchConfirmWorkspaceKey,onWorkspaceChange:y.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:y.launchConfirm.providerType?pn(!!y.launchConfirmResumeId):y.launchConfirm.confirmLabel,busyLabel:y.launchConfirm.providerType?void 0:y.launchConfirm.busyLabel,busy:y.launchConfirmBusy,showArgsInput:y.launchConfirm.showArgsInput,argsValue:y.launchConfirmArgs,onArgsChange:y.setLaunchConfirmArgs,showModelInput:y.launchConfirm.showModelInput,modelValue:y.launchConfirmModel,onModelChange:y.setLaunchConfirmModel,historyProviderNode:y.launchConfirm.providerType&&(y.launchConfirmSessionsLoading||y.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"}),y.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:Za()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:y.launchConfirmTextFilter,onChange:C=>y.setLaunchConfirmTextFilter(C.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:y.launchConfirmWorkspaceFilter,onChange:C=>y.setLaunchConfirmWorkspaceFilter(C.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:y.launchConfirmModelFilter,onChange:C=>y.setLaunchConfirmModelFilter(C.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),t.jsxs("select",{value:y.launchConfirmSortMode,onChange:C=>y.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.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:y.launchConfirmResumableOnly,onChange:C=>y.setLaunchConfirmResumableOnly(C.target.checked),disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:y.launchConfirmResumeId,onChange:C=>y.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:y.launchConfirmBusy||y.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:jp()}),y.filteredLaunchConfirmSavedSessions.map(C=>t.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]}),!y.launchConfirmSessionsLoading&&y.launchConfirmSavedSessions.length>0&&y.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),y.launchConfirmResumeId&&(()=>{const C=y.filteredLaunchConfirmSavedSessions.find(U=>U.providerSessionId===y.launchConfirmResumeId);if(!C)return null;const P=hl(C);return t.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:P.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:P.providerSessionId}),t.jsx("div",{className:"mt-1",children:P.metaLine}),P.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:P.updatedLabel}),P.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:P.preview})]})})()]}),onConfirm:y.handleConfirmLaunch,onCancel:y.closeLaunchConfirm}),d&&t.jsx(fl,{section:f,onSectionChange:g})]})}function bl(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 Ph(e,s){if(!e)return[];const r=e.recentLaunches||[];return r.length>0?r.map(n=>({id:n.id,label:n.title||n.providerName||n.providerType,kind:n.kind,providerType:n.providerType,providerSessionId:n.providerSessionId,subtitle:Ss(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var c,l,u,f,d;const a=br(n)?"cli":Ps(n)?"acp":"ide",i=Ss(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((c=n.activeChat)==null?void 0:c.title)||(br(n)?n.cliName||n.type:Ps(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Ps(n)?i||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:((d=(f=(u=(l=n.activeChat)==null?void 0:l.messages)==null?void 0:u.at)==null?void 0:f.call(u,-1))==null?void 0:d.timestamp)||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Dh(e,s){const r=new Map;for(const n of s){const a=is(n.conversation),i=r.get(a);i?i.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],i=[...a].sort((x,g)=>g.timestamp-x.timestamp)[0]||null,c=(i==null?void 0:i.conversation)||null,l=ba(n),u=a.filter(x=>x.unread||x.requiresAction).length,f=bl(n),d=[n.platform||"machine",f].filter(Boolean);return{id:n.id,label:_t(n,{fallbackId:n.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:c,latestTimestamp:(i==null?void 0:i.timestamp)||0,fallbackActivityAt:l,preview:c?mp(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 Eh({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:i,liveSessionInboxState:c,sendDaemonCommand:l,requestedActiveTabKey:u,onRequestedActiveTabConsumed:f,requestedMachineId:d,onRequestedMachineConsumed:x,requestedMobileSection:g,onRequestedMobileSectionConsumed:w,setSelectedTabKey:M,setScreen:m,setSelectedMachineId:p,setSection:b,setMachineBackTarget:h,resetMachineAction:S,markNotificationTargetRead:R}){const k=o.useRef(null),I=o.useCallback(j=>{if(!(j!=null&&j.sessionId))return;const v=dn(j,c),y=Math.max(Date.now(),ps(j),v.lastUpdated||0);Gr("mark_read:start",{tabKey:j.tabKey,sessionId:j.sessionId,displayPrimary:lt(j),inboxBucket:v.inboxBucket,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:ps(j),readAt:y}),R({sessionId:j.sessionId,providerSessionId:j.providerSessionId,tabKey:j.tabKey,routeId:j.routeId},y),l(is(j)||j.routeId,"mark_session_seen",{sessionId:j.sessionId,seenAt:y}).then(E=>{Gr("mark_read:result",{tabKey:j.tabKey,sessionId:j.sessionId,result:E})}).catch(E=>{Gr("mark_read:error",{tabKey:j.tabKey,sessionId:j.sessionId,error:E instanceof Error?E.message:String(E)})})},[c,l]);return o.useEffect(()=>{var v;if(!n){m("inbox"),M(((v=e[0])==null?void 0:v.tabKey)||null),k.current=null;return}if(i!=="chat"){k.current=null;return}const j=`${n.tabKey}:${n.sessionId||""}`;k.current!==j&&(k.current=j,I(n))},[e,I,i,n,m,M]),o.useEffect(()=>{if(!u)return;const j=e.find(v=>v.tabKey===u);j&&(M(j.tabKey),m("chat"),f==null||f())},[e,f,u,m,M]),o.useEffect(()=>{if(!d)return;const j=s.find(v=>v.id===d);j&&(p(j.id),S(),b("machines"),h("inbox"),m("machine"),x==null||x())},[s,x,d,S,h,m,b,p]),o.useEffect(()=>{g&&(b(g),m("inbox"),w==null||w())},[w,g,m,b]),o.useEffect(()=>{const j=r.filter(v=>v.inboxBucket==="task_complete"||v.unread);j.length!==0&&Gr("inbox_state",{screen:i,selectedTabKey:a,items:j.map(v=>{const y=dn(v.conversation,c);return{liveState:y,tabKey:v.conversation.tabKey,sessionId:v.conversation.sessionId,displayPrimary:lt(v.conversation),serverBucket:y.inboxBucket,computedBucket:v.inboxBucket,serverUnread:y.unread,computedUnread:v.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,activityAt:ps(v.conversation)}})})},[r,c,i,a]),{markConversationRead:I}}function $h(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function ji(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Kh(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Bh({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,i]=o.useState("idle"),[c,l]=o.useState(""),[u,f]=o.useState(null),d=o.useCallback(()=>{i("idle"),l(""),f(null)},[]),x=o.useCallback(async(h,S,R)=>{var k;try{i("loading"),l(`Launching ${S}…`);const I={ideType:S,enableCdp:!0};(k=R==null?void 0:R.workspacePath)!=null&&k.trim()&&(I.workspace=R.workspacePath.trim()),await e(h,"launch_ide",I),i("done"),l(`${S} launch requested`)}catch(I){i("error"),l(I instanceof Error?I.message:"Launch IDE failed"),console.error("Launch IDE failed",I)}},[e]),g=o.useCallback(async(h,S,R)=>{if(S.trim())try{i("loading"),l(R!=null&&R.createIfMissing?"Creating folder…":"Saving workspace…");const k=await e(h,"workspace_add",{path:S.trim(),createIfMissing:(R==null?void 0:R.createIfMissing)===!0});if(k!=null&&k.success){i("done"),l(R!=null&&R.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),l((k==null?void 0:k.error)||"Could not save workspace")}catch(k){i("error"),l(k instanceof Error?k.message:"Could not save workspace")}},[e]),w=o.useCallback(async h=>{var S,R,k,I,j,v;try{i("loading"),l("Starting daemon upgrade…");const y=await e(h,"daemon_upgrade",{});if((S=y==null?void 0:y.result)!=null&&S.alreadyLatest){i("done"),l(`Already on v${((R=y==null?void 0:y.result)==null?void 0:R.version)||"latest"}.`);return}if((k=y==null?void 0:y.result)!=null&&k.upgraded||(I=y==null?void 0:y.result)!=null&&I.success){i("done"),l(`Upgrade to v${((j=y==null?void 0:y.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),l(((v=y==null?void 0:y.result)==null?void 0:v.error)||"Upgrade failed")}catch(y){i("error"),l(y instanceof Error?y.message:"Upgrade failed")}},[e]),M=o.useCallback(async(h,S,R,k)=>{var v,y,E;const I=Date.now(),j={machineId:h,kind:S,providerType:R,workspaceId:(k==null?void 0:k.workspaceId)||null,workspacePath:(k==null?void 0:k.workspacePath)||null,resumeSessionId:(k==null?void 0:k.resumeSessionId)||null,startedAt:I};try{i("loading"),l(`Launching ${R}…`),f(j);const L={cliType:R};(v=k==null?void 0:k.workspacePath)!=null&&v.trim()?L.dir=k.workspacePath.trim():k!=null&&k.workspaceId&&(L.workspaceId=k.workspaceId),k!=null&&k.resumeSessionId&&(L.resumeSessionId=k.resumeSessionId),(y=k==null?void 0:k.args)!=null&&y.trim()&&(L.cliArgs=k.args.trim().split(/\s+/).filter(Boolean)),(E=k==null?void 0:k.model)!=null&&E.trim()&&(L.initialModel=k.model.trim());const A=await e(h,"launch_cli",L),_=(A==null?void 0:A.result)||A,B=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(A!=null&&A.success&&B){f(null),i("done"),l(`${R} launched`),s(as(B));return}if(A!=null&&A.success){i("loading"),l(`${R} launch requested — waiting for session…`);return}f(null),i("error"),l((A==null?void 0:A.error)||(_==null?void 0:_.error)||`Could not launch ${S.toUpperCase()} workspace`)}catch(L){if(Kh(L)){i("loading"),l(`${R} launch requested — waiting for session…`);return}f(null),i("error"),l(L instanceof Error?L.message:`Could not launch ${S.toUpperCase()} workspace`)}},[s,e]),m=o.useCallback(async(h,S)=>{try{const R=await e(h,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),k=(R==null?void 0:R.result)??R;return Array.isArray(k==null?void 0:k.sessions)?k.sessions:[]}catch(R){return console.error("Failed to list saved sessions on mobile:",R),[]}},[e]),p=o.useCallback(async(h,S)=>In(e,h,S),[e]);o.useEffect(()=>{if(!u)return;const h=ji(u.workspacePath),S=r.find(k=>{var L,A,_,B;if(!k||k.type==="adhdev-daemon"||$h(k.daemonId||k.id)!==u.machineId||(k.transport==="acp"?"acp":k.transport==="pty"?"cli":null)!==u.kind||String(k.agentType||k.type||"")!==u.providerType)return!1;const y=String(k.providerSessionId||"");if(u.resumeSessionId&&y)return y===u.resumeSessionId;if(h){const H=ji(k.workspace||k.runtimeWorkspaceLabel);return H?H===h:!1}return Number(k.lastUpdated||k._lastUpdate||k.timestamp||((B=(_=(A=(L=k.activeChat)==null?void 0:L.messages)==null?void 0:A.at)==null?void 0:_.call(A,-1))==null?void 0:B.timestamp)||0)>=u.startedAt-5e3});if(!S)return;const R=Sc({entrySessionId:S.sessionId,entryInstanceId:S.instanceId,entryRouteId:S.id,conversations:n});R&&(f(null),i("done"),l(`${u.providerType} launched`),s(as(R)))},[n,r,s,u]),o.useEffect(()=>{if(!u)return;const h=window.setTimeout(()=>{f(S=>!S||S.startedAt!==u.startedAt?S:(i("error"),l("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[u]);const b=o.useCallback(async(h,S)=>{if(S.kind==="ide"&&S.providerType){await x(h,S.providerType,{workspacePath:S.workspace||null});return}(S.kind==="cli"||S.kind==="acp")&&S.providerType&&await M(h,S.kind,S.providerType,{workspacePath:S.workspace||null,resumeSessionId:S.providerSessionId||null})},[x,M]);return{machineAction:{state:a,message:c},resetMachineAction:d,handleLaunchDetectedIde:x,handleAddWorkspace:g,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:M,handleListSavedSessions:m,handleBrowseDirectory:p,handleOpenRecent:b}}function Oh({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:i,setScreen:c,setSelectedMachineId:l,setSection:u,setMachineBackTarget:f}){const d=o.useCallback(b=>{i(b.tabKey),c("chat"),n(b)},[n,c,i]),x=o.useCallback(b=>{const h=e.find(S=>S.routeId===b.routeId&&S.streamSource==="native");h&&(i(h.tabKey),c("chat"),n(h))},[e,n,c,i]),g=o.useCallback(()=>{n(s),c("inbox")},[n,s,c]),w=o.useCallback((b,h="inbox")=>{l(b),a(),u("machines"),f(h),c("machine")},[a,f,c,u,l]),M=o.useCallback(b=>{const h=is(b);h&&w(h,"chat")},[w]),m=o.useCallback(()=>{a(),c(r)},[r,a,c]),p=o.useCallback(b=>{u(b),c("inbox")},[c,u]);return{openConversation:d,openNativeConversation:x,backFromConversation:g,openMachine:w,openConversationMachine:M,backFromMachine:m,changeMachineSection:p}}function Wh(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function qr(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Hh({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,userName:u,requestedActiveTabKey:f,onRequestedActiveTabConsumed:d,requestedMachineId:x,onRequestedMachineConsumed:g,requestedMobileSection:w,onRequestedMobileSectionConsumed:M,onOpenHistory:m,onOpenRemote:p,onStopCli:b,wsStatus:h,isConnected:S,onShowHiddenConversation:R,onShowAllHiddenConversations:k,onHideConversation:I,onOpenNewSession:j,notificationStateBySessionId:v,liveSessionInboxState:y,onMarkNotificationTargetRead:E}){const[L,A]=o.useState(()=>{var Q;return((Q=e[0])==null?void 0:Q.tabKey)||null}),[_,B]=o.useState(()=>e[0]?"chat":"inbox"),[H,C]=o.useState("chats"),[P,U]=o.useState(null),[N,$]=o.useState("inbox"),z=Vs(),q="0.8.93",W=o.useMemo(()=>e.find(Q=>Q.tabKey===L)||e[0]||null,[e,L]),ne=o.useMemo(()=>W?r.find(Q=>Q.id===W.routeId):void 0,[r,W]),ae=o.useMemo(()=>!W||Qe(W)||!tt(W)?null:Hs(W),[W]),ke=o.useMemo(()=>r.filter(Q=>Q.type==="adhdev-daemon").sort(Fa),[r]),X=o.useMemo(()=>ke.find(Q=>Q.id===P)||null,[ke,P]),pe=Sn({sendDaemonCommand:a,activeConv:W||void 0,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),Y=Bh({sendDaemonCommand:a,navigate:z,ides:r,conversations:e}),J=o.useMemo(()=>e.map(Q=>{const Se=_==="chat"&&(W==null?void 0:W.tabKey)===Q.tabKey,De=jn(Q,y,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Se,notificationStateBySessionId:v}),Oe=ps(Q),$e=Dc(Q);return{conversation:Q,timestamp:Oe,preview:$e,unread:De.unread,requiresAction:De.requiresAction,isWorking:De.isWorking,inboxBucket:De.inboxBucket}}),[e,y,v,_,W]),{markConversationRead:ue}=Eh({conversations:e,machineEntries:ke,items:J,selectedConversation:W,selectedTabKey:L,screen:_,liveSessionInboxState:y,sendDaemonCommand:a,requestedActiveTabKey:f,onRequestedActiveTabConsumed:d,requestedMachineId:x,onRequestedMachineConsumed:g,requestedMobileSection:w,onRequestedMobileSectionConsumed:M,setSelectedTabKey:A,setScreen:B,setSelectedMachineId:U,setSection:C,setMachineBackTarget:$,resetMachineAction:Y.resetMachineAction,markNotificationTargetRead:E}),le=Oh({conversations:e,selectedConversation:W,machineBackTarget:N,markConversationRead:ue,resetMachineAction:Y.resetMachineAction,setSelectedTabKey:A,setScreen:B,setSelectedMachineId:U,setSection:C,setMachineBackTarget:$}),V=o.useMemo(()=>qr(J.filter(Q=>Q.requiresAction)),[J]),ve=o.useMemo(()=>qr(J.filter(Q=>Q.unread&&!Q.requiresAction)),[J]),ie=o.useMemo(()=>qr(J.filter(Q=>!Q.unread&&!Q.requiresAction&&Q.isWorking)),[J]),ce=o.useMemo(()=>qr(J.filter(Q=>!Q.unread&&!Q.requiresAction&&!Q.isWorking)),[J]),te=o.useMemo(()=>X?J.filter(Q=>is(Q.conversation)===X.id):[],[J,X]),me=o.useMemo(()=>Ph(X,r),[r,X]),re=(X==null?void 0:X.version)||null,je=!!X&&!!re&&!0&&re!==q,we=o.useMemo(()=>(X==null?void 0:X.availableProviders)||[],[X]),Te=o.useMemo(()=>we.filter(Q=>Q.category==="cli"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[we]),T=o.useMemo(()=>we.filter(Q=>Q.category==="acp"&&Q.installed!==!1).map(Q=>({type:Q.type,displayName:Q.displayName||Q.type,icon:Q.icon})),[we]),fe=o.useMemo(()=>Dh(ke,J),[J,ke]),be=o.useCallback(async Q=>{X&&await Y.handleOpenRecent(X.id,Q)},[Y,X]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:_==="chat"&&W?t.jsx(jh,{selectedConversation:W,isAcp:Qe(W),isStandalone:l,selectedIdeEntry:ne,actionLogs:n,userName:u,isSendingChat:pe.isSendingChat,sendFeedbackMessage:pe.sendFeedbackMessage,isFocusingAgent:pe.isFocusingAgent,handleModalButton:pe.handleModalButton,handleRelaunch:pe.handleRelaunch,onBack:le.backFromConversation,onOpenNativeConversation:le.openNativeConversation,onOpenMachine:le.openConversationMachine,onHideConversation:I,onOpenHistory:m,onOpenRemote:p,onStopCli:b,cliViewMode:ae,onSetCliViewMode:async Q=>{if(W&&ae!==Q)try{await a(is(W)||W.routeId,"set_cli_view_mode",{targetSessionId:W.sessionId,cliType:Ot(W),mode:Q})}catch(Se){const De=uo(Se);lo(Se)?console.warn(De?"CLI view mode result was lost after send; keeping optimistic mobile mode override:":"Skipped CLI view mode switch:",Se instanceof Error?Se.message:String(Se)):console.error("Failed to switch CLI view mode:",Se)}},handleSendChat:pe.handleSendChat,handleFocusAgent:pe.handleFocusAgent}):_==="machine"&&X?t.jsx(_h,{selectedMachineEntry:X,selectedMachineConversations:te,selectedMachineRecentLaunches:me,cliProviders:Te,acpProviders:T,selectedMachineNeedsUpgrade:je,appVersion:q,machineAction:Y.machineAction,isStandalone:l,section:H,showBottomNav:N==="inbox",onBack:le.backFromMachine,onSectionChange:le.changeMachineSection,onOpenConversation:le.openConversation,onOpenRecent:be,onOpenMachineDetails:()=>z(`/machines/${X.id}`),onMachineUpgrade:()=>Y.handleMachineUpgrade(X.id),onLaunchDetectedIde:(Q,Se)=>Y.handleLaunchDetectedIde(X.id,Q,Se),onAddWorkspace:(Q,Se)=>Y.handleAddWorkspace(X.id,Q,Se),onBrowseDirectory:Q=>Y.handleBrowseDirectory(X.id,Q),onLaunchWorkspaceProvider:(Q,Se,De)=>Y.handleLaunchWorkspaceProvider(X.id,Q,Se,De),onListSavedSessions:Q=>Y.handleListSavedSessions(X.id,Q)}):t.jsx(Sh,{section:H,attentionItems:V,unreadItems:ve,workingItems:ie,completedItems:ce,hiddenConversations:s,machineCards:fe,getAvatarText:Wh,onOpenConversation:le.openConversation,onShowConversation:R,onShowAllHidden:k,onOpenNewSession:j,onOpenMachine:le.openMachine,onOpenSettings:()=>z("/settings"),onSectionChange:C,wsStatus:h,isConnected:S,isStandalone:l})})}function Qn(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Fh({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:i}){const c=o.useRef(0),[l,u]=o.useState(!1),[f,d]=o.useState(null),x=o.useCallback(()=>{c.current=0,u(!1),d(null)},[]);o.useEffect(()=>(window.addEventListener("dragend",x),window.addEventListener("drop",x),()=>{window.removeEventListener("dragend",x),window.removeEventListener("drop",x)}),[x]);const g=o.useCallback(p=>{p.dataTransfer.types.includes("text/tab-key")&&(c.current+=1,u(!0))},[]),w=o.useCallback(p=>{if(!p.dataTransfer.types.includes("text/tab-key"))return;if(p.preventDefault(),!Qn(s,r)){d("merge");return}const b=p.currentTarget.getBoundingClientRect(),h=p.clientX-b.left,S=b.width/3;h<S?d("split-left"):h>S*2?d("split-right"):d("merge")},[s,r]),M=o.useCallback(()=>{c.current-=1,!(c.current>0)&&(c.current=0,u(!1),d(null))},[]),m=o.useCallback(p=>{c.current=0,u(!1);const b=p.dataTransfer.getData("text/tab-key"),h=b?e.some(R=>R.tabKey===b):!1,S=f;if(d(null),i(),!!b){if(p.preventDefault(),S==="split-left"&&Qn(s,r)){r==null||r(b,"split-left");return}if(S==="split-right"&&Qn(s,r)){r==null||r(b,"split-right");return}if(h){a(b);return}n==null||n(b)}},[e,f,s,r,n,a,i]);return{dragOver:l,dropAction:f,resetDragState:x,handleDragEnter:g,handleDragOver:w,handleDragLeave:M,handleDrop:m}}function Uh(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 zh({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[i,c]=o.useState(s??null),[l,u]=o.useState(r??[]),[f,d]=o.useState(null),x=o.useRef(null),g=o.useRef(null),w=o.useRef(n),M=o.useRef(a);o.useEffect(()=>{w.current=n},[n]),o.useEffect(()=>{M.current=a},[a]),o.useEffect(()=>{s&&s!==i&&c(s)},[s,i]),o.useEffect(()=>{u(j=>{const v=Uh(j,e);return v.length===j.length&&v.every((y,E)=>y===j[E])?j:v})},[e]);const m=o.useMemo(()=>{const j=f??l;if(j.length===0)return e;const v=new Map(j.map((y,E)=>[y,E]));return[...e].sort((y,E)=>{const L=v.get(y.tabKey)??999,A=v.get(E.tabKey)??999;return L-A})},[e,f,l]);o.useEffect(()=>{var v,y;if(m.length===0){i!==null&&(c(null),(v=w.current)==null||v.call(w,null));return}if(i&&m.some(E=>E.tabKey===i))return;const j=m[0].tabKey;j!==i&&(c(j),(y=w.current)==null||y.call(w,j))},[m,i]);const p=o.useMemo(()=>m.find(j=>j.tabKey===i),[m,i]),b=o.useCallback(j=>{var v;c(j),(v=w.current)==null||v.call(w,j)},[]),h=o.useCallback((j,v,y)=>{u(E=>{var B;const L=E.filter(H=>H!==j),A=L.indexOf(v);if(A<0)return E;const _=y==="left"?A:A+1;return L.splice(_,0,j),(B=M.current)==null||B.call(M,L),L}),d(null)},[]),S=o.useCallback((j,v,y)=>{const L=(l.length>0?l:e.map(B=>B.tabKey)).filter(B=>B!==j),A=L.indexOf(v);if(A<0)return;const _=y==="left"?A:A+1;L.splice(_,0,j),x.current=L,d(L)},[l,e]),R=o.useCallback(()=>{var v;const j=x.current;j&&(u(j),(v=M.current)==null||v.call(M,j))},[]),k=o.useCallback(()=>{x.current=null,d(null)},[]),I=o.useCallback(j=>{u(v=>{var E;const y=v.filter(L=>L!==j);return y.push(j),(E=M.current)==null||E.call(M,y),y})},[]);return{activeTabId:i,activeConv:p,sortedConversations:m,previewOrderRef:x,draggingTabRef:g,selectTab:b,handleTabReorder:h,updatePreviewOrder:S,commitPreviewOrder:R,clearPreviewOrder:k,moveTabToEnd:I,setDraggingTabKey:j=>{g.current=j}}}function Vh({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 bo({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(pl,{}),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 gl="adhdev-tab-shortcuts";function yl(){try{return JSON.parse(localStorage.getItem(gl)||"{}")}catch{return{}}}function vl({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[i,c]=o.useState(()=>yl()),[l,u]=o.useState(null),f=o.useCallback(x=>{const g=[];return x.metaKey&&g.push(a?"⌘":"Meta"),x.ctrlKey&&g.push("Ctrl"),x.altKey&&g.push(a?"⌥":"Alt"),x.shiftKey&&g.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(x.key)?null:(g.push(x.key.length===1?x.key.toUpperCase():x.key),g.join("+"))},[a]),d=o.useCallback(x=>{c(x);try{localStorage.setItem(gl,JSON.stringify(x))}catch{}},[]);return o.useEffect(()=>{if(!e||!l)return;const x=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){u(null);return}const w=f(g);if(!w)return;const M={...i};for(const[m,p]of Object.entries(M))p===w&&delete M[m];M[l]=w,d(M),u(null)};return window.addEventListener("keydown",x,!0),()=>window.removeEventListener("keydown",x,!0)},[e,l,i,d,f]),o.useEffect(()=>{if(!e)return;const x=g=>{if(!(!g.ctrlKey&&!g.metaKey&&!g.altKey)){for(const[w,M]of Object.entries(i))if(s.includes(w)&&f(g)===M){g.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[e,i,s,r,n,f]),{isMac:a,tabShortcuts:i,shortcutListening:l,setShortcutListening:u,saveShortcuts:d}}const Gh=o.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:i,conversationKeys:c,draggingTabRef:l,onFocus:u,onSelectTab:f,onConversationActivated:d,onPreviewReorder:x,onReorderTab:g,onCommitPreviewOrder:w,onClearPreviewOrder:M,onDragStateReset:m,onDragTabKeyChange:p,onReceiveTab:b,onOpenContextMenu:h,longPressTimer:S,isGroupActive:R}){const k=qs(s),I=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",j=k.isReconnecting,v=o.useCallback(P=>{l.current=s.tabKey,p(s.tabKey),P.dataTransfer.setData("text/tab-key",s.tabKey),P.dataTransfer.effectAllowed="move"},[s.tabKey,l,p]),y=o.useCallback(()=>{l.current=null,p(null),w(),M(),m()},[l,p,w,M,m]),E=o.useCallback(P=>{const U=l.current;if(!(!U||U===s.tabKey)&&P.dataTransfer.types.includes("text/tab-key")){P.preventDefault(),P.stopPropagation();const N=P.currentTarget.getBoundingClientRect(),$=P.clientX<N.left+N.width/2?"left":"right";x(U,s.tabKey,$)}},[s.tabKey,l,x]),L=o.useCallback(P=>{P.preventDefault(),P.stopPropagation();const U=P.dataTransfer.getData("text/tab-key");if(U&&U!==s.tabKey){const N=P.currentTarget.getBoundingClientRect(),$=P.clientX<N.left+N.width/2?"left":"right";c.includes(U)?g(U,s.tabKey,$):b&&b(U)}M()},[s.tabKey,c,g,b,M]),A=o.useCallback(P=>{P.stopPropagation(),u(),f(s.tabKey),d(s)},[s,d,u,f]),_=o.useCallback(P=>{P.preventDefault(),h(P.clientX,P.clientY,s.tabKey)},[s.tabKey,h]),B=o.useCallback(P=>{const U=P.touches[0];S.current=setTimeout(()=>{h(U.clientX,U.clientY,s.tabKey)},600)},[s.tabKey,S,h]),H=o.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),C=["adhdev-dockview-tab",I,r&&"is-active",R&&"is-group-active",j&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:C,draggable:!0,onDragStart:v,onDragEnd:y,onDragOver:E,onDrop:L,onClick:A,onContextMenu:_,onTouchStart:B,onTouchEnd:H,onTouchMove:H,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?t.jsx("div",{className:"tab-spinner"}):k.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:lt(s),children:lt(s)}),t.jsx("span",{className:"adhdev-dockview-tab-meta",children:j?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:hs(s)}):k.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting",children:[hs(s),t.jsx("span",{className:"connecting-dots"})]}):hs(s)})]}),i&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${i}`,children:i})]})},(e,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function qh({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:x,onDragStateReset:g,onDragTabKeyChange:w,onReceiveTab:M,onHideTab:m,isGroupActive:p,allowTabShortcuts:b=!0}){const[h,S]=o.useState(null),R=o.useRef(null),k=o.useRef(null),I=o.useMemo(()=>e.map(_=>_.tabKey),[e]);jr("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:j,tabShortcuts:v,shortcutListening:y,setShortcutListening:E,saveShortcuts:L}=vl({enabled:b,sortedTabKeys:e.map(_=>_.tabKey),onFocus:i,onSelectTab:c});o.useEffect(()=>{if(!h)return;const _=B=>{const H=document.querySelector("[data-pane-context-menu]");H&&H.contains(B.target)||S(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[h]),o.useEffect(()=>{const _=k.current;if(!_)return;const B=H=>{Math.abs(H.deltaY)<=Math.abs(H.deltaX)||(H.preventDefault(),_.scrollLeft+=H.deltaY)};return _.addEventListener("wheel",B,{passive:!1}),()=>_.removeEventListener("wheel",B)},[]);const A=o.useCallback((_,B,H)=>{S({x:_,y:B,tabKey:H})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:k,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(_=>t.jsx(Gh,{conv:_,isActive:s===_.tabKey,isDraggedTab:a.current===_.tabKey,isTaskCompleteUnread:n.has(_.tabKey),shortcut:b?v[_.tabKey]:void 0,conversationKeys:I,draggingTabRef:a,onFocus:i,onSelectTab:c,onConversationActivated:l,onPreviewReorder:u,onReorderTab:f,onCommitPreviewOrder:d,onClearPreviewOrder:x,onDragStateReset:g,onDragTabKeyChange:w,onReceiveTab:M,onOpenContextMenu:A,longPressTimer:R,isGroupActive:p},_.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:[b&&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:_=>{_.stopPropagation(),E(h.tabKey),S(null)},children:["⌨ ",v[h.tabKey]?`Change shortcut (${v[h.tabKey]})`:"Set shortcut"]}),v[h.tabKey]&&t.jsx("button",{className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onClick:()=>{const _={...v};delete _[h.tabKey],L(_),S(null)},children:"✕ Remove shortcut"})]}),m&&t.jsxs(t.Fragment,{children:[b&&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:()=>{m(h.tabKey),S(null)},children:"🚫 Hide from Dashboard"})]})]}),b&&y&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>E(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:_=>_.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Yh({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,userName:f,groupIndex:d,onFocus:x,isSplitMode:g,numGroups:w,onMoveTab:M,onReceiveTab:m,style:p,onActiveTabChange:b,initialActiveTabId:h,initialTabOrder:S,onTabOrderChange:R,onHideTab:k,isFocused:I,allowTabShortcuts:j=!0,notificationStateBySessionId:v,liveSessionInboxState:y}){const{sendCommand:E}=Tt(),L=o.useRef(null),{activeTabId:A,activeConv:_,sortedConversations:B,draggingTabRef:H,selectTab:C,handleTabReorder:P,updatePreviewOrder:U,commitPreviewOrder:N,clearPreviewOrder:$,moveTabToEnd:z,setDraggingTabKey:q}=zh({conversations:e,initialActiveTabId:h,initialTabOrder:S,onActiveTabChange:b,onTabOrderChange:R}),W=Sn({sendDaemonCommand:a,activeConv:_,setLocalUserMessages:i,setActionLogs:c,isStandalone:l}),{dragOver:ne,dropAction:ae,resetDragState:ke,handleDragEnter:X,handleDragOver:pe,handleDragLeave:Y,handleDrop:J}=Fh({conversations:e,numGroups:w,onMoveTab:M,onReceiveTab:m,onOwnTabDrop:z,onClearPreviewOrder:$}),ue=_&&!Qe(_)&&Hs(_)==="terminal",le=o.useMemo(()=>_?s.find(ce=>ce.id===_.routeId):void 0,[s,_]),V=o.useMemo(()=>_?n.filter(ce=>ce.routeId===_.tabKey):[],[n,_]),ve=o.useMemo(()=>new Set(B.filter(ce=>Cu(ce,y,{isOpenConversation:ce.tabKey===A,notificationStateBySessionId:v})).map(ce=>ce.tabKey)),[A,y,B]);jr("PaneGroup",{groupIndex:d,conversationCount:e.length,activeTabId:A,dragOver:ne});const ie=o.useCallback(ce=>{ce.streamSource==="agent-stream"&&ce.agentType&&E(ce.routeId,ml(),{agentType:ce.agentType,...ce.sessionId&&{targetSessionId:ce.sessionId}}).catch(()=>{})},[E]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:x,style:{...p,outline:ne?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(qh,{conversations:B,activeTabId:A,groupIndex:d,numGroups:w,unreadTabKeys:ve,draggingTabRef:H,onFocus:x,onSelectTab:C,onConversationActivated:ie,onPreviewReorder:U,onReorderTab:P,onCommitPreviewOrder:N,onClearPreviewOrder:$,onDragStateReset:ke,onDragTabKeyChange:q,onMoveTab:M,onReceiveTab:m,onHideTab:k,isGroupActive:I??!1,allowTabShortcuts:j}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:X,onDragOver:pe,onDragLeave:Y,onDrop:J,children:[ne&&t.jsx(Vh,{dropAction:ae,canSplit:!!(w<4&&M)}),_?t.jsx(ho,{activeConv:_,clearToken:r[_.tabKey]||0,isCliTerminal:!!ue,ideEntry:le,terminalRef:L,handleModalButton:W.handleModalButton,handleRelaunch:W.handleRelaunch,handleSendChat:W.handleSendChat,isSendingChat:W.isSendingChat,sendFeedbackMessage:W.sendFeedbackMessage,handleFocusAgent:W.handleFocusAgent,isFocusingAgent:W.isFocusingAgent,actionLogs:V,userName:f,isInputActive:!g||!!I}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(bo,{conversationsCount:e.length,isSplitMode:g,isStandalone:l,hasRegisteredMachines:u})})]})]})}function Xh({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:f,setActionLogs:d,isStandalone:x,hasRegisteredMachines:g,userName:w,focusedGroup:M,setFocusedGroup:m,moveTabToGroup:p,splitTabRelative:b,closeGroup:h,handleResizeStart:S,groupActiveTabIds:R,setGroupActiveTabIds:k,groupTabOrders:I,setGroupTabOrders:j,toggleHiddenTab:v,allowTabShortcuts:y=!0,notificationStateBySessionId:E,liveSessionInboxState:L}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((A,_)=>{const B=s&&n.length===r?`${n[_]}%`:void 0;return t.jsxs(at.Fragment,{children:[s&&_>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:H=>S(_-1,H),onDoubleClick:()=>h(_),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(Yh,{style:s?{flexBasis:B??`${100/r}%`,flexGrow:B?0:1,flexShrink:B?0:1}:void 0,conversations:A,clearedTabs:i,ides:c,actionLogs:l,sendDaemonCommand:u,setLocalUserMessages:f,setActionLogs:d,isStandalone:x,hasRegisteredMachines:g,userName:w,groupIndex:_,isFocused:s&&M===_,onFocus:()=>m(_),isSplitMode:s,numGroups:r,onMoveTab:(H,C)=>{C==="left"&&_>0?p(H,_-1):C==="right"&&_<r-1?p(H,_+1):C==="split-left"&&r<4?b(H,_,"left"):C==="split-right"&&r<4&&b(H,_,"right")},onReceiveTab:H=>p(H,_),onActiveTabChange:H=>k(C=>(C[_]??null)===(H??null)?C:{...C,[_]:H}),initialActiveTabId:R[_],initialTabOrder:I[_],onTabOrderChange:H=>j(C=>{const P=C[_]||[];return P.length===H.length&&P.every((U,N)=>U===H[N])?C:{...C,[_]:H}}),onHideTab:v,allowTabShortcuts:y,notificationStateBySessionId:E,liveSessionInboxState:L})]},_)})})}function wl({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,i]=o.useState(null),[c,l]=o.useState(null);o.useEffect(()=>e?ht.onScreenshot("ide-page",(d,x)=>{if(d!==e)return;const g=new FileReader;g.onload=()=>i(g.result),g.readAsDataURL(x)}):void 0,[e]),o.useEffect(()=>{r!=="connected"&&i(null)},[r]),o.useEffect(()=>{var d;return e?((d=ht.onStatus)==null?void 0:d.call(ht,(x,g)=>{x===e&&g!=null&&g.screenshotUsage&&l(g.screenshotUsage)}))||(()=>{}):void 0},[e]),o.useEffect(()=>{i(null)},[e,s]),o.useEffect(()=>{const f=e?ht.get(e):null;if(!(!f||r!=="connected"))return n!=="chat"&&s?f.startScreenshots(s):f.stopScreenshots(s),()=>{f.stopScreenshots(s)}},[n,r,s,e]);const u=o.useCallback(async(f,d)=>{const x=e?ht.get(e):null;return!x||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):x.sendInput(f,d,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:c,handleRemoteAction:u}}const jl="adhdev-dashboard-action-shortcuts",Jh=1200,Qh={toggleHiddenTabs:"G H",setActiveTabShortcut:"G S",selectPreviousGroupTab:"G K",selectNextGroupTab:"G J",splitActiveTabRight:"⌘+⌥+\\",focusLeftPane:"⌘+⌥+←",focusRightPane:"⌘+⌥+→",moveActiveTabToLeftPane:"⌘+⌥+⇧+←",moveActiveTabToRightPane:"⌘+⌥+⇧+→",triggerPrimaryApprovalAction:"⌥+A",triggerSecondaryApprovalAction:"⌥+D",toggleCliView:"T"};function Zh(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function nt(e,s){switch(e){case"openShortcutHelp":return"?";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+⌥+=":"Ctrl+Alt+\\";case"splitActiveTabDown":return s?"⌘+⌥+-":"Ctrl+Alt+-";case"focusLeftPane":return s?"⌘+⌥+[":"Ctrl+Alt+←";case"focusRightPane":return s?"⌘+⌥+]":"Ctrl+Alt+→";case"focusUpPane":return s?"⌘+⌥+U":"Ctrl+Alt+↑";case"focusDownPane":return s?"⌘+⌥+J":"Ctrl+Alt+↓";case"moveActiveTabToLeftPane":return s?"⌘+⌥+,":"Ctrl+Alt+Shift+←";case"moveActiveTabToRightPane":return s?"⌘+⌥+.":"Ctrl+Alt+Shift+→";case"moveActiveTabToUpPane":return s?"⌘+⌥+I":"Ctrl+Alt+Shift+↑";case"moveActiveTabToDownPane":return s?"⌘+⌥+K":"Ctrl+Alt+Shift+↓";case"triggerPrimaryApprovalAction":return s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌥+[":"Ctrl+Alt+[";case"selectNextGroupTab":return s?"⌥+]":"Ctrl+Alt+]";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function kl(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:nt("openShortcutHelp",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:nt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:nt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:nt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:nt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:nt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:nt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:nt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:nt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:nt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:nt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:nt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:nt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:nt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:nt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:nt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:nt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:nt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:nt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:nt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:nt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:nt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:nt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:nt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:nt("toggleCliView",e)}]}function Ma(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function xn(e){const s=Object.fromEntries(kl(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(jl)||"{}"),n={...s,...r};for(const[a,i]of Object.entries(Qh))n[a]===i&&(n[a]=s[a]);return n}catch{return s}}function Sl(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function ex({enabled:e=!0,onTrigger:s}){const r=Zh(),[n,a]=o.useState(()=>xn(r)),[i,c]=o.useState(null),[l,u]=o.useState([]),f=o.useRef({parts:[],timer:null}),d=o.useCallback(m=>{const p=[];return m.metaKey&&p.push(r?"⌘":"Meta"),m.ctrlKey&&p.push("Ctrl"),m.altKey&&p.push(r?"⌥":"Alt"),m.shiftKey&&m.key.length!==1&&p.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(p.push(Sl(m.key)),p.join("+"))},[r]),x=o.useCallback(m=>{a(m);try{localStorage.setItem(jl,JSON.stringify(m))}catch{}},[]);o.useEffect(()=>{const m=xn(r),p=Object.entries(n),b=Object.entries(m);p.length===b.length&&p.every(([h,S])=>m[h]===S)||x(m)},[n,r,x]);const g=o.useCallback(()=>{typeof window<"u"&&f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current={parts:[],timer:null}},[]),w=o.useCallback(()=>{typeof window>"u"||(f.current.timer!=null&&window.clearTimeout(f.current.timer),f.current.timer=window.setTimeout(()=>{f.current={parts:[],timer:null}},Jh))},[]);o.useEffect(()=>{if(!i)return;const m=p=>{if(p.preventDefault(),p.stopPropagation(),p.key==="Escape"){c(null),u([]);return}const b=d(p);if(!b)return;const S=!(p.metaKey||p.ctrlKey||p.altKey)&&/^[A-Z0-9]$/.test(b);if(l.length===0&&S){u([b]);return}const k=[...l,b].slice(0,2).join(" "),I={...n};for(const[j,v]of Object.entries(I))v===k&&delete I[j];I[i]=k,x(I),c(null),u([])};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[n,d,x,i,l]),o.useEffect(()=>{if(!e||i)return;const m=p=>{if(p.defaultPrevented)return;const b=d(p);if(!b)return;const h=p.metaKey||p.ctrlKey||p.altKey;if(Ma(p.target)&&!h)return;const S=f.current.parts,R=h?[b]:[...S.slice(-1),b].slice(-2),k=R.join(" "),I=R[R.length-1],j=Object.entries(n).filter(([,A])=>!!A),v=j.find(([,A])=>A===k);if(v){p.preventDefault(),g(),s(v[0]);return}if(j.some(([,A])=>A.startsWith(`${k} `))){p.preventDefault(),f.current.parts=R,w();return}const E=j.find(([,A])=>A===I);if(E){p.preventDefault(),g(),s(E[0]);return}if(j.some(([,A])=>A.startsWith(`${I} `))){p.preventDefault(),f.current.parts=[I],w();return}g()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[n,w,e,d,s,g,i]),o.useEffect(()=>()=>g(),[g]);const M=o.useMemo(()=>kl(r),[r]);return{isMac:r,actionDefinitions:M,actionShortcuts:n,shortcutListening:i,shortcutListeningDraft:l,setShortcutListening:c,setShortcutListeningDraft:u,saveShortcuts:x}}function tx({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:n.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:n.dockActiveTab})):s?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:n.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:n.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:n.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:r?`Change shortcut (${r})`:"Set shortcut",shortcut:n.setActiveTabShortcut}),r&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:n.hideCurrentTab,tone:"muted"}),a}function sx(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function ki({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!sx(n):!0}const Nl=o.createContext(null);function Mn(){const e=o.useContext(Nl);if(!e)throw new Error("DashboardDockviewContext missing");return e}function nn(e){return lt(e)||e.tabKey}function rx(e){return`remote:${e}`}function ts(e){return e.startsWith("remote:")}function Si(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Zn(e){var r,n,a,i,c;const s=e==null?void 0:e.defaultView;if(s)try{s.focus(),(n=(r=e==null?void 0:e.body)==null?void 0:r.focus)==null||n.call(r),(i=(a=e==null?void 0:e.documentElement)==null?void 0:a.focus)==null||i.call(a),(c=s.requestAnimationFrame)==null||c.call(s,()=>{var l,u;try{s.focus(),(u=(l=e==null?void 0:e.body)==null?void 0:l.focus)==null||u.call(l)}catch{}})}catch{}}function Yr(e,s){e.classList.remove(ma.className,pa.className),e.classList.add(s==="light"?ma.className:pa.className)}function Ni(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 nx(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 ax(e,s,r){var c;const n=[s];let a;for(const l of n){let u;for(const f of l){const d=e.addPanel({id:f.tabKey,component:"conversation",title:nn(f),params:{kind:"conversation",tabKey:f.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return r??((c=s[0])==null?void 0:c.tabKey)??null}function Ci(e,s){const r=new Set(s.map(n=>n.tabKey));for(const n of[...e.panels])ts(n.id)||r.has(n.id)||e.removePanel(n);for(const n of s){const a=e.getPanel(n.tabKey);if(a){a.update({params:{tabKey:n.tabKey}}),a.title!==nn(n)&&a.api.setTitle(nn(n));continue}e.addPanel({id:n.tabKey,component:"conversation",title:nn(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 Ii(e,s,r){var u,f;const n=r?rx(r):null;for(const d of[...e.panels])ts(d.id)&&(!n||d.id!==n)&&e.removePanel(d);if(!r||!n)return;const a=Ht(s,r);if(!a&&e.totalPanels===0)return;const i=e.getPanel(n),c=Kc(a);if(i){i.title!==c&&i.api.setTitle(c);return}const l=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((f=e.panels.find(d=>!ts(d.id)))==null?void 0:f.id);e.addPanel({id:n,component:"remote",title:c,params:{kind:"remote",routeId:r},...l?{position:{referencePanel:l,direction:"right"},inactive:!0}:{}})}function ox({params:e,api:s}){var x;const r=Mn(),n=o.useRef(null),[a,i]=o.useState(s.isActive),c=r.conversationsByTabKey.get(e.tabKey),l=Sn({sendDaemonCommand:r.sendDaemonCommand,activeConv:c,setLocalUserMessages:r.setLocalUserMessages,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});o.useEffect(()=>{i(s.isActive);const g=[s.onDidActiveChange(w=>i(w.isActive)),s.onDidActiveGroupChange(w=>{if(!s.isActive&&!w.isActive){i(!1);return}i(s.isActive)})];return()=>{for(const w of g)w.dispose()}},[s]);const u=o.useMemo(()=>c?r.ides.find(g=>g.id===c.routeId):void 0,[r.ides,c]),f=o.useMemo(()=>c?r.actionLogs.filter(g=>g.routeId===c.tabKey):[],[r.actionLogs,c]);if(!c)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(bo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,suppressGuide:r.hasDetachedConversationPanels})});const d=!Qe(c)&&Hs(c)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(ho,{activeConv:c,clearToken:r.clearedTabs[c.tabKey]||0,isCliTerminal:d,ideEntry:u,terminalRef:n,handleModalButton:l.handleModalButton,handleRelaunch:l.handleRelaunch,handleSendChat:l.handleSendChat,isSendingChat:l.isSendingChat,handleFocusAgent:l.handleFocusAgent,isFocusingAgent:l.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((x=r.scrollToBottomRequest)==null?void 0:x.tabKey)===c.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a})})}function ix({params:e}){var u;const s=Mn(),r=o.useMemo(()=>Ht([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=o.useMemo(()=>s.ides.find(f=>f.id===e.routeId),[s.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((u=r==null?void 0:r.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:i,screenshotUsage:c,handleRemoteAction:l}=wl({doId:a,targetSessionId:r?wc(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(rc,{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 cx(){const e=Mn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(bo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,suppressGuide:e.hasDetachedConversationPanels})})}function lx(e){var w,M;nx(e);const s=Mn(),r=o.useCallback(m=>{"button"in m&&m.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const m=Ht([...s.conversationsByTabKey.values()],e.params.routeId),p=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,b=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${b?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(m==null?void 0:m.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:m!=null&&m.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:m.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=jn(n,s.liveSessionInboxState,{isOpenConversation:a,notificationStateBySessionId:s.notificationStateBySessionId}),l=c.isReconnecting,u=c.isConnecting,f=c.isGenerating,d=c.isWaiting,x=c.unread,g=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${i?" is-group-active":""}${l?" is-reconnecting":""}`,title:lt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:m=>{var p;m.preventDefault(),r(m),s.openTabContextMenu({x:m.clientX,y:m.clientY,tabKey:n.tabKey,sourceDocument:((p=m.target)==null?void 0:p.ownerDocument)??document})},children:[x&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:f?t.jsx("div",{className:"tab-spinner"}):d?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):l?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):u?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:lt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:l?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:hs(n)}):u?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:hs(n)}):t.jsx("span",{children:hs(n)})})]}),g&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:g,children:g})]})}function dx({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setLocalUserMessages:i,setActionLogs:c,isStandalone:l,hasRegisteredMachines:u,initialDataLoaded:f,userName:d,toggleHiddenTab:x,actionShortcuts:g,registerActionHandlers:w,onActiveTabChange:M,requestedActiveTabKey:m,requestedRemoteIdeId:p,onRequestedActiveTabConsumed:b,scrollToBottomRequest:h,notificationStateBySessionId:S,liveSessionInboxState:R}){var Dt,Z,Ke;const{theme:k}=no(),{sendCommand:I}=Tt(),j=o.useRef(null),v=o.useRef(null),y=o.useRef(!1),E=o.useRef(!1),L=o.useRef(!1),A=o.useRef(null),_=o.useRef([]),[B,H]=o.useState(null),[C,P]=o.useState(!1),[U,N]=o.useState(!1),[$,z]=o.useState(0),q=o.useRef(null),W=o.useMemo(()=>il(typeof window<"u"?window.innerWidth:1280),[]),ne=o.useRef(typeof window>"u"?{}:Uf(W)),ae=o.useMemo(()=>new Map(e.map(D=>[D.tabKey,D])),[e]),ke=o.useMemo(()=>{const D=j.current;return D?D.groups.some(O=>{try{const F=O.model.location.type;return F!=="floating"&&F!=="popout"?!1:O.panels.some(G=>ae.has(G.id))}catch{return!1}}):!1},[ae,$,e]),X=o.useCallback(()=>{var D;(D=j.current)==null||D.focus()},[]),pe=o.useCallback(D=>{const O=document,F=D.document;for(const Ae of O.querySelectorAll('link[rel="stylesheet"]')){const We=F.createElement("link");We.rel="stylesheet",We.href=Ae.href,Ae.crossOrigin&&(We.crossOrigin=Ae.crossOrigin),F.head.appendChild(We)}for(const Ae of O.querySelectorAll("style")){const We=F.createElement("style");We.textContent=Ae.textContent,F.head.appendChild(We)}const G=[];for(const Ae of O.styleSheets)try{for(const We of Ae.cssRules)We instanceof CSSStyleRule&&(We.selectorText===":root"||We.selectorText==="html")&&G.push(We.cssText)}catch{}if(G.length>0){const Ae=F.createElement("style");Ae.textContent=G.join(`
|
|
44
|
-
`),F.head.appendChild(Ae)}const oe=O.documentElement.getAttribute("data-theme");oe&&F.documentElement.setAttribute("data-theme",oe),F.documentElement.style.colorScheme=oe==="light"?"light":"dark",F.body.className=O.body.className;const Ie=O.documentElement.getAttribute("style");Ie&&F.documentElement.setAttribute("style",Ie);const Le=F.getElementById("dv-popout-window");Le instanceof HTMLElement&&(Le.classList.add("adhdev-dockview"),Yr(Le,k))},[k]),Y=o.useCallback(()=>{var O;const D=j.current;if(D)for(const F of D.groups)try{const G=(O=F.element)==null?void 0:O.ownerDocument;if(!G||G===document)continue;const oe=G.getElementById("dv-popout-window");oe instanceof HTMLElement&&(oe.classList.add("adhdev-dockview"),Yr(oe,k));const Ie=document.documentElement.getAttribute("data-theme");Ie&&G.documentElement.setAttribute("data-theme",Ie),G.documentElement.style.colorScheme=Ie==="light"?"light":"dark",G.body.className=document.body.className;const Le=document.documentElement.getAttribute("style");Le?G.documentElement.setAttribute("style",Le):G.documentElement.removeAttribute("style")}catch{}},[k]),J=o.useCallback(()=>{var O;const D=j.current;if(D)for(const F of D.groups)try{const G=(O=F.element)==null?void 0:O.ownerDocument;if(!G||G===document)continue;const oe=G.getElementById("dv-popout-window");if(!(oe instanceof HTMLElement))continue;oe.classList.add("adhdev-dockview"),Yr(oe,k),oe.classList.toggle("is-showing-dockview-overlay",U),oe.classList.toggle("is-dragging-dockview",C)}catch{}},[C,U,k]),ue=o.useCallback(D=>{const O=j.current;if(!O)return;const F=O.getPanel(D);F&&O.addPopoutGroup(F,{popoutUrl:"/popout.html",onDidOpen:({window:G})=>{pe(G),je();const oe=ae.get(D);G.document.title=oe?`${lt(oe)} — ADHDev`:"ADHDev — Popout"}})},[ae,pe]),le=o.useCallback(D=>{const O=j.current,F=O==null?void 0:O.getPanel(D);if(!O||!F)return;const G=O.groups.filter(oe=>{var Ie;try{return((Ie=oe.element)==null?void 0:Ie.ownerDocument)===document}catch{return!0}});G.length>0?F.api.moveTo({group:G[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),V=o.useCallback(D=>{var G;const O=j.current;if(!O)return!1;const F=O.getPanel(D);if(!F)return!1;try{return((G=F.group.element)==null?void 0:G.ownerDocument)!==document}catch{return!1}},[]),ve=o.useCallback(D=>{V(D)&&le(D),x(D)},[V,le,x]),ie=o.useCallback(D=>{const O=j.current,F=O==null?void 0:O.getPanel(D);!O||!F||O.addFloatingGroup(F,{width:600,height:500})},[]),ce=o.useCallback(D=>{var F;const O=(F=j.current)==null?void 0:F.getPanel(D);if(!O)return!1;try{return O.group.model.location.type==="floating"}catch{return!1}},[]),te=o.useCallback(()=>{var O,F;const D=(F=(O=j.current)==null?void 0:O.activePanel)==null?void 0:F.id;return!D||ts(D)?null:ae.has(D)?D:null},[ae]),me=o.useCallback(D=>{const O=j.current,F=O==null?void 0:O.getPanel(D);if(!O||!F)return;const G=O.groups.filter(oe=>{try{return oe.model.location.type==="grid"}catch{return!0}});G.length>0?F.api.moveTo({group:G[0],position:"center"}):F.api.moveTo({position:"center"}),F.api.setActive()},[]),re=o.useCallback(()=>{var Ie;const D=j.current;if(!D)return;const F=D.groups.filter(Le=>{var Ae;try{return((Ae=Le.element)==null?void 0:Ae.ownerDocument)===document&&Le.model.location.type==="grid"}catch{return!1}})[0]||null,G=[...D.panels];for(const Le of G){const Ae=(Ie=Le.group.element)==null?void 0:Ie.ownerDocument,We=Le.group.model.location.type;Ae===document&&We==="grid"||(F&&F.id!==Le.group.id?Le.api.moveTo({group:F,position:"center"}):Le.api.moveTo({position:"center"}))}const oe=D.activePanel;oe&&(oe.group.model.openPanel(oe),oe.api.setActive()),Zn(document)},[]),je=o.useCallback(()=>{var O,F;const D=j.current;if(D)for(const G of D.groups){const oe=(O=G.element)==null?void 0:O.ownerDocument;if(!oe||oe===document)continue;const Ie=oe.getElementById("dv-popout-window");if(!(Ie instanceof HTMLElement))continue;let Le=null,Ae=oe.title||"ADHDev",We="Popout workspace";const Be=G.activePanel;if(Be)if(Le=Be.id,ts(Be.id)){const Ne=((F=Be.params)==null?void 0:F.routeId)||Be.id.slice(7),_e=Ht([...ae.values()],Ne);Ae=Kc(_e),We=_e!=null&&_e.machineName?`Remote view · ${_e.machineName}`:"Remote view"}else{const Ne=ae.get(Be.id);Ae=Ne?lt(Ne):Be.title||Be.id,We=Ne?hs(Ne):"Dockview panel"}oe.title=`${Ae} — ADHDev`;let Ge=oe.getElementById("adhdev-popout-header");Ge instanceof HTMLElement||(Ge=oe.createElement("div"),Ge.id="adhdev-popout-header",oe.body.appendChild(Ge)),Ge.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(";")),Ge.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;">${Si(Ae)}</div>
|
|
48
|
-
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${Si(We)}</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
|
-
`,Ie.style.top="52px",Ie.style.height="calc(100% - 52px)";const Ze=Ge.querySelector("[data-adhdev-popout-focus]");Ze&&(Ze.onclick=()=>{window.focus()});const se=Ge.querySelector("[data-adhdev-popout-dock]");se&&(se.disabled=!Le,se.style.opacity=Le?"1":"0.5",se.style.cursor=Le?"pointer":"default",se.onclick=()=>{var Ne;Le&&le(Le),(Ne=oe.defaultView)==null||Ne.focus()})}},[ae,le]),we=o.useCallback(D=>{var G;const O=j.current,F=O==null?void 0:O.getPanel(D);if(!(!O||!F)){F.group.model.openPanel(F),F.api.setActive();try{const oe=F.group.model.location;oe.type==="popout"?oe.getWindow().focus():Zn((G=F.group.element)==null?void 0:G.ownerDocument)}catch{}}},[]),Te=o.useCallback(D=>{const O=j.current,F=O==null?void 0:O.activePanel,G=(O==null?void 0:O.activeGroup)||(F==null?void 0:F.group);if(!O||!F||!G)return;const oe=G.panels||[];if(oe.length<=1)return;const Ie=oe.findIndex(We=>We.id===F.id);if(Ie<0)return;const Le=(Ie+D+oe.length)%oe.length,Ae=oe[Le];Ae&&(Ae.group.model.openPanel(Ae),Ae.api.setActive())},[]),T=o.useCallback(D=>{var se;const O=j.current,F=(O==null?void 0:O.activeGroup)||((se=O==null?void 0:O.activePanel)==null?void 0:se.group);if(!O||!F)return;const G=O.groups||[],oe=G.find(Ne=>Ne.id===F.id);if(!oe)return;const Ie=oe.element.getBoundingClientRect(),Le=Ie.left+Ie.width/2,Ae=Ie.top+Ie.height/2,We=(Ne,_e,rt,K)=>Math.max(0,Math.min(_e,K)-Math.max(Ne,rt)),Be=Ne=>{const _e=Ne.element.getBoundingClientRect(),rt=_e.left+_e.width/2,K=_e.top+_e.height/2;let ee=0,xe=0,Ee=0,Re=!1;if(D==="left"?(Re=rt<Le,ee=Math.max(0,Ie.left-_e.right),xe=Math.abs(K-Ae),Ee=We(Ie.top,Ie.bottom,_e.top,_e.bottom)):D==="right"?(Re=rt>Le,ee=Math.max(0,_e.left-Ie.right),xe=Math.abs(K-Ae),Ee=We(Ie.top,Ie.bottom,_e.top,_e.bottom)):D==="above"?(Re=K<Ae,ee=Math.max(0,Ie.top-_e.bottom),xe=Math.abs(rt-Le),Ee=We(Ie.left,Ie.right,_e.left,_e.right)):(Re=K>Ae,ee=Math.max(0,_e.top-Ie.bottom),xe=Math.abs(rt-Le),Ee=We(Ie.left,Ie.right,_e.left,_e.right)),!Re)return Number.POSITIVE_INFINITY;const Ce=Ee>0?0:120;return ee*3+xe+Ce};let Ge=null,Ze=Number.POSITIVE_INFINITY;for(const Ne of G){if(Ne.id===oe.id)continue;const _e=Be(Ne);Number.isFinite(_e)&&(_e>=Ze||(Ze=_e,Ge=Ne))}return Ge||void 0},[]),fe=o.useCallback(D=>{var G;const O=T(D);if(!O)return;const F=O.activePanel||O.panels[0];F&&(O.model.openPanel(F),F.api.setActive(),Zn((G=O.element)==null?void 0:G.ownerDocument))},[T]),be=o.useCallback((D,O)=>{const F=j.current,G=F==null?void 0:F.activePanel,oe=(F==null?void 0:F.activeGroup)||(G==null?void 0:G.group);if(!F||!G||!oe)return;let Ie=T(D);!Ie&&(O!=null&&O.createGroupIfMissing)&&(Ie=F.addGroup({referenceGroup:oe,direction:D})),Ie&&(G.api.moveTo({group:Ie,position:"center"}),G.group.model.openPanel(G),G.api.setActive())},[T]),{isMac:Q,tabShortcuts:Se,shortcutListening:De,setShortcutListening:Oe,saveShortcuts:$e}=vl({sortedTabKeys:e.map(D=>D.tabKey),onFocus:X,onSelectTab:we}),Ue=o.useCallback(()=>{var F;const D=j.current;if(!D)return;const O=D.activePanel;if(O){if(ts(O.id)){const G=((F=O.params)==null?void 0:F.routeId)||O.id.slice(7),oe=Ht(e,G);oe!=null&&oe.tabKey&&Oe(oe.tabKey);return}ae.has(O.id)&&Oe(O.id)}},[ae,we,Oe,e]),ze=o.useCallback(D=>{const O=[];return D.metaKey&&O.push(Q?"⌘":"Meta"),D.ctrlKey&&O.push("Ctrl"),D.altKey&&O.push(Q?"⌥":"Alt"),D.shiftKey&&D.key.length!==1&&O.push(Q?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(D.key)?null:(O.push(Sl(D.key)),O.join("+"))},[Q]),mt=o.useCallback(D=>{var O,F;switch(D){case"splitActiveTabRight":be("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":be("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const G=te();G&&ie(G);return}case"popoutActiveTab":{const G=te();G&&ue(G);return}case"dockActiveTab":{const G=te();if(!G)return;V(G)?le(G):ce(G)&&me(G);return}case"focusLeftPane":fe("left");return;case"focusRightPane":fe("right");return;case"focusUpPane":fe("above");return;case"focusDownPane":fe("below");return;case"moveActiveTabToLeftPane":be("left");return;case"moveActiveTabToRightPane":be("right");return;case"moveActiveTabToUpPane":be("above");return;case"moveActiveTabToDownPane":be("below");return;case"selectPreviousGroupTab":Te(-1);return;case"selectNextGroupTab":Te(1);return;case"setActiveTabShortcut":Ue();return;case"hideCurrentTab":{const G=(F=(O=j.current)==null?void 0:O.activePanel)==null?void 0:F.id;G&&!ts(G)&&ve(G);return}default:return}},[Te,me,fe,ie,te,ve,ce,V,le,be,ue,Ue]);o.useEffect(()=>{if(!B)return;const D=B.sourceDocument,O=D.defaultView??window,F=G=>{const oe=D.querySelector("[data-dockview-tab-context-menu]");oe&&oe.contains(G.target)||H(null)};return O.addEventListener("mousedown",F,!0),O!==window&&window.addEventListener("mousedown",()=>H(null),!0),()=>{O.removeEventListener("mousedown",F,!0),O!==window&&window.removeEventListener("mousedown",()=>H(null),!0)}},[B]);const it=o.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:ae,hasDetachedConversationPanels:ke,ides:r,isStandalone:l,hasRegisteredMachines:u,liveSessionInboxState:R,notificationStateBySessionId:S,sendDaemonCommand:a,setActionLogs:c,setLocalUserMessages:i,toggleHiddenTab:ve,userName:d,scrollToBottomRequest:h,tabShortcuts:Se,openTabContextMenu:({x:D,y:O,tabKey:F,sourceDocument:G})=>H({x:D,y:O,tabKey:F,sourceDocument:G??document}),popoutTab:ue,moveTabBackToMain:le,isTabInPopout:V,floatTab:ie,isTabFloating:ce}),[n,s,ae,ke,r,l,u,R,S,a,c,i,ve,d,h,Se,ue,le,V,ie,ce]),xt=B?tx({isTabInPopout:V(B.tabKey),isTabFloating:ce(B.tabKey),tabShortcut:Se[B.tabKey],actionShortcuts:g}):[],Ve=o.useCallback(D=>{var G;const O=j.current;if((((G=O==null?void 0:O.activePanel)==null?void 0:G.id)??null)===D.id){D.group.model.openPanel(D);return}D.group.model.openPanel(D),D.api.setActive()},[]),pt=o.useCallback(D=>{if(!D)return!1;const O=j.current;if(!O)return!1;const F=O.getPanel(D);return F?(Ve(F),b==null||b(),!0):!1},[Ve,b]),bt=o.useCallback(()=>{if(L.current)return!1;const D=pt(A.current);return D&&(L.current=!0),D},[pt]),ct=o.useCallback(()=>{var O;const D=j.current;D&&Ff(W,{activeTabId:((O=D.activePanel)==null?void 0:O.id)??null,layout:D.toJSON()})},[W]),Me=o.useCallback(()=>{zf(W,ne.current)},[W]),Je=o.useCallback(D=>{var G,oe,Ie,Le;const O=j.current;if(!O)return{kind:"grid"};const F=O.toJSON();for(const Ae of F.floatingGroups||[])if((oe=(G=Ae.data)==null?void 0:G.views)!=null&&oe.includes(D)&&Ae.position)return{kind:"floating",position:Ae.position};for(const Ae of F.popoutGroups||[])if((Le=(Ie=Ae.data)==null?void 0:Ie.views)!=null&&Le.includes(D))return{kind:"popout",position:Ae.position,popoutUrl:Ae.url};return{kind:"grid"}},[]),Ye=o.useCallback(D=>{const O=j.current;if(!O)return;const F=O.getPanel(D),G=ne.current[D];if(!F||!G||G.kind==="grid")return;if(F.group.model.location.type===G.kind){delete ne.current[D],Me();return}if(G.kind==="floating"){O.addFloatingGroup(F,{x:G.position.left??24,y:G.position.top??24,width:G.position.width,height:G.position.height}),delete ne.current[D],Me();return}delete ne.current[D],Me()},[Me]);o.useEffect(()=>(w==null||w({setShortcutForActiveTab:Ue,restoreHiddenTabToSavedLocation:Ye,activateConversationTab:we,resetAllPanelsToMain:re,activatePreviousTabInGroup:()=>Te(-1),activateNextTabInGroup:()=>Te(1),floatActiveTab:()=>{const D=te();D&&ie(D)},popoutActiveTab:()=>{const D=te();D&&ue(D)},dockActiveTab:()=>{const D=te();D&&(V(D)?le(D):ce(D)&&me(D))},splitActiveTabRight:()=>be("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>be("below",{createGroupIfMissing:!0}),focusLeftPane:()=>fe("left"),focusRightPane:()=>fe("right"),focusUpPane:()=>fe("above"),focusDownPane:()=>fe("below"),moveActiveTabToLeftPane:()=>be("left"),moveActiveTabToRightPane:()=>be("right"),moveActiveTabToUpPane:()=>be("above"),moveActiveTabToDownPane:()=>be("below")}),()=>w==null?void 0:w(null)),[Te,me,ie,fe,te,ce,V,be,le,ue,w,re,Ye,we,Ue]);const Fe=o.useCallback(()=>{const D=v.current;if(!D)return;const O=D.querySelectorAll(".dv-drop-target-container, .dv-drop-target-anchor, .dv-drop-target-dropzone, .dv-drop-target-selection");for(const F of O)F.setAttribute("data-adhdev-force-hidden","true")},[]),dt=o.useCallback(()=>{const D=v.current;if(!D)return;const O=D.querySelectorAll('[data-adhdev-force-hidden="true"]');for(const F of O)F.removeAttribute("data-adhdev-force-hidden")},[]),vt=o.useCallback(()=>{const D=v.current;if(!D)return;const O=D.querySelectorAll(".dv-drop-target-container");for(const oe of O)oe.remove();const F=D.querySelectorAll(".dv-drop-target-dropzone");for(const oe of F)oe.remove();const G=D.querySelectorAll(".dv-drop-target");for(const oe of G)oe.classList.remove("dv-drop-target")},[]),jt=o.useCallback(()=>{P(!1),N(!1),dt(),Fe(),vt(),!(typeof window>"u")&&(q.current!=null&&window.clearTimeout(q.current),window.requestAnimationFrame(()=>{Fe(),vt()}),q.current=window.setTimeout(()=>{Fe(),vt(),q.current=null},80))},[dt,Fe,vt]),Lt=o.useCallback(D=>{var F;j.current=D.api;const O=Hf(W);if(A.current=(O==null?void 0:O.activeTabId)??null,O!=null&&O.layout&&D.api.fromJSON(O.layout,{reuseExistingPanels:!1}),E.current=ki({hasStoredLayout:!!(O!=null&&O.layout),initialDataLoaded:f,visibleConversationCount:e.length,ides:r}),E.current||(Ci(D.api,e),Ii(D.api,e,p)),D.api.totalPanels===0&&e.length>0){const G=ax(D.api,e,m);if(G){const oe=D.api.getPanel(G);oe&&Ve(oe)}}else!E.current&&!pt(m)&&bt();y.current=!0,D.api.onDidActivePanelChange(G=>{var Ie;if(A.current=(G==null?void 0:G.id)??null,L.current=!0,je(),G&&ts(G.id)){const Le=((Ie=G.params)==null?void 0:Ie.routeId)||G.id.slice(7),Ae=Ht(e,Le);M((Ae==null?void 0:Ae.tabKey)??null),ct();return}if(M((G==null?void 0:G.id)??null),ct(),!G)return;const oe=ae.get(G.id);(oe==null?void 0:oe.streamSource)==="agent-stream"&&oe.agentType&&I(oe.routeId,ml(),{agentType:oe.agentType,...oe.sessionId&&{targetSessionId:oe.sessionId}}).catch(()=>{})}),D.api.onDidLayoutChange(()=>{ct(),je(),z(G=>G+1)}),D.api.onWillDragPanel(()=>{P(!0),N(!1),Fe()}),D.api.onWillDragGroup(()=>{P(!0),N(!1),Fe()}),D.api.onWillShowOverlay(()=>{dt(),N(!0)}),D.api.onDidMovePanel(jt),D.api.onDidDrop(jt),D.api.onDidAddGroup(G=>{requestAnimationFrame(()=>{var oe,Ie;try{const Le=(oe=G.element)==null?void 0:oe.ownerDocument;if(!Le||Le===document)return;(Ie=Le.getElementById("dv-popout-window"))==null||Ie.classList.add("adhdev-dockview");const Ae=document.documentElement.getAttribute("data-theme");Ae&&Le.documentElement.setAttribute("data-theme",Ae),Le.body.className=document.body.className;const We=document.documentElement.getAttribute("style");We&&Le.documentElement.setAttribute("style",We)}catch{}je(),z(Le=>Le+1)})}),M(((F=D.api.activePanel)==null?void 0:F.id)??null)},[Ve,pt,jt,dt,ae,r,f,W,Fe,M,ct,m,p,I,je,e]);o.useLayoutEffect(()=>{const D=j.current;if(!D||!y.current||E.current&&ki({hasStoredLayout:!0,initialDataLoaded:f,visibleConversationCount:e.length,ides:r}))return;E.current&&(E.current=!1);const O=_.current,F=new Set(O),G=e.map(Be=>Be.tabKey),oe=new Set(G);let Ie=!1;for(const Be of O)oe.has(Be)||(ne.current[Be]=Je(Be),Ie=!0);Ie&&Me(),Ci(D,e),Ii(D,e,p);const Le=G.filter(Be=>!F.has(Be));let Ae=!1;for(const Be of Le){const Ge=D.getPanel(Be),Ze=ne.current[Be];if(!Ge||!Ze||Ze.kind==="grid")continue;if(Ge.group.model.location.type===Ze.kind){delete ne.current[Be],Ae=!0;continue}if(Ze.kind==="floating"){D.addFloatingGroup(Ge,{x:Ze.position.left??24,y:Ze.position.top??24,width:Ze.position.width,height:Ze.position.height}),delete ne.current[Be],Ae=!0;continue}}if(Ae&&Me(),_.current=G,m&&pt(m))return;!D.activePanel&&D.panels[0]&&Ve(D.panels[0]),!!(D.activePanel&&D.getPanel(D.activePanel.id))||bt()},[Ve,pt,bt,r,f,Me,Je,m,p,e]),o.useEffect(()=>{y.current&&pt(m)},[pt,m]),o.useEffect(()=>{if(!C||typeof window>"u")return;const D=()=>jt();return window.addEventListener("pointerup",D),window.addEventListener("mouseup",D),window.addEventListener("dragend",D),()=>{window.removeEventListener("pointerup",D),window.removeEventListener("mouseup",D),window.removeEventListener("dragend",D)}},[jt,C]),o.useEffect(()=>()=>{typeof window>"u"||q.current!=null&&window.clearTimeout(q.current)},[]),o.useEffect(()=>{const D=F=>{const G=F.target;if(!G)return;const oe=G.querySelector("[data-tab-key]")||G.closest("[data-tab-key]");if(oe){const Ie=oe.getAttribute("data-tab-key");if(Ie&&F.dataTransfer){const Le=G.closest(".dv-tab")||oe.closest(".dv-tab")||oe;F.dataTransfer.effectAllowed="move",F.dataTransfer.setData("text/tab-key",Ie),Le instanceof HTMLElement&&F.dataTransfer.setDragImage(Le,Math.max(12,Math.round(Le.clientWidth/2)),Math.max(10,Math.round(Le.clientHeight/2)))}}};window.addEventListener("dragstart",D);const O=Ni(j.current);for(const F of O)F.addEventListener("dragstart",D);return()=>{window.removeEventListener("dragstart",D);for(const F of O)F.removeEventListener("dragstart",D)}},[$]),o.useEffect(()=>{var O;const D=(O=v.current)==null?void 0:O.querySelector(".adhdev-dockview");D instanceof HTMLElement&&Yr(D,k),Y(),je(),J()},[je,J,Y,k]),o.useEffect(()=>{je(),J()},[je,J]),o.useEffect(()=>{const D=O=>{if(O.defaultPrevented||De)return;const F=ze(O);if(!F)return;const G=O.metaKey||O.ctrlKey||O.altKey;Ma(O.target)&&!G||xn(Q).setActiveTabShortcut!==F||(O.preventDefault(),O.stopPropagation(),Ue())};return window.addEventListener("keydown",D,!0),()=>window.removeEventListener("keydown",D,!0)},[ze,Q,De,Ue]),o.useEffect(()=>{const D=v.current;if(!D)return;const O=F=>{var Ae,We;if(!F.isTrusted)return;const G=(We=(Ae=F.target)==null?void 0:Ae.closest)==null?void 0:We.call(Ae,".dv-scrollable");if(!G)return;F.preventDefault(),F.stopPropagation();const oe=Math.abs(F.deltaX),Ie=Math.abs(F.deltaY),Le=oe>Ie?F.deltaX:F.deltaY;G.dispatchEvent(new WheelEvent("wheel",{deltaY:Le,deltaMode:F.deltaMode,bubbles:!1,cancelable:!0}))};return D.addEventListener("wheel",O,{passive:!1,capture:!0}),()=>D.removeEventListener("wheel",O,{capture:!0})},[]),o.useEffect(()=>{const D=Ni(j.current);if(D.length===0)return;const O=D.map(F=>{let G=[],oe=null;const Ie=()=>{oe!=null&&F.clearTimeout(oe),oe=null,G=[]},Le=()=>{oe!=null&&F.clearTimeout(oe),oe=F.setTimeout(()=>{oe=null,G=[]},1200)},Ae=Be=>{if(!Be.ctrlKey&&!Be.metaKey&&!Be.altKey)return;const Ge=ze(Be);if(!Ge)return;const Ze=yl();for(const[se,Ne]of Object.entries(Ze))if(e.some(_e=>_e.tabKey===se)&&Ne===Ge){Be.preventDefault(),we(se);return}},We=Be=>{if(Be.defaultPrevented||De)return;const Ge=ze(Be);if(!Ge)return;const Ze=Be.metaKey||Be.ctrlKey||Be.altKey;if(Ma(Be.target)&&!Ze)return;const se=xn(Q),Ne=Object.entries(se).filter(([Ce,et])=>!!et&&(Ce==="splitActiveTabRight"||Ce==="splitActiveTabDown"||Ce==="floatActiveTab"||Ce==="popoutActiveTab"||Ce==="dockActiveTab"||Ce==="focusLeftPane"||Ce==="focusRightPane"||Ce==="focusUpPane"||Ce==="focusDownPane"||Ce==="moveActiveTabToLeftPane"||Ce==="moveActiveTabToRightPane"||Ce==="moveActiveTabToUpPane"||Ce==="moveActiveTabToDownPane"||Ce==="selectPreviousGroupTab"||Ce==="selectNextGroupTab"||Ce==="setActiveTabShortcut"||Ce==="hideCurrentTab")),_e=Ze?[Ge]:[...G.slice(-1),Ge].slice(-2),rt=_e.join(" "),K=_e[_e.length-1],ee=Ne.find(([,Ce])=>Ce===rt);if(ee){Be.preventDefault(),Ie(),mt(ee[0]);return}if(Ne.some(([,Ce])=>Ce.startsWith(`${rt} `))){Be.preventDefault(),G=_e,Le();return}const Ee=Ne.find(([,Ce])=>Ce===K);if(Ee){Be.preventDefault(),Ie(),mt(Ee[0]);return}if(Ne.some(([,Ce])=>Ce.startsWith(`${K} `))){Be.preventDefault(),G=[K],Le();return}Ie()};return F.addEventListener("keydown",Ae),F.addEventListener("keydown",We),()=>{Ie(),F.removeEventListener("keydown",Ae),F.removeEventListener("keydown",We)}});return()=>{for(const F of O)F()}},[ze,Q,$,we,De,mt,e]);const Mt=k==="light"?ma:pa,Ct=((Ke=(Z=(Dt=j.current)==null?void 0:Dt.activePanel)==null?void 0:Z.group.element)==null?void 0:Ke.ownerDocument)??document;return t.jsxs(Nl.Provider,{value:it,children:[t.jsx("div",{ref:v,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(yd,{className:`h-full min-h-0 min-w-0 adhdev-dockview${C?" is-dragging-dockview":""}${U?" is-showing-dockview-overlay":""}`,components:{conversation:ox,remote:ix},defaultTabComponent:lx,watermarkComponent:cx,onReady:Lt,singleTabMode:"default",tabAnimation:"smooth",theme:Mt,popoutUrl:"/popout.html"})}),B&&pr.createPortal(t.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:B.x,top:B.y},children:xt.map(D=>{if(D.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},D.id);let O=t.jsx(au,{size:13,className:"shrink-0 opacity-70"}),F=()=>{};switch(D.id){case"dockInWindow":case"dockBackToGrid":O=t.jsx(iu,{size:13,className:"shrink-0 opacity-70"}),F=()=>{me(B.tabKey),H(null)};break;case"moveBackToMain":O=t.jsx(nu,{size:13,className:"shrink-0 opacity-70"}),F=()=>{le(B.tabKey),H(null)};break;case"floatAsPanel":O=t.jsx(ou,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ie(B.tabKey),H(null)};break;case"openInNewWindow":O=t.jsx(ru,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ue(B.tabKey),H(null)};break;case"setShortcut":F=G=>{G.stopPropagation(),Oe(B.tabKey),H(null)};break;case"removeShortcut":O=t.jsx(At,{size:13,className:"shrink-0 opacity-70"}),F=()=>{const G={...Se};delete G[B.tabKey],$e(G),H(null)};break;case"hideTab":O=t.jsx(Qi,{size:13,className:"shrink-0 opacity-70"}),F=()=>{ve(B.tabKey),H(null)};break}return t.jsxs("button",{className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${D.tone==="muted"?"text-text-muted":""}`,onClick:F,children:[O,t.jsx("span",{className:"flex-1 min-w-0",children:D.label}),D.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:D.shortcut}):null]},D.id)})}),B.sourceDocument.body),De&&pr.createPortal(t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>Oe(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:D=>D.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",Q?"⌘+1":"Ctrl+1",", ",Q?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Ct.body)]})}const Cl="adhdev-recent-launch-args-v1",ux=8;function mx(e){return String(e||"").trim().replace(/\s+/g," ")}function Il(e,s){return`${e.trim()}::${s.trim()}`}function Al(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Cl)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function px(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Cl,JSON.stringify(e))}catch{}}function Ml(e,s){var i;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((i=Al().byKey[Il(r,n)])==null?void 0:i.items)||[]}function Tl(e,s,r){var d;const n=String(e||"").trim(),a=String(s||"").trim(),i=mx(r);if(!n||!a||!i)return;const c=Al(),l=Il(n,a),u=((d=c.byKey[l])==null?void 0:d.items)||[],f=[i,...u.filter(x=>x!==i)].slice(0,ux);c.byKey[l]={items:f},px(c)}function fx(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 go(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 Ll(e){var a;const s=[],r=[],n=[];for(const i of e||[]){const c=String((i==null?void 0:i.lifecycle)||"").trim(),l=go((i==null?void 0:i.meta)||void 0),u=((a=i==null?void 0:i.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(c)?s.push(i):(c==="stopped"||c==="failed")&&(u||l)?r.push(i):n.push(i)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function Rl(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function $s(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function ea(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function hx(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Ai(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"unknown"}function Mi(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 xx(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function bx(e){switch(e){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-[#ffffff0a] text-text-muted"}}function gx(e){var r;const s=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const i=`${n.providerType}::${n.workspace}::${a}`;s.set(i,(s.get(i)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function yx({machineCards:e,conversations:s,ides:r,initialMachineId:n,sendDaemonCommand:a,onOpenConversation:i,onClose:c}){var U;const[l,u]=o.useState(n||((U=e[0])==null?void 0:U.id)||null),[f,d]=o.useState(""),[x,g]=o.useState(null),[w,M]=o.useState(!1);o.useEffect(()=>{var N;u(n||((N=e[0])==null?void 0:N.id)||null)},[n,e]);const m=o.useMemo(()=>e.find(N=>N.id===l)||e[0]||null,[l,e]),p=o.useMemo(()=>r.filter(N=>{if(N.type==="adhdev-daemon"||N.transport!=="pty")return!1;const $=hx(N.daemonId||N.id);return!!(m!=null&&m.id)&&$===m.id}),[m==null?void 0:m.id,r]),b=sl(m==null?void 0:m.id,{enabled:!!(m!=null&&m.id),includeSessions:!0,limit:6,intervalMs:1e4}),h=b.diagnostics,S=b.loading,R=b.applyDiagnostics,k=o.useMemo(()=>{const N=new Map;for(const $ of p){const z=s.find(q=>q.sessionId===$.sessionId||q.routeId===$.id);$.sessionId&&z&&N.set($.sessionId,z)}return N},[p,s]),I=o.useCallback(async()=>{if(m!=null&&m.id){M(!0);try{const N=await a(m.id,"session_host_get_diagnostics",{includeSessions:!0,limit:6}),$=ea(N);if(!($!=null&&$.success))throw new Error(($==null?void 0:$.error)||"Could not load hosted runtime diagnostics");R($.diagnostics||$.result||null),d("")}catch(N){const $=N instanceof Error?N.message:"Could not load hosted runtime diagnostics";d($)}finally{M(!1)}}},[m==null?void 0:m.id,R,a]);o.useEffect(()=>{!(m!=null&&m.id)||h||S||w||I()},[m==null?void 0:m.id,h,S,I,w]);const j=o.useCallback(async(N,$)=>{if(!(m!=null&&m.id)||N==="session_host_stop_session"&&!window.confirm(`Stop ${$.displayName}?
|
|
55
|
-
This will terminate the hosted runtime.`))return;const z=`${N}:${$.sessionId}`;g(z);try{const q=await a(m.id,N,{sessionId:$.sessionId}),W=ea(q);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Session host action failed");const ne=N==="session_host_resume_session"?"resumed":N==="session_host_restart_session"?"restarted":"stopped";st.showToast(`Session host ${ne}: ${$.displayName}`,"success"),await I()}catch(q){const W=q instanceof Error?q.message:"Session host action failed";d(W),st.showToast(W,"warning")}finally{g(q=>q===z?null:q)}},[m==null?void 0:m.id,I,a]),v=o.useCallback(async()=>{if(!(!(m!=null&&m.id)||!window.confirm(`Prune duplicate hosted runtimes?
|
|
56
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`))){g("session_host_prune_duplicate_sessions");try{const $=await a(m.id,"session_host_prune_duplicate_sessions",{}),z=ea($);if(!(z!=null&&z.success))throw new Error((z==null?void 0:z.error)||"Duplicate prune failed");const q=z.result||{},W=Array.isArray(q.prunedSessionIds)?q.prunedSessionIds.length:0,ne=typeof q.duplicateGroupCount=="number"?q.duplicateGroupCount:0;st.showToast(`Pruned ${W} duplicate runtime(s) across ${ne} group(s)`,"success"),await I()}catch($){const z=$ instanceof Error?$.message:"Duplicate prune failed";d(z),st.showToast(z,"warning")}finally{g($=>$==="session_host_prune_duplicate_sessions"?null:$)}}},[m==null?void 0:m.id,I,a]),y=o.useMemo(()=>[...(h==null?void 0:h.sessions)||[]].sort((N,$)=>($.lastActivityAt||0)-(N.lastActivityAt||0)),[h==null?void 0:h.sessions]),E=o.useMemo(()=>h!=null&&h.liveRuntimes||h!=null&&h.recoverySnapshots||h!=null&&h.inactiveRecords?{liveRuntimes:(h==null?void 0:h.liveRuntimes)||[],recoverySnapshots:(h==null?void 0:h.recoverySnapshots)||[],inactiveRecords:(h==null?void 0:h.inactiveRecords)||[]}:Ll(y),[h==null?void 0:h.inactiveRecords,h==null?void 0:h.liveRuntimes,h==null?void 0:h.recoverySnapshots,y]),L=E.liveRuntimes,A=E.recoverySnapshots,_=E.inactiveRecords,B=o.useMemo(()=>gx(L),[L]),H=o.useMemo(()=>[...(h==null?void 0:h.recentLogs)||[]].reverse().find(N=>N.level==="warn"||N.level==="error")||null,[h==null?void 0:h.recentLogs]),C=o.useMemo(()=>[...(h==null?void 0:h.recentTransitions)||[]].slice(-3).reverse(),[h==null?void 0:h.recentTransitions]),P=(N,$)=>{var J,ue;const z=k.get(N.sessionId),q=p.find(le=>le.sessionId===N.sessionId),W=x===`session_host_resume_session:${N.sessionId}`,ne=x===`session_host_restart_session:${N.sessionId}`,ae=x===`session_host_stop_session:${N.sessionId}`,ke=go(N.meta),X=typeof((J=N.meta)==null?void 0:J.runtimeRecoveryError)=="string"?String(N.meta.runtimeRecoveryError):"",pe=$==="recovery"?"Recover":"Resume",Y=Rl($);return t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-3.5",children:[t.jsx("div",{className:"flex items-start justify-between gap-3",children:t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("div",{className:"text-[14px] font-bold text-text-primary",children:N.displayName||(q==null?void 0:q.runtimeDisplayName)||(q==null?void 0:q.cliName)||N.providerType}),t.jsx("span",{className:`rounded-md px-2 py-0.5 text-[10px] font-semibold ${bx(N.lifecycle)}`,children:N.lifecycle}),ke&&t.jsx("span",{className:"rounded-md bg-sky-500/[0.08] px-2 py-0.5 text-[10px] font-semibold text-sky-300",children:ke})]}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:N.workspaceLabel||(q==null?void 0:q.runtimeWorkspaceLabel)||N.workspace||"No workspace"}),t.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-2 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-mono text-text-primary",children:N.runtimeKey}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:((ue=N.writeOwner)==null?void 0:ue.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:xx(N.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(Ea,{size:11})," ",N.attachedClients.length]})]}),t.jsxs("div",{className:"mt-1 text-[11px] text-text-secondary",children:["Active ",Mi(N.lastActivityAt),N.osPid?` · pid ${N.osPid}`:"",` · Next: ${Y}`]}),X&&t.jsx("div",{className:"mt-2 rounded-xl border border-red-500/[0.18] bg-red-500/[0.07] px-3 py-2 text-[11px] text-red-200",children:X})]})}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[z&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",onClick:()=>{i(z),c()},children:"Open chat"}),$==="recovery"&&(N.lifecycle==="interrupted"||N.lifecycle==="failed"||N.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!x,onClick:()=>{j("session_host_resume_session",N)},children:W?`${pe}ing…`:pe}),t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:!!x,onClick:()=>{j("session_host_restart_session",N)},children:ne?"Restarting…":"Restart"}),$==="live"&&(N.lifecycle==="running"||N.lifecycle==="starting"||N.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn border-red-500/20 px-2.5 py-1 text-[11px] text-red-300 hover:text-red-200",disabled:!!x,onClick:()=>{j("session_host_stop_session",N)},children:ae?"Stopping…":"Stop"})]})]},N.sessionId)};return t.jsx("div",{className:"fixed inset-0 z-[115] flex items-end justify-center bg-black/55 backdrop-blur-[2px] md:items-center md:p-4",onClick:c,children:t.jsxs("div",{className:"w-full max-h-[88vh] overflow-hidden rounded-t-[28px] border border-border-subtle bg-bg-primary shadow-[0_-20px_60px_rgba(0,0,0,0.35)] md:max-w-3xl md:rounded-[28px] md:shadow-[0_20px_60px_rgba(0,0,0,0.35)]",onClick:N=>N.stopPropagation(),children:[t.jsx("div",{className:"mx-auto mt-3 h-1.5 w-12 rounded-full bg-border-subtle"}),t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 pt-4 pb-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(Zt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"mt-1 text-[18px] font-black tracking-tight text-text-primary",children:(m==null?void 0:m.label)||"No machine selected"}),t.jsx("div",{className:"mt-1 text-[12px] text-text-secondary",children:"Live runtime status, next actions, and explicit recover/restart controls."})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:()=>{I()},disabled:S||w,"aria-label":"Refresh hosted runtime recovery",children:t.jsx(Gs,{size:16})}),t.jsx("button",{type:"button",className:"flex h-9 w-9 items-center justify-center rounded-full border border-border-subtle bg-bg-secondary text-text-secondary",onClick:c,"aria-label":"Close hosted runtime recovery",children:t.jsx(At,{size:16})})]})]}),e.length>1&&t.jsx("div",{className:"flex gap-2 overflow-x-auto px-5 pb-3 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:e.map(N=>t.jsx("button",{type:"button",className:`shrink-0 rounded-full border px-3 py-1.5 text-[12px] font-semibold transition-colors ${N.id===(m==null?void 0:m.id)?"border-accent-primary/40 bg-accent-primary/12 text-accent-primary":"border-border-subtle bg-bg-secondary text-text-secondary"}`,onClick:()=>u(N.id),children:N.label},N.id))}),t.jsxs("div",{className:"flex max-h-[calc(88vh-122px)] flex-col gap-3 overflow-y-auto px-5 pb-[calc(18px+env(safe-area-inset-bottom,0px))]",children:[f&&!h&&t.jsx("div",{className:"rounded-2xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-4 py-3 text-[12px] text-amber-100",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(ks,{size:14,className:"mt-0.5 shrink-0 text-amber-300"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"mt-1 text-amber-200/90",children:f})]})]})}),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:A.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:Mi(h.hostStartedAt)}),t.jsx("div",{className:"mt-0.5 text-[10px] text-text-secondary",children:Ai(h.hostStartedAt)})]})]}),H&&t.jsxs("div",{className:"rounded-2xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-4 py-3",children:[t.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.16em] text-amber-200",children:[t.jsx(ks,{size:13})," Latest warning"]}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-primary",children:H.message})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3 pt-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:[t.jsx(yn,{size:14})," Live hosted runtimes"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[B>0&&t.jsx("button",{type:"button",className:"machine-btn px-2.5 py-1 text-[11px]",disabled:x==="session_host_prune_duplicate_sessions",onClick:()=>{v()},children:x==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune ${B}`}),t.jsxs("div",{className:"text-[11px] text-text-secondary",children:[p.length," dashboard session",p.length===1?"":"s"]})]})]}),t.jsx("div",{className:"text-[11px] text-text-secondary leading-relaxed",children:$s("live")}),L.length===0?t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary px-4 py-4 text-[13px] text-text-secondary",children:"No live hosted CLI runtimes on this machine right now."}):t.jsx("div",{className:"space-y-2",children:L.map(N=>P(N,"live"))}),t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recovery snapshots"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:$s("recovery")}),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 recovery snapshots need attention."}):t.jsx("div",{className:"space-y-2",children:A.map(N=>P(N,"recovery"))})]}),_.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Inactive records"}),t.jsx("div",{className:"mb-2 text-[11px] text-text-secondary leading-relaxed",children:$s("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:_.map(N=>P(N,"inactive"))})]}),C.length>0&&t.jsxs("div",{className:"pb-1",children:[t.jsx("div",{className:"mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.18em] text-text-secondary",children:"Recent activity"}),t.jsx("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary divide-y divide-border-subtle",children:C.map(N=>{const $=y.find(z=>z.sessionId===N.sessionId);return t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-2.5",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[12px] font-semibold text-text-primary",children:($==null?void 0:$.displayName)||N.sessionId}),t.jsxs("div",{className:"mt-0.5 text-[11px] leading-relaxed text-text-secondary",children:[N.action,N.lifecycle?` · ${N.lifecycle}`:"",N.detail?` · ${N.detail}`:"",N.error?` · ${N.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${N.success===!1?"text-red-300":"text-text-secondary"}`,children:Ai(N.timestamp)})]},`${N.sessionId}:${N.timestamp}:${N.action}`)})})]})]})]})]})})}function _l(e){return!e.hasLoadedInitialResults&&!e.isLoading}function or({title:e,description:s,action:r,children:n,className:a="",contentClassName:i=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),s&&t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:s})]}),r?t.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?t.jsx("div",{className:s||r?`mt-3 ${i}`.trim():i,children:n}):null]})}function Pl({busy:e,savedSessionsLoading:s,savedSessionsError:r,selectedSession:n,onRefresh:a,onOpenHistory:i,onClearSelection:c}){const l=n?hl(n):null;return t.jsxs(or,{title:"Saved history",description:Za(),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:Np()})]}),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 ta(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 Xr(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function vx({machines:e,conversations:s,ides:r,onClose:n,onBrowseDirectory:a,onSaveWorkspace:i,onLaunchIde:c,onLaunchProvider:l,onListSavedSessions:u,sendDaemonCommand:f,onOpenConversation:d}){var Ct,Dt;const x=Nr(),g=o.useMemo(()=>[...e].sort(Fa),[e]),[w,M]=o.useState(((Ct=g[0])==null?void 0:Ct.id)||""),m=o.useMemo(()=>g.find(Z=>Z.id===w)||g[0],[w,g]),p=o.useMemo(()=>((m==null?void 0:m.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[m]),b=(m==null?void 0:m.defaultWorkspaceId)||null,[h,S]=o.useState(""),[R,k]=o.useState(""),[I,j]=o.useState(ta(g[0])),[v,y]=o.useState(""),[E,L]=o.useState(""),[A,_]=o.useState([]),[B,H]=o.useState(""),[C,P]=o.useState([]),[U,N]=o.useState(!1),[$,z]=o.useState(!1),[q,W]=o.useState(""),[ne,ae]=o.useState(!1),[ke,X]=o.useState(()=>wt()),[pe,Y]=o.useState(!1),[J,ue]=o.useState(null),[le,V]=o.useState(!1),[ve,ie]=o.useState(""),[ce,te]=o.useState(!1),[me,re]=o.useState(""),[je,we]=o.useState([]),[Te,T]=o.useState(!1),[fe,be]=o.useState(""),[Q,Se]=o.useState(!1),De=o.useRef(null),Oe=o.useRef(0);o.useEffect(()=>{var Z;!w&&((Z=g[0])!=null&&Z.id)&&M(g[0].id)},[w,g]),o.useEffect(()=>{!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||x(m.id,{minFreshMs:3e4}).catch(()=>{})},[x,m]);const $e=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(Z=>Z.category==="cli"&&Z.installed!==!1),[m]),Ue=o.useMemo(()=>((m==null?void 0:m.availableProviders)||[]).filter(Z=>Z.category==="acp"&&Z.installed!==!1),[m]),ze=o.useMemo(()=>((m==null?void 0:m.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[m]),mt=o.useMemo(()=>I==="cli"?$e.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):I==="acp"?Ue.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):ze,[Ue,I,$e,ze]);o.useEffect(()=>{var Ke;if(!m)return;if(De.current!==m.id){De.current=m.id,S(b||((Ke=p[0])==null?void 0:Ke.id)||"__home__"),k(""),j(ta(m)),y(""),L(""),H(""),P([]),z(!1),W(""),X(wt()),ie("");return}S(D=>{var O;return D==="__custom__"||D==="__home__"||p.some(F=>F.id===D)?D:b||((O=p[0])==null?void 0:O.id)||"__home__"}),j(D=>D==="ide"&&ze.length>0||D==="cli"&&$e.length>0||D==="acp"&&Ue.length>0?D:ta(m))},[Ue.length,$e.length,b,ze.length,m,p]),o.useEffect(()=>{var Z;I&&(mt.some(Ke=>Ke.id===v)||y(((Z=mt[0])==null?void 0:Z.id)||""))},[I,mt,v]);const it=o.useCallback(async(Z,Ke)=>{const D=Oe.current+1;return Oe.current=D,N(!0),W(""),u(Z,Ke).then(O=>{Oe.current===D&&P(O)}).catch(O=>{Oe.current===D&&(P([]),W(O instanceof Error?O.message:"Could not load saved sessions"))}).finally(()=>{Oe.current===D&&(N(!1),z(!0))})},[u]),xt=o.useCallback((Z,Ke)=>{_(Ml(Z,Ke))},[]);o.useEffect(()=>{Oe.current+=1,H(""),X(wt()),!m||!v||I==="ide"?_([]):xt(m.id,v),z(!1),P([]),W(""),N(!1)},[I,xt,it,m,v]),o.useEffect(()=>{if(!B)return;const Z=C.find(Ke=>Ke.providerSessionId===B);Z!=null&&Z.canResume||H("")},[C,B]);const Ve=h==="__custom__"?R.trim():h==="__home__"?"":((Dt=p.find(Z=>Z.id===h))==null?void 0:Dt.path)||"",pt=o.useMemo(()=>m?r.filter(Z=>Z.id!==m.id&&Z.daemonId===m.id).map(Z=>Z.workspace):[],[r,m]),bt=o.useMemo(()=>((m==null?void 0:m.recentLaunches)||[]).map(Z=>Z.workspace),[m]),ct=o.useCallback(Z=>{const Ke=String(Z.workspace||"").trim();if(!Ke)return;const D=p.find(O=>Xr(O.path)===Xr(Ke));if(D){S(D.id),k("");return}S("__custom__"),k(Ke)},[p]),Me=o.useCallback(Z=>{const Ke=String(Z.workspace||"").trim();if(!Ke)return{workspaceId:null,workspacePath:null};const D=p.find(O=>Xr(O.path)===Xr(Ke));return D?{workspaceId:D.id,workspacePath:null}:{workspaceId:null,workspacePath:Ke}},[p]),Je=o.useMemo(()=>C.find(Z=>Z.providerSessionId===B)||null,[C,B]),Ye=o.useMemo(()=>{var Ke;if(I!=="cli"||!m||!v)return null;const Z=((Ke=$e.find(D=>D.type===v))==null?void 0:Ke.displayName)||v;return{routeId:m.id,daemonId:m.id,providerSessionId:B||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:v,status:"idle",title:Z,messages:[],ideType:v,workspaceName:Ve,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${m.id}:${v}`,machineName:_t(m,{fallbackId:m.id})}},[I,$e,Ve,m,B,v]),Fe=o.useCallback(()=>{var Ke;if(!m)return;S("__custom__"),te(!0),be("");const Z=Cn(m.platform,Nn(R.trim(),Ve,pt,bt,m.defaultWorkspacePath,(Ke=p.find(D=>D.id===b))==null?void 0:Ke.path,p.map(D=>D.path)));T(!0),a(m.id,Z).then(D=>{re(D.path),k(D.path),we(D.directories)}).catch(D=>{be(D instanceof Error?D.message:"Could not load folder")}).finally(()=>T(!1))},[R,b,bt,pt,a,Ve,m,p]),dt=o.useCallback(Z=>{m&&(T(!0),be(""),a(m.id,Z).then(Ke=>{re(Ke.path),k(Ke.path),we(Ke.directories)}).catch(Ke=>{be(Ke instanceof Error?Ke.message:"Could not load folder")}).finally(()=>T(!1)))},[a,m]),vt=o.useCallback(async()=>{if(!m||!Ve)return;Se(!0),ie("");const Z=await i(m.id,Ve);if(Se(!1),!Z.ok){ie(Z.error||"Could not save workspace");return}ie("Workspace saved. It will appear in the list once the machine state refreshes.")},[i,Ve,m]),jt=o.useCallback(async()=>{if(!m||!I||!v)return;V(!0),ie("");const Z=E.trim()?E.trim().split(/\s+/).filter(Boolean):[],Ke=I==="ide"?await c(m.id,v,{workspacePath:Ve||null}):await l(m.id,I,v,{workspaceId:h!=="__home__"&&h!=="__custom__"?h:null,workspacePath:h==="__custom__"&&Ve||null,resumeSessionId:I==="cli"&&B?B:null,cliArgs:Z});if(V(!1),!Ke.ok){ie(Ke.error||"Could not start session");return}I!=="ide"&&E.trim()&&(Tl(m.id,v,E),xt(m.id,v)),n()},[I,E,xt,n,c,l,Ve,m,B,v,h]),Lt=I?Oc(I,I==="cli"&&!!B):"Start",Mt=I?Wc(I,I==="cli"&&!!B):"Starting…";return m?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"dashboard-new-title",children:t.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start or recover session"}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:"Pick a machine and workspace, then choose whether to start fresh, resume saved history, or recover a hosted runtime."})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:n,"aria-label":"Close new session dialog",children:t.jsx(At,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[t.jsx(or,{title:"Machine",children:t.jsx("select",{value:m.id,onChange:Z=>M(Z.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:le,children:g.map(Z=>t.jsx("option",{value:Z.id,children:_t(Z,{fallbackId:Z.id})},Z.id))})}),I==="cli"&&t.jsx(or,{title:"Hosted runtimes",description:"Review live runtimes, recovery snapshots, and recover or restart options without leaving this launch flow.",action:t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:le||!m,onClick:()=>Y(!0),children:[t.jsx(Zt,{size:14}),kp()]})}),t.jsxs(or,{title:"Workspace",description:"Saved workspace is preferred. Home and custom folders are still available.",action:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Fe,disabled:le,children:"Browse…"}),children:[t.jsxs("select",{value:h,onChange:Z=>{const Ke=Z.target.value;S(Ke),Ke==="__custom__"?Fe():ie("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:le,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),p.map(Z=>t.jsxs("option",{value:Z.id,children:[Z.id===b?"⭐ ":"",kn(Z.path,Z.label)||Z.path]},Z.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.":Ve||"Select a workspace folder."}),h==="__custom__"&&Ve&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Fe,disabled:le,children:[t.jsx(Bs,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:vt,disabled:le||Q,children:Q?"Saving…":"Save workspace"})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:"CLI",enabled:$e.length>0},{id:"ide",label:"IDE",enabled:ze.length>0},{id:"acp",label:"ACP",enabled:Ue.length>0}].map(Z=>t.jsx("button",{type:"button",className:`btn btn-sm ${I===Z.id?"btn-primary":"btn-secondary"}`,onClick:()=>j(Z.id),disabled:!Z.enabled||le,children:Z.label},Z.id))})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[mt.map(Z=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${v===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>y(Z.id),disabled:le,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.meta})]},Z.id)),mt.length===0&&t.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),I!=="ide"&&t.jsxs(or,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:E,onChange:Z=>L(Z.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:le}),A.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:A.map(Z=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>L(Z),disabled:le,title:Z,children:Z},Z))})]}),I==="cli"&&t.jsx(Pl,{busy:le,savedSessionsLoading:U,savedSessionsError:q,selectedSession:Je,onRefresh:()=>{!m||!v||it(m.id,v)},onOpenHistory:()=>{!m||!v||(ae(!0),_l({hasLoadedInitialResults:$,isLoading:U})&&it(m.id,v))},onClearSelection:()=>H("")}),ve&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ve.includes("saved")||ve.includes("requested")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:ve})]}),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:le,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:jt,disabled:le||!I||!v||h==="__custom__"&&!Ve,children:[t.jsx(Ka,{size:14}),le?Mt:Lt]})]})]})}),ce&&t.jsx(An,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:me,directories:je,busy:Te,error:fe,onClose:()=>te(!1),onNavigate:dt,onConfirm:Z=>{k(Z),re(Z),S("__custom__"),te(!1)}}),ne&&Ye&&t.jsx(so,{activeConv:Ye,ides:[],isCreatingChat:!1,isRefreshingHistory:U,savedSessions:C,isSavedSessionsLoading:U,isResumingSavedSessionId:J,savedHistoryFilters:ke,onSavedHistoryFiltersChange:X,onClose:()=>ae(!1),onNewChat:()=>{H(""),ae(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!m||!v||it(m.id,v)},onResumeSavedSession:Z=>{if(!m||!v||J||!Z.canResume)return;const Ke=Me(Z);H(Z.providerSessionId),ct(Z),ue(Z.providerSessionId),ae(!1),V(!0),ie(""),l(m.id,"cli",v,{workspaceId:Ke.workspaceId,workspacePath:Ke.workspacePath,resumeSessionId:Z.providerSessionId}).then(D=>{if(!D.ok){ie(D.error||"Could not resume session");return}n()}).finally(()=>{V(!1),ue(D=>D===Z.providerSessionId?null:D)})}}),pe&&m&&t.jsx(yx,{machineCards:[{id:m.id,label:_t(m,{fallbackId:m.id}),subtitle:[m.platform||"machine",bl(m)].filter(Boolean).join(" · "),unread:0,total:0,latestConversation:null,preview:""}],conversations:s,ides:r,initialMachineId:m.id,sendDaemonCommand:f,onOpenConversation:Z=>{Y(!1),n(),d(Z)},onClose:()=>Y(!1)})]}):null}function wx(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 jx(e){return e instanceof Error?e.message:String(e||"")}function kx(e){const s=jx(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Sx({showMobileChatMode:e,isMobile:s,activeConv:r,chatIdes:n,wsStatus:a,isConnected:i,onOpenHistory:c,onOpenRemote:l,onStopCli:u,activeCliViewMode:f,onSetActiveCliViewMode:d,mobileChatConversations:x,hiddenConversations:g,ides:w,actionLogs:M,sendDaemonCommand:m,setLocalUserMessages:p,setActionLogs:b,isStandalone:h,initialDataLoaded:S,userName:R,requestedMobileTabKey:k,onRequestedMobileTabConsumed:I,requestedMachineId:j,onRequestedMachineConsumed:v,requestedMobileSection:y,onRequestedMobileSectionConsumed:E,containerRef:L,isSplitMode:A,numGroups:_,groupSizes:B,groupedConvs:H,clearedTabs:C,focusedGroup:P,setFocusedGroup:U,moveTabToGroup:N,splitTabRelative:$,closeGroup:z,handleResizeStart:q,groupActiveTabIds:W,setGroupActiveTabIds:ne,groupTabOrders:ae,setGroupTabOrders:ke,toggleHiddenTab:X,visibleConversations:pe,requestedDesktopTabKey:Y,onRequestedDesktopTabConsumed:J,onDesktopActiveTabChange:ue,onHideConversation:le,onShowHiddenConversation:V,onShowAllHiddenConversations:ve,scrollToBottomRequest:ie,machineEntries:ce,onBrowseMachineDirectory:te,onSaveMachineWorkspace:me,onLaunchMachineIde:re,onLaunchMachineProvider:je,onListMachineSavedSessions:we,notifications:Te,notificationUnreadCount:T,notificationStateBySessionId:fe,liveSessionInboxState:be,onMarkNotificationRead:Q,onMarkNotificationUnread:Se,onDeleteNotification:De,onMarkNotificationTargetRead:Oe}){const $e=at.useRef(null),[Ue,ze]=at.useState(!1),[mt,it]=at.useState(!1),[xt,Ve]=at.useState(!1),[pt,bt]=at.useState(!1),ct=at.useCallback(se=>{var Ne;pr.flushSync(()=>{V(se)}),(Ne=$e.current)==null||Ne.restoreHiddenTabToSavedLocation(se.tabKey)},[V]),Me=at.useCallback(se=>{var _e;const Ne=x.find(rt=>xr(rt,se))||g.find(rt=>xr(rt,se));Ne&&(g.some(rt=>rt.tabKey===Ne.tabKey)&&ct(Ne),ue(Ne.tabKey),(_e=$e.current)==null||_e.activateConversationTab(Ne.tabKey)),Q(se.id),(se.sessionId||se.providerSessionId||se.tabKey||se.routeId)&&Oe({sessionId:se.sessionId,providerSessionId:se.providerSessionId,tabKey:se.tabKey,routeId:se.routeId}),ze(!1)},[ct,g,x,ue,Q,Oe]),[Je,Ye]=at.useState(!1),[Fe,dt]=at.useState("quickstart"),[vt,jt]=at.useState("workspace"),Lt=!e&&!s,Mt=at.useCallback(se=>{ze(se),se&&it(!1)},[]),Ct=at.useCallback(se=>{it(se),se&&ze(!1)},[]),Dt=at.useCallback(()=>{var Ne;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Ne=$e.current)==null||Ne.resetAllPanelsToMain(),it(!1))},[]),Z=at.useCallback(()=>{dt(pe.length===0?"quickstart":"shortcuts"),jt("workspace"),Ve(!0),ze(!1),it(!1)},[pe.length]),Ke=at.useCallback(async se=>{var ee;if(!r)return;const Ne=(ee=r.modalButtons)==null?void 0:ee[se];if(!Ne)return;const _e=yr(r);if(!_e)return;const rt=Ne.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),K=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(rt);try{await m(_e,"resolve_action",{button:Ne,action:K?"approve":"reject",buttonIndex:se,...Es(r)})}catch(xe){kx(xe)||console.error("[Shortcut approval] Failed:",xe)}},[r,m]),{isMac:D,actionDefinitions:O,actionShortcuts:F,shortcutListening:G,shortcutListeningDraft:oe,setShortcutListening:Ie,setShortcutListeningDraft:Le,saveShortcuts:Ae}=ex({enabled:Lt&&!xt,onTrigger:se=>{var Ne,_e,rt,K,ee,xe,Ee,Re,Ce,et,It,Pe,qt,Ar,Ys,Xs;if(se==="openShortcutHelp"){Z();return}if(se==="hideCurrentTab"){r&&le(r);return}if(se==="toggleHiddenTabs"){Ct(!mt);return}if(se==="openHistoryForActiveTab"){r&&!Qe(r)&&c(r);return}if(se==="openRemoteForActiveTab"){r&&!tt(r)&&!Qe(r)&&l(r);return}if(se==="splitActiveTabRight"){(Ne=$e.current)==null||Ne.splitActiveTabRight();return}if(se==="splitActiveTabDown"){(_e=$e.current)==null||_e.splitActiveTabDown();return}if(se==="floatActiveTab"){(rt=$e.current)==null||rt.floatActiveTab();return}if(se==="popoutActiveTab"){(K=$e.current)==null||K.popoutActiveTab();return}if(se==="dockActiveTab"){(ee=$e.current)==null||ee.dockActiveTab();return}if(se==="focusLeftPane"){(xe=$e.current)==null||xe.focusLeftPane();return}if(se==="focusRightPane"){(Ee=$e.current)==null||Ee.focusRightPane();return}if(se==="focusUpPane"){(Re=$e.current)==null||Re.focusUpPane();return}if(se==="focusDownPane"){(Ce=$e.current)==null||Ce.focusDownPane();return}if(se==="moveActiveTabToLeftPane"){(et=$e.current)==null||et.moveActiveTabToLeftPane();return}if(se==="moveActiveTabToRightPane"){(It=$e.current)==null||It.moveActiveTabToRightPane();return}if(se==="moveActiveTabToUpPane"){(Pe=$e.current)==null||Pe.moveActiveTabToUpPane();return}if(se==="moveActiveTabToDownPane"){(qt=$e.current)==null||qt.moveActiveTabToDownPane();return}if(se==="triggerPrimaryApprovalAction"){Ke(0);return}if(se==="triggerSecondaryApprovalAction"){Ke(1);return}if(se==="triggerTertiaryApprovalAction"){Ke(2);return}if(se==="setActiveTabShortcut"){(Ar=$e.current)==null||Ar.setShortcutForActiveTab();return}if(se==="selectPreviousGroupTab"){(Ys=$e.current)==null||Ys.activatePreviousTabInGroup();return}if(se==="selectNextGroupTab"){(Xs=$e.current)==null||Xs.activateNextTabInGroup();return}!r||!tt(r)||Qe(r)||se==="toggleCliView"&&d(f==="chat"?"terminal":"chat")}}),We=at.useCallback(()=>{Ve(!1),Ie(null),Le([])},[Ie,Le]),Be=at.useMemo(()=>vt==="all"?O:O.filter(se=>wx(se)===vt),[O,vt]),Ge=at.useCallback(()=>{const se=Object.fromEntries(O.map(Ne=>[Ne.id,""]));Ae(se)},[O,Ae]),Ze=at.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const se=Object.fromEntries(O.map(Ne=>[Ne.id,Ne.defaultShortcut]));Ae(se)},[O,Ae]);return at.useEffect(()=>{const se=Ne=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Ne.metaKey&&Ne.key.toLowerCase()==="w":Ne.ctrlKey&&Ne.key.toLowerCase()==="w")&&(Ne.preventDefault(),r&&le&&le(r))};return window.addEventListener("keydown",se),()=>window.removeEventListener("keydown",se)},[r,le]),at.useEffect(()=>{if(!xt||G)return;const se=Ne=>{Ne.key==="Escape"&&(Ne.preventDefault(),We())};return window.addEventListener("keydown",se,!0),()=>window.removeEventListener("keydown",se,!0)},[We,xt,G]),at.useEffect(()=>{if(!Lt){Ye(!1);return}Ye(!0);const se=window.setTimeout(()=>{Ye(!1)},1e4);return()=>window.clearTimeout(se)},[Lt]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(gp,{activeConv:r,agentCount:n.length,wsStatus:a,isConnected:i,conversations:pe,hiddenConversations:g,onOpenHistory:c,onHideConversation:le,onShowConversation:ct,onShowAllHidden:ve,onResetPanelsToMain:Dt,notifications:Te,notificationUnreadCount:T,onOpenNotification:Me,onMarkNotificationRead:Q,onMarkNotificationUnread:Se,onDeleteNotification:De,inboxOpen:Ue,onInboxOpenChange:Mt,hiddenOpen:mt,onHiddenOpenChange:Ct,onOpenNewSession:s?void 0:()=>bt(!0),actionShortcuts:F,onOpenRemote:()=>{!r||tt(r)||Qe(r)||l(r)},onStopCli:u,activeCliViewMode:f,onSetCliViewMode:d}),e?t.jsx(Hh,{conversations:x,hiddenConversations:g,ides:w,actionLogs:M,sendDaemonCommand:m,setLocalUserMessages:p,setActionLogs:b,isStandalone:h,userName:R,requestedActiveTabKey:k,onRequestedActiveTabConsumed:I,requestedMachineId:j,onRequestedMachineConsumed:v,requestedMobileSection:y,onRequestedMobileSectionConsumed:E,onOpenHistory:c,onOpenRemote:l,onStopCli:u,wsStatus:a,isConnected:i,onShowHiddenConversation:ct,onShowAllHiddenConversations:ve,onOpenNewSession:()=>bt(!0),notificationStateBySessionId:fe,liveSessionInboxState:be,onMarkNotificationTargetRead:Oe}):s?t.jsx(Xh,{containerRef:L,isSplitMode:A,numGroups:_,groupSizes:B,groupedConvs:H,clearedTabs:C,ides:w,actionLogs:M,sendDaemonCommand:m,setLocalUserMessages:p,setActionLogs:b,isStandalone:h,hasRegisteredMachines:ce.length>0,userName:R,focusedGroup:P,setFocusedGroup:U,moveTabToGroup:N,splitTabRelative:$,closeGroup:z,handleResizeStart:q,groupActiveTabIds:W,setGroupActiveTabIds:ne,groupTabOrders:ae,setGroupTabOrders:ke,toggleHiddenTab:X,allowTabShortcuts:!1,notificationStateBySessionId:fe,liveSessionInboxState:be}):t.jsx(dx,{visibleConversations:pe,clearedTabs:C,ides:w,actionLogs:M,sendDaemonCommand:m,setLocalUserMessages:p,setActionLogs:b,isStandalone:h,hasRegisteredMachines:ce.length>0,initialDataLoaded:S,userName:R,toggleHiddenTab:X,actionShortcuts:F,registerActionHandlers:se=>{$e.current=se},notificationStateBySessionId:fe,liveSessionInboxState:be,onActiveTabChange:ue,requestedActiveTabKey:Y,onRequestedActiveTabConsumed:J,scrollToBottomRequest:ie}),pt&&t.jsx(vx,{machines:ce,conversations:x,ides:w,onClose:()=>bt(!1),onBrowseDirectory:te,onSaveWorkspace:me,onLaunchIde:re,onLaunchProvider:je,onListSavedSessions:we,sendDaemonCommand:m,onOpenConversation:se=>{bt(!1),V(se),ue(se.tabKey)}}),xt&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:We,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:se=>se.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:We,"aria-label":"Close dashboard guide",children:t.jsx(At,{size:14})})]}),t.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(se=>t.jsx("button",{type:"button",className:`btn btn-sm ${Fe===se.id?"btn-primary":"btn-secondary"}`,onClick:()=>dt(se.id),children:se.label},se.id))}),Fe==="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 ",D?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),Fe==="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."]})]})]})]}),Fe==="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(se=>t.jsx("button",{type:"button",className:`btn btn-sm ${vt===se.id?"btn-primary":"btn-secondary"}`,onClick:()=>jt(se.id),children:se.label},se.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ge,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:Ze,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:Be.map(se=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${G===se.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:se.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:se.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:se.defaultShortcut})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-bg-tertiary border border-border-subtle min-w-[72px] text-center",children:G===se.id?oe.length>0?`${oe.join(" ")} ...`:"Listening...":F[se.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Ie(se.id),Le([])},children:G===se.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Ne={...F};Ne[se.id]="",Ae(Ne)},children:"Disable"})]})]})},se.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",D?"⌥S":"Ctrl+Alt+S",". Press Esc to stop listening."]})]})]})}),!e&&t.jsxs("button",{type:"button",onClick:Z,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 ${Je?"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:"?"}),Je&&t.jsx("span",{children:"Guide"})]})]})}const sa=[{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 Nx({onClose:e}){const[s,r]=o.useState(0),n=sa[s],a=s===sa.length-1;return t.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:i=>{i.stopPropagation()},children:[t.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[t.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:t.jsx(At,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:sa.map((i,c)=>t.jsx("div",{style:{width:c===s?24:8,height:8,borderRadius:4,background:c===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},c))}),t.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),t.jsxs("div",{style:{textAlign:"center"},children:[t.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[t.jsx("span",{children:n.icon})," ",n.title]}),t.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&t.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[t.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&t.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),t.jsx("div",{className:"flex justify-end items-center mt-6",children:t.jsx("button",{onClick:()=>a?e():r(i=>i+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),t.jsx("style",{children:`
|
|
57
|
-
@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 Cx({hasExtensions:e,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?t.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[t.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${r==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:s}),n.map(i=>{const c=r===i.tabKey,l=i.status==="waiting_approval",u=i.status==="generating";return t.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${c?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(i.tabKey),children:[t.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:l?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),i.title,l&&t.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},i.tabKey)})]}):null}function Ix({ideData:e,allIdes:s,connectionStates:r,localUserMessages:n,ideName:a,preferredTabKey:i}){const[c,l]=o.useState(()=>i||"native"),u=o.useMemo(()=>Fc(s),[s]),f=o.useMemo(()=>e?ro(e,n,{machineNames:u,connectionStates:r,defaultConnectionState:"new"}):[],[e,n,u,r]),d=o.useMemo(()=>f.find(p=>p.streamSource==="native"),[f]),x=o.useMemo(()=>f.filter(p=>p.streamSource==="agent-stream"),[f]),g=o.useMemo(()=>e?Ht(f,e.id):null,[f,e]);o.useEffect(()=>{i&&l(i)},[i]),o.useEffect(()=>{if(i||!g)return;const p=g.streamSource==="native"?"native":g.tabKey;!p||c===p||c==="native"&&l(p)},[c,g,i]),o.useEffect(()=>{var p;c!=="native"&&(x.some(b=>b.tabKey===c)||l(((p=x[0])==null?void 0:p.tabKey)||"native"))},[c,x]),o.useEffect(()=>{c==="native"&&(d||x[0]&&l(x[0].tabKey))},[c,d,x]);const w=o.useMemo(()=>c==="native"&&d?d:x.find(p=>p.tabKey===c)||g||d||x[0],[c,d,g,x]),M=o.useMemo(()=>x.map(p=>({tabKey:p.tabKey,title:$c(p)||a,status:p.status})),[x,a]),m=o.useCallback(p=>{if(p)return f.find(b=>xr(b,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[f]);return{activeChatTab:c,setActiveChatTab:l,activeConv:w,conversations:f,extensionTabs:M,hasExtensions:M.length>0,resolveConversationByTarget:m}}function Ax({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,localUserMessages:i,sendDaemonCommand:c,setLocalUserMessages:l,setActionLogs:u,isStandalone:f,userName:d,onOpenHistory:x,onConversationChange:g,onClose:w}){const[M,m]=o.useState("split"),[p,b]=o.useState(()=>ns(e)?"native":e.tabKey),h=o.useRef(null),S=o.useMemo(()=>s||r.find(N=>N.id===e.routeId),[e.routeId,s,r]),R=o.useMemo(()=>ot((S==null?void 0:S.type)||""),[S==null?void 0:S.type]),{conversations:k,extensionTabs:I,hasExtensions:j}=Ix({ideData:S,allIdes:r,connectionStates:n,localUserMessages:i,ideName:R||"IDE",preferredTabKey:ns(e)?void 0:e.tabKey}),v=o.useMemo(()=>S?Ht(k,S.id):null,[S,k]);o.useEffect(()=>{const N=h.current,$={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(h.current=$,!(N&&N.routeId===$.routeId&&N.tabKey===$.tabKey&&N.streamSource===$.streamSource)){if(ns(e)){b("native");return}b(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),o.useEffect(()=>{if(p==="native"){if(k.some(N=>N.streamSource==="native"))return;(v==null?void 0:v.streamSource)==="agent-stream"&&b(v.tabKey);return}if(!k.some(N=>N.tabKey===p)){if((v==null?void 0:v.streamSource)==="agent-stream"){b(v.tabKey);return}b("native")}},[k,p,v]);const y=o.useMemo(()=>p==="native"?k.find(N=>N.streamSource==="native")||e:k.find(N=>N.tabKey===p)||e,[e,k,p]),E=rl(y),L=o.useMemo(()=>E.status||E.modalMessage||E.modalButtons?{...y,...E.status?{status:E.status}:{},...E.modalMessage!==void 0?{modalMessage:E.modalMessage}:{},...E.modalButtons!==void 0?{modalButtons:E.modalButtons}:{}}:y,[y,E]),A=Sr(L),_=Sn({sendDaemonCommand:c,activeConv:L,setLocalUserMessages:l,setActionLogs:u,isStandalone:f}),{connScreenshot:B,screenshotUsage:H,handleRemoteAction:C}=wl({doId:A,targetSessionId:wc(L),connState:L.connectionState||"new",viewMode:M}),P=o.useMemo(()=>a.filter(N=>N.routeId===L.tabKey),[a,L.tabKey]);o.useEffect(()=>{g==null||g(L)},[L,g]),o.useEffect(()=>{const N=$=>{$.key==="Escape"&&w()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[w]);const U=o.useCallback(N=>{N.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:w,children:t.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:U,children:[t.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[t.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[t.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(Pt,{size:16})}),t.jsx("span",{className:"truncate",children:Va(y)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:w,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(N=>{const $=M===N;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${$?"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:()=>m(N),title:N==="split"?"Split view":"Remote only",children:N==="split"?t.jsx(Ud,{size:15}):t.jsx(Pt,{size:15})},N)})}),t.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),t.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>x(y),title:"Chat History",children:[t.jsx($a,{size:14,className:"md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"History"})]}),t.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:w,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${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(Cx,{hasExtensions:j,ideName:R||"IDE",activeChatTab:p,extensionTabs:I,onSelectTab:b}),t.jsx(ic,{activeConv:L,onModalButton:_.handleModalButton}),t.jsx(ja,{activeConv:L,ideEntry:S,showMetaChips:!1,handleSendChat:_.handleSendChat,isSendingChat:_.isSendingChat,sendFeedbackMessage:_.sendFeedbackMessage,handleFocusAgent:_.handleFocusAgent,isFocusingAgent:_.isFocusingAgent,actionLogs:P,userName:d})]}),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(rc,{addLog:()=>{},connState:L.connectionState||"new",connScreenshot:B,screenshotUsage:H,transportType:L.transport,onAction:C})})]})]})})}function Mx({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const i=fp(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 Tx({historyModalOpen:e,historyTargetConv:s,ides:r,isHistoryCreatingChat:n,isHistoryRefreshingHistory:a,savedHistorySessions:i,isSavedHistoryLoading:c,isResumingSavedHistorySessionId:l,onCloseHistory:u,onNewHistoryChat:f,onSwitchHistorySession:d,onRefreshHistory:x,onResumeSavedHistorySession:g,remoteDialogConv:w,remoteDialogIdeEntry:M,connectionStates:m,actionLogs:p,localUserMessages:b,sendDaemonCommand:h,setLocalUserMessages:S,setActionLogs:R,isStandalone:k,userName:I,onOpenRemoteHistory:j,onRemoteConversationChange:v,onCloseRemoteDialog:y,cliStopDialogOpen:E,cliStopTargetConv:L,onCancelCliStop:A,onStopCliNow:_,onSaveCliAndStop:B,toasts:H,onDismissToast:C,onClickToast:P,showOnboarding:U,onCloseOnboarding:N}){var q;const[$,z]=at.useState(()=>wt());return t.jsxs(t.Fragment,{children:[e&&s&&t.jsx(so,{activeConv:s,ides:r,isCreatingChat:n,isRefreshingHistory:a,savedSessions:i,isSavedSessionsLoading:c,isResumingSavedSessionId:l,savedHistoryFilters:$,onSavedHistoryFiltersChange:z,onClose:u,onNewChat:f,onSwitchSession:d,onRefreshHistory:x,onResumeSavedSession:g}),w&&t.jsx(Ax,{activeConv:w,ideEntry:M,ides:r,connectionStates:m,actionLogs:p,localUserMessages:b,sendDaemonCommand:h,setLocalUserMessages:S,setActionLogs:R,isStandalone:k,userName:I,onOpenHistory:j,onConversationChange:v,onClose:y}),E&&L&&(tt(L)||Qe(L))&&t.jsx(Mx,{activeConv:L,canSaveAndStop:tt(L)&&!Qe(L)&&!!((q=L.resume)!=null&&q.supported),onCancel:A,onStopNow:_,onSaveAndStop:B}),t.jsx(Hc,{toasts:H,onDismiss:C,onClickToast:P}),U&&t.jsx(Nx,{onClose:N})]})}function Lx({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:i}){return e.length===0?null:t.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:r?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:r?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[t.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:t.jsx(Gs,{size:14})}),t.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[t.jsxs("span",{children:[r?"Daemon update required":"Update available",s?t.jsxs(t.Fragment,{children:[": ",t.jsxs("strong",{children:["v",s]})]}):null]}),e.map(c=>{const l=_t(c,{fallbackId:c.id}),u=n[c.id],f=c.version||c.daemonVersion||"unknown",d=c.versionUpdateRequired===!0;return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:l}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",f]}),d&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:"retry"}):t.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:d?"Update now":"Upgrade"})]},c.id)})]}),!r&&t.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:i,title:"Dismiss",children:t.jsx(At,{size:16})})]})}function Rx(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function _x(e){const s=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?s===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:r===e.autoReadKey?r:null}:r===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:r}:{shouldSchedule:!0,shouldCancelPending:r!==null&&r!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!r,nextPendingKey:null}}function Px(e){const s=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,i=[e.tabKey,e.historySessionId||"",s,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&s&&s!==r),autoReadKey:i,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Dx(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Ti(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ex(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function $x(){var No,Co,Io,Ao,Mo;const{sendCommand:e}=Tt(),s=Nr(),r=tl(),n=Pa(),a=Vs(),[i,c]=vd(),l=i.get("activeTab"),u=((No=n.state)==null?void 0:No.openRemoteForTabKey)||null,f=((Co=n.state)==null?void 0:Co.openMachineId)||null,d=((Io=n.state)==null?void 0:Io.mobileSection)||null,x=Rc(),g=x.ides||[],w=x.initialLoaded??!0,{updateRouteChats:M,setToasts:m}=x,[p,b]=o.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),h=x.toasts||[],S=x.wsStatus||"connected",R=x.isConnected??!0,k=x.connectionStates||{},I=x.showReconnected||!1,{groupAssignments:j,setGroupAssignments:v,focusedGroup:y,setFocusedGroup:E,groupActiveTabIds:L,setGroupActiveTabIds:A,groupTabOrders:_,setGroupTabOrders:B,groupSizes:H,setGroupSizes:C,isMobile:P,hasHydratedStoredLayout:U,hydrateStoredLayout:N}=Gf(),[$,z]=o.useState(!1),[q,W]=o.useState(!1),[ne,ae]=o.useState(null),[ke,X]=o.useState([]),[pe,Y]=o.useState(!1),[J,ue]=o.useState(null),[le,V]=o.useState(()=>io());o.useEffect(()=>mf(V),[]);const ve=o.useMemo(()=>Rx({isMobile:P,mobileViewMode:le}),[P,le]),[ie,ce]=o.useState([]),[te,me]=o.useState({}),[re,je]=o.useState({}),[we,Te]=o.useState({}),[T,fe]=o.useState(null),[be,Q]=o.useState(null),[Se,De]=o.useState(null),Oe=o.useRef(null);jr("Dashboard",{ideCount:g.length,toastCount:h.length,focusedGroup:y,groupCount:Object.keys(j).length,localMessageTabs:Object.keys(te).length,actionLogCount:ie.length});const $e=o.useMemo(()=>g.filter(de=>de.type==="adhdev-daemon").sort(Fa),[g]),Ue=$e[0],ze=!!Ue;o.useEffect(()=>{for(const de of $e){(!de.detectedIdes||!de.availableProviders||!de.recentLaunches||!de.workspaces)&&s(de.id,{minFreshMs:3e4}).catch(()=>{});const ye=de.machine;(typeof(ye==null?void 0:ye.cpus)!="number"||typeof(ye==null?void 0:ye.totalMem)!="number"||typeof(ye==null?void 0:ye.arch)!="string"||typeof(ye==null?void 0:ye.release)!="string")&&r(de.id,{minFreshMs:3e4}).catch(()=>{})}},[s,r,$e]);const mt=(Ue==null?void 0:Ue.terminalBackend)||null,it=Ue?_t(Ue,{fallbackId:Ue.id}):null,xt=(Ue==null?void 0:Ue.id)||null,Ve=o.useMemo(()=>jf(g,re),[g,re]),{hiddenTabs:pt,hideTab:bt,toggleTab:ct,showTab:Me,showAllTabs:Je}=wf(),{chatIdes:Ye,conversations:Fe,visibleConversations:dt,visibleTabKeys:vt,resolveConversationBySessionId:jt,resolveConversationByTarget:Lt}=Pf({ides:Ve,connectionStates:k,localUserMessages:te,clearedTabs:we,hiddenTabs:pt}),Mt=o.useMemo(()=>new Map(Fe.map(de=>[de.tabKey,Fr(de)])),[Fe]),Ct=o.useCallback(de=>{const ge=Mt.get(de)||Fr({tabKey:de});bt(ge)},[Mt,bt]),Dt=o.useCallback(de=>{const ge=Mt.get(de)||Fr({tabKey:de});ct(ge)},[Mt,ct]),Z=o.useCallback(de=>{const ge=Mt.get(de)||Fr({tabKey:de});Me(ge)},[Mt,Me]);sp(dt,ve),o.useEffect(()=>{Object.keys(re).length!==0&&je(de=>kf(de,g))},[g,re]);const Ke=o.useMemo(()=>Nu(g),[g]),{notifications:D,unreadCount:O,notificationStateBySessionId:F,markRead:G,markUnread:oe,markTargetRead:Ie,deleteNotification:Le}=gh({conversations:Fe,liveSessionInboxState:Ke}),Ae=o.useCallback(de=>{const ge=D.find(he=>he.id===de),ye=Math.max(Date.now(),(ge==null?void 0:ge.updatedAt)||0);G(de,ye),ge!=null&&ge.sessionId&&e(ge.machineId||ge.routeId,"mark_session_seen",{sessionId:ge.sessionId,seenAt:ye}).catch(()=>{})},[G,D,e]),We=o.useCallback(de=>{const ge=D.find(ye=>ye.id===de);oe(de),ge!=null&&ge.sessionId&&e(ge.machineId||ge.routeId,"mark_notification_unread",{sessionId:ge.sessionId,notificationId:ge.id}).catch(()=>{})},[oe,D,e]),Be=o.useCallback(de=>{const ge=D.find(ye=>ye.id===de);Le(de),ge!=null&&ge.sessionId&&e(ge.machineId||ge.routeId,"delete_notification",{sessionId:ge.sessionId,notificationId:ge.id}).catch(()=>{})},[Le,D,e]),Ge=o.useRef(null),Ze=o.useRef(null),se=o.useRef(null),Ne=o.useRef(null),_e=o.useRef(null),{containerRef:rt,normalizedGroupAssignments:K,numGroups:ee,isSplitMode:xe,groupedConvs:Ee,moveTabToGroup:Re,closeGroup:Ce,handleResizeStart:et,splitTabRelative:It}=th({groupAssignments:j,setGroupAssignments:v,setFocusedGroup:E,setGroupActiveTabIds:A,setGroupTabOrders:B,groupSizes:H,setGroupSizes:C,isMobile:P,visibleConversations:dt,visibleTabKeys:vt}),Pe=o.useMemo(()=>{var ge,ye;if(!P){if(T){const he=Fe.find(Xe=>Xe.tabKey===T);if(he)return he}return dt[0]}const de=L[y];if(de){const he=Fe.find(Xe=>Xe.tabKey===de);if(he)return he}return((ge=Ee[y])==null?void 0:ge[0])||((ye=Ee[0])==null?void 0:ye[0])},[T,P,L,y,Fe,Ee,dt]);o.useEffect(()=>{const de=()=>{se.current&&(clearTimeout(se.current),se.current=null),Ne.current&&(clearTimeout(Ne.current),Ne.current=null),_e.current&&(document.removeEventListener("visibilitychange",_e.current),_e.current=null),Ze.current=null};if(P){de(),Ge.current=null;return}if(!(Pe!=null&&Pe.sessionId)){de(),Ge.current=null;return}const ge=dn(Pe,Ke),ye=Px({tabKey:Pe.tabKey,historySessionId:kr(Pe)||"",lastMessageHash:Pe.lastMessageHash||"",lastMessageAt:Number(Pe.lastMessageAt||0),timestamp:ps(Pe),liveState:ge}),he=ye.autoReadKey,Xe=_x({autoReadKey:he,shouldMarkSeen:ye.shouldMarkSeen,completedKey:Ge.current,pendingKey:Ze.current});if(!ye.shouldMarkSeen){Xe.shouldCancelPending&&de(),Ge.current=he;return}if(!Xe.shouldSchedule)return;Xe.shouldCancelPending&&de();const ft=ac(Pe),Et=()=>{if(document.visibilityState!=="visible"||Ge.current===he)return;Ge.current=he,Ze.current=null,se.current=null,Ne.current=null,_e.current&&(document.removeEventListener("visibilitychange",_e.current),_e.current=null);const gt=ye.readAt;Ie({...ft},gt),e(Pe.daemonId||Pe.routeId,"mark_session_seen",{sessionId:Pe.sessionId,seenAt:gt}).catch(()=>{})};if(Ze.current=Xe.nextPendingKey,document.visibilityState==="visible"){se.current=setTimeout(Et,1500);const gt=()=>{document.visibilityState!=="visible"&&se.current&&(clearTimeout(se.current),se.current=null)};_e.current=gt,document.addEventListener("visibilitychange",gt);return}const Yt=()=>{document.visibilityState==="visible"&&(Ne.current&&clearTimeout(Ne.current),Ne.current=setTimeout(Et,800),_e.current&&(document.removeEventListener("visibilitychange",_e.current),_e.current=null))};_e.current=Yt,document.addEventListener("visibilitychange",Yt)},[Pe,P,Ke,Ie,e]),o.useEffect(()=>()=>{se.current&&clearTimeout(se.current),Ne.current&&clearTimeout(Ne.current),_e.current&&document.removeEventListener("visibilitychange",_e.current)},[]);const{requestedDesktopTabKey:qt,requestedMobileTabKey:Ar,consumeRequestedActiveTab:Ys}=Df({isMobile:P,urlActiveTab:l,resolveConversationBySessionId:jt,setSearchParams:c}),{remoteDialogConv:Xs,remoteDialogIdeEntry:Ol,remoteDialogActiveConv:Wl,setRemoteDialogActiveConv:Rn,openRemoteDialog:Hl,closeRemoteDialog:Fl}=Xf({isMobile:P,location:n,navigate:a,requestedRemoteTabTarget:u,requestedDesktopTabKey:qt,conversations:Fe,ides:g,resolveConversationByTarget:Lt}),ut=Wl||Xs||Pe,Ft=!!ut&&tt(ut)&&!Qe(ut),Mr=o.useMemo(()=>{if(!ut||!Ft)return null;const de=ut.daemonId||ut.routeId||"",ge=Ot(ut);return`${de}:${ge}`},[ut,Ft]),Ul=o.useMemo(()=>dt,[dt]),Tr=P&&le==="chat",zl=o.useMemo(()=>Fe.filter(de=>co(pt,de)),[Fe,pt]),Lr=o.useCallback(de=>{const ge=new URLSearchParams(i);ge.set("activeTab",de),c(ge,{replace:!0})},[i,c]),Vl=o.useCallback(async(de,ge)=>In(e,de,ge),[e]),Gl=o.useCallback(async(de,ge)=>{if(!ge.trim())return{ok:!1,error:"Choose a workspace path first."};try{const ye=await e(de,"workspace_add",{path:ge.trim()});return ye!=null&&ye.success?{ok:!0}:{ok:!1,error:(ye==null?void 0:ye.error)||"Could not save workspace"}}catch(ye){return{ok:!1,error:ye instanceof Error?ye.message:"Could not save workspace"}}},[e]),ql=o.useCallback(async(de,ge,ye)=>{var he;try{const Xe={ideType:ge,enableCdp:!0};(he=ye==null?void 0:ye.workspacePath)!=null&&he.trim()&&(Xe.workspace=ye.workspacePath.trim());const ft=await e(de,"launch_ide",Xe);return!(ft!=null&&ft.success)&&(ft==null?void 0:ft.success)!==void 0?{ok:!1,error:(ft==null?void 0:ft.error)||"Could not launch IDE"}:(De({machineId:de,kind:"ide",providerType:ge,workspacePath:(ye==null?void 0:ye.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(Xe){return{ok:!1,error:Xe instanceof Error?Xe.message:"Could not launch IDE"}}},[e]),Yl=o.useCallback(async(de,ge,ye,he)=>{var ft,Et,Yt;const Xe=Date.now();try{const gt={cliType:ye};(ft=he==null?void 0:he.workspacePath)!=null&&ft.trim()?gt.dir=he.workspacePath.trim():he!=null&&he.workspaceId&&(gt.workspaceId=he.workspaceId),(Et=he==null?void 0:he.resumeSessionId)!=null&&Et.trim()&&(gt.resumeSessionId=he.resumeSessionId.trim()),Array.isArray(he==null?void 0:he.cliArgs)&&he.cliArgs.length>0&&(gt.cliArgs=he.cliArgs),(Yt=he==null?void 0:he.initialModel)!=null&&Yt.trim()&&(gt.initialModel=he.initialModel.trim());const yt=await e(de,"launch_cli",gt),$t=(yt==null?void 0:yt.result)||yt,Js=($t==null?void 0:$t.sessionId)||($t==null?void 0:$t.id);return yt!=null&&yt.success&&Js?(Lr(Js),{ok:!0}):yt!=null&&yt.success?(De({machineId:de,kind:ge,providerType:ye,workspacePath:(he==null?void 0:he.workspacePath)||null,resumeSessionId:(he==null?void 0:he.resumeSessionId)||null,startedAt:Xe}),{ok:!0}):{ok:!1,error:(yt==null?void 0:yt.error)||($t==null?void 0:$t.error)||`Could not launch ${ge.toUpperCase()} session`}}catch(gt){return Ex(gt)?(De({machineId:de,kind:ge,providerType:ye,workspacePath:(he==null?void 0:he.workspacePath)||null,resumeSessionId:(he==null?void 0:he.resumeSessionId)||null,startedAt:Xe}),{ok:!0}):{ok:!1,error:gt instanceof Error?gt.message:`Could not launch ${ge.toUpperCase()} session`}}},[Lr,e]),Xl=o.useCallback(async(de,ge)=>{if(!de||!ge)return[];try{const ye=await e(de,"list_saved_sessions",{providerType:ge,kind:"cli",limit:30}),he=(ye==null?void 0:ye.result)??ye;return Array.isArray(he==null?void 0:he.sessions)?he.sessions:[]}catch(ye){return console.error("List saved sessions failed",ye),[]}},[e]);o.useEffect(()=>{if(!Se)return;const de=Ti(Se.workspacePath),ge=g.find(he=>{var gt,yt,$t,Js;if(!he||he.type==="adhdev-daemon"||Dx(he.daemonId||he.id)!==Se.machineId||(br(he)?"cli":Ps(he)?"acp":"ide")!==Se.kind||String(he.agentType||he.type||"")!==Se.providerType)return!1;if(Se.resumeSessionId)return String(he.providerSessionId||"")===Se.resumeSessionId;if(de){const Pn=Ti(he.workspace||he.runtimeWorkspaceLabel);return Pn?Pn===de:!1}return Number(he.lastUpdated||he._lastUpdate||he.timestamp||((Js=($t=(yt=(gt=he.activeChat)==null?void 0:gt.messages)==null?void 0:yt.at)==null?void 0:$t.call(yt,-1))==null?void 0:Js.timestamp)||0)>=Se.startedAt-5e3});if(!ge)return;const ye=Sc({entrySessionId:ge.sessionId,entryInstanceId:ge.instanceId,entryRouteId:ge.id,conversations:Fe});ye&&(De(null),Lr(ye))},[Fe,Lr,g,Se]),o.useEffect(()=>{if(!Se)return;const de=window.setTimeout(()=>{De(ge=>!ge||ge.startedAt!==Se.startedAt?ge:null)},45e3);return()=>window.clearTimeout(de)},[Se]),Sf({visibleConversations:dt,clearedTabs:we,setClearedTabs:Te,setActionLogs:ce}),Ef({ides:g,sendDaemonCommand:e,setToasts:m,setLocalUserMessages:me,resolveConversationByTarget:Lt});const{isRefreshingHistory:Jl,handleRefreshHistory:Ql}=di({sendDaemonCommand:e,activeConv:Pe,chats:(Ao=g.find(de=>de.id===(Pe==null?void 0:Pe.routeId)))==null?void 0:Ao.chats,updateRouteChats:M,setToasts:m,setLocalUserMessages:me,setClearedTabs:Te}),{isCreatingChat:Zl,isRefreshingHistory:ed,handleSwitchSession:td,handleNewChat:sd,handleRefreshHistory:rd}=di({sendDaemonCommand:e,activeConv:ut,chats:(Mo=g.find(de=>de.id===(ut==null?void 0:ut.routeId)))==null?void 0:Mo.chats,updateRouteChats:M,setToasts:m,setLocalUserMessages:me,setClearedTabs:Te}),_n=o.useCallback(async()=>{if(!(!ut||!Ft||pe)){Y(!0);try{const de=ut.daemonId||ut.routeId,ge=Ot(ut),ye=await e(de,"list_saved_sessions",{agentType:ge,providerType:ge,kind:"cli",limit:50}),he=(ye==null?void 0:ye.result)??ye;X(Array.isArray(he==null?void 0:he.sessions)?he.sessions:[])}catch(de){console.error("Refresh saved sessions failed",de),X([])}finally{Y(!1)}}},[ut,pe,Ft,e]);o.useEffect(()=>{if(!$){Oe.current=null;return}if(!Ft){Oe.current=null,X([]),Y(!1);return}!Mr||pe||Oe.current!==Mr&&(Oe.current=Mr,_n())},[_n,$,pe,Ft,Mr]);const nd=o.useCallback(async de=>{if(!ut||!Ft||!de.providerSessionId||!de.workspace)return;const ge=ut.daemonId||ut.routeId,ye=Ot(ut);try{ue(de.providerSessionId);const he=await e(ge,"launch_cli",{cliType:ye,dir:de.workspace,resumeSessionId:de.providerSessionId,initialModel:mc(de.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Xe=(he==null?void 0:he.result)??he,ft=typeof(Xe==null?void 0:Xe.sessionId)=="string"?Xe.sessionId:typeof(Xe==null?void 0:Xe.id)=="string"?Xe.id:"";ft&&c(Et=>{const Yt=new URLSearchParams(Et);return Yt.set("activeTab",ft),Yt},{replace:!0}),z(!1)}catch(he){console.error("Resume saved session failed",he)}finally{ue(null)}},[ut,Ft,e,c]);Yf({urlActiveTab:P&&!Tr?l:null,conversations:Fe,resolveConversationBySessionId:jt,normalizedGroupAssignments:K,hasHydratedStoredLayout:P&&!Tr?U:!0,hydrateStoredLayout:P&&!Tr?N:()=>{},setGroupActiveTabIds:A,setFocusedGroup:E,setSearchParams:c,historyModalOpen:$,activeConv:Pe,isRefreshingHistory:Jl,ides:g,handleRefreshHistory:Ql});const wo=o.useCallback(async(de,ge)=>{const ye=ge||ne||Pe;if(!ye||!tt(ye)&&!Qe(ye))return;const he=Ot(ye),Xe=ye.routeId||ye.daemonId||"";try{await e(Xe,"stop_cli",{cliType:he,targetSessionId:ye.sessionId,mode:de})}catch(ft){console.error("Stop CLI failed:",ft)}},[Pe,ne,e]),ad=o.useCallback(async de=>{const ge=de||Pe;!ge||!tt(ge)&&!Qe(ge)||(ae(ge),W(!0))},[Pe]),od=o.useMemo(()=>!Pe||!tt(Pe)||Qe(Pe)?null:Hs(Pe),[Pe]),id=o.useCallback(async de=>{if(!Pe||!tt(Pe)||Qe(Pe))return;const ge=Hs(Pe);if(ge===de)return;const ye=Pe.sessionId;ye&&je(he=>({...he,[ye]:de}));try{await e(is(Pe)||Pe.routeId,"set_cli_view_mode",{targetSessionId:Pe.sessionId,cliType:Ot(Pe),mode:de})}catch(he){const Xe=uo(he);ye&&!Xe&&je(ft=>{const Et={...ft};return ge===ol(g,ye)?delete Et[ye]:Et[ye]=ge,Et}),lo(he)?console.warn(Xe?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",he instanceof Error?he.message:String(he)):console.error("Failed to switch CLI view mode:",he)}},[Pe,g,e]),{versionMismatchDaemons:cd,hasRequiredVersionDaemons:jo,appVersion:ld,versionBannerDismissed:dd,setVersionBannerDismissed:ud,upgradingDaemons:md,handleBannerUpgrade:pd}=sh({ides:g,sendDaemonCommand:e}),ko=o.useCallback(de=>{fe(de.tabKey),c(ge=>{const ye=new URLSearchParams(ge),he=ym(de);return he?ye.set("activeTab",he):ye.delete("activeTab"),ye},{replace:!0})},[c]),So=o.useCallback(de=>{Z(de.tabKey),ko(de)},[ko,Z]),fd=o.useCallback(de=>{Ct(de.tabKey)},[Ct]);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(xp,{wsStatus:S,showReconnected:I}),t.jsx(bp,{terminalBackend:mt,isStandalone:ze,machineLabel:it,machineKey:xt}),(!dd||jo)&&t.jsx(Lx,{daemons:cd,targetVersion:ld,required:jo,upgradingDaemons:md,onUpgrade:pd,onDismiss:()=>ud(!0)}),t.jsx(Sx,{showMobileChatMode:Tr,isMobile:P,activeConv:Pe,chatIdes:Ye,wsStatus:S,isConnected:R,onOpenHistory:de=>{de&&Rn(de),z(!0)},onOpenRemote:Hl,onStopCli:ad,activeCliViewMode:od,onSetActiveCliViewMode:id,mobileChatConversations:Ul,ides:g,actionLogs:ie,sendDaemonCommand:e,setLocalUserMessages:me,setActionLogs:ce,isStandalone:ze,initialDataLoaded:w,userName:x.userName,requestedMobileTabKey:Ar,onRequestedMobileTabConsumed:Ys,requestedMachineId:f,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:rt,isSplitMode:xe,numGroups:ee,groupSizes:H,groupedConvs:Ee,clearedTabs:we,focusedGroup:y,setFocusedGroup:E,moveTabToGroup:Re,splitTabRelative:It,closeGroup:Ce,handleResizeStart:et,groupActiveTabIds:L,setGroupActiveTabIds:A,groupTabOrders:_,setGroupTabOrders:B,toggleHiddenTab:Dt,visibleConversations:dt,hiddenConversations:zl,requestedDesktopTabKey:qt,onRequestedDesktopTabConsumed:Ys,onDesktopActiveTabChange:fe,onHideConversation:fd,onShowHiddenConversation:So,onShowAllHiddenConversations:Je,scrollToBottomRequest:be,machineEntries:$e,onBrowseMachineDirectory:Vl,onSaveMachineWorkspace:Gl,onLaunchMachineIde:ql,onLaunchMachineProvider:Yl,onListMachineSavedSessions:Xl,notifications:D,notificationUnreadCount:O,notificationStateBySessionId:F,liveSessionInboxState:Ke,onMarkNotificationRead:Ae,onMarkNotificationUnread:We,onDeleteNotification:Be,onMarkNotificationTargetRead:Ie}),t.jsx("style",{children:`
|
|
60
|
-
body { overflow: hidden; overscroll-behavior: none; }
|
|
61
|
-
`}),t.jsx(Tx,{historyModalOpen:$,historyTargetConv:ut,ides:g,isHistoryCreatingChat:Zl,isHistoryRefreshingHistory:Ft?!1:ed,savedHistorySessions:ke,isSavedHistoryLoading:pe,isResumingSavedHistorySessionId:J,onCloseHistory:()=>z(!1),onNewHistoryChat:sd,onSwitchHistorySession:td,onRefreshHistory:Ft?_n:rd,onResumeSavedHistorySession:nd,remoteDialogConv:Xs,remoteDialogIdeEntry:Ol,connectionStates:k,actionLogs:ie,localUserMessages:te,sendDaemonCommand:e,setLocalUserMessages:me,setActionLogs:ce,isStandalone:ze,userName:x.userName,onOpenRemoteHistory:de=>{de&&Rn(de),z(!0)},onRemoteConversationChange:Rn,onCloseRemoteDialog:Fl,cliStopDialogOpen:q,cliStopTargetConv:ne,onCancelCliStop:()=>{W(!1),ae(null)},onStopCliNow:async()=>{W(!1),await wo("hard",ne),ae(null)},onSaveCliAndStop:async()=>{W(!1),await wo("save",ne),ae(null)},toasts:h,onDismissToast:de=>m(ge=>ge.filter(ye=>ye.id!==de)),onClickToast:de=>{if(de.targetKey){const ge=Lt(de.targetKey);ge&&(E(K.get(ge.tabKey)??0),So(ge),Q({tabKey:ge.tabKey,nonce:Date.now()}))}},showOnboarding:p,onCloseOnboarding:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}b(!1)}})]})}function Kx({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[i,c]=o.useState([]),[l,u]=o.useState(null),[f,d]=o.useState(null),[x,g]=o.useState(!1),[w,M]=o.useState(null),[m,p]=o.useState(!1),[b,h]=o.useState(""),S=o.useRef(null),R=o.useCallback(N=>{S.current=N},[]),k=o.useCallback((N,$,z=!1)=>{c(q=>[...q.slice(-100),{timestamp:Date.now(),level:N,message:$}]),setTimeout(()=>{var q;return(q=a.current)==null?void 0:q.scrollIntoView({behavior:"smooth"})},100),z&&st.showToast($,N==="error"||N==="warn"?"warning":"success")},[a]),I=o.useCallback(N=>{const $=N instanceof Error?N.message:String(N||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),j=o.useCallback(async(N,$)=>{var z;if(!e||l)return!1;u(N),k("info",`Launching ${ot(N)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const q={ideType:N,enableCdp:!0};(z=$==null?void 0:$.workspace)!=null&&z.trim()?q.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(q.useDefaultWorkspace=!0);const W=await r(e,"launch_ide",q);return k(W!=null&&W.success?"info":"error",W!=null&&W.success?`${ot(N)} launched`:`Failed: ${W==null?void 0:W.error}`,!0),!!(W!=null&&W.success)}catch(q){return k("error",`Launch error: ${q.message}`,!0),!1}finally{u(null)}},[e,l,k,r]),v=o.useCallback(async N=>{if(!e)return{success:!1};const{cliType:$,dir:z,workspaceId:q,useDefaultWorkspace:W,useHome:ne,argsStr:ae,model:ke,resumeSessionId:X}=N;if(!$)return k("warn","Select a CLI or ACP provider first",!0),{success:!1};const pe=ae?ae.split(/\s+/).filter(Boolean):void 0,Y=(z==null?void 0:z.trim())||(q?"(saved id)":W?"(default workspace)":ne?"(home)":"");k("info",`Launching ${$}${Y?` in ${Y}`:""}${ke?` (model: ${ke})`:""}...`),d($);try{const J={cliType:$,cliArgs:pe,initialModel:ke||void 0};z!=null&&z.trim()?J.dir=z.trim():q?J.workspaceId=q:W?J.useDefaultWorkspace=!0:ne&&(J.useHome=!0),X&&(J.resumeSessionId=X);const ue=await r(e,"launch_cli",J),le=(ue==null?void 0:ue.result)||ue;return ue!=null&&ue.success?(k("info",`${$} launched`,!0),(le==null?void 0:le.launchSource)==="home"?k("info","📂 Running in home directory (explicit choice)"):(le==null?void 0:le.launchSource)==="defaultWorkspace"&&k("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:le==null?void 0:le.sessionId}):(k("error",`Failed: ${(ue==null?void 0:ue.error)||(le==null?void 0:le.error)}`,!0),(ue==null?void 0:ue.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&M({cliType:$,argsStr:ae,model:ke}),{success:!1,sessionId:le==null?void 0:le.sessionId})}catch(J){return I(J)?(k("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(k("error",`Launch error: ${J.message}`,!0),{success:!1})}finally{d(null)}},[e,k,I,r]),y=o.useCallback(async(N,$,z,q)=>e?N?$.trim()?v({cliType:N,dir:$,argsStr:z,model:q}):(M({cliType:N,argsStr:z,model:q}),{success:!1}):(k("warn","Select a provider",!0),{success:!1}):{success:!1},[e,k,v]),E=o.useCallback(async(N,$,z)=>{if(e&&window.confirm(`Stop ${N}?
|
|
62
|
-
This will terminate the process.`))try{const q=await r(e,"stop_cli",{cliType:N,dir:$,targetSessionId:z});q!=null&&q.success?k("info",`${N} stopped`,!0):k("error",`Stop failed: ${(q==null?void 0:q.error)||"Unknown error"}`,!0)}catch(q){k("error",`Stop failed: ${q.message}`,!0)}},[e,k,r]),L=o.useCallback(async N=>{try{await r(N.daemonId,"restart_ide",{ideType:N.type}),k("info",`${ot(N.type)} restart initiated`,!0)}catch($){k("error",`Restart failed: ${$.message}`,!0)}},[k,r]),A=o.useCallback(async N=>{if(window.confirm(`Stop ${ot(N.type)}?
|
|
63
|
-
This will disconnect CDP and optionally kill the process.`))try{const $=await r(N.daemonId,"stop_ide",{ideType:N.type,killProcess:!0});$!=null&&$.success?k("info",`${ot(N.type)} stopped`,!0):k("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){k("error",`Stop failed: ${$.message}`,!0)}},[k,r]),_=o.useCallback(async()=>{if(e)try{const N=await r(e,"detect_ides",{});k("info",`Found ${((N==null?void 0:N.result)||[]).length} IDE(s)`,!0)}catch(N){k("error",`Detection failed: ${N.message}`,!0)}},[e,k,r]),B=o.useCallback(async N=>{if(!e||!N.trim())return!1;g(!0);try{const $=await r(e,"workspace_add",{path:N.trim()});return $!=null&&$.success?(k("info",`Workspace added: ${N.trim()}`),!0):(k("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return k("error",$.message),!1}finally{g(!1)}},[e,k,r]),H=o.useCallback(async N=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const $=await r(e,"workspace_remove",{id:N});$!=null&&$.success?k("info","Workspace removed",!0):k("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){k("error",$.message,!0)}finally{g(!1)}}},[e,k,r]),C=o.useCallback(async N=>{var $;if(e){g(!0);try{const z=await r(e,"workspace_set_default",N===null?{clear:!0}:{id:N});if(z!=null&&z.success){k("info",N?"Default workspace updated":"Default workspace cleared",!0);const q=typeof z.defaultWorkspacePath=="string"?z.defaultWorkspacePath:"";q&&(($=S.current)==null||$.call(S,q))}else k("error",(z==null?void 0:z.error)||"workspace_set_default failed",!0)}catch(z){k("error",z.message,!0)}finally{g(!1)}}},[e,k,r]),P=o.useCallback(async N=>{var z;if(!e||!N.trim())return;const $=N.trim();g(!0);try{const q=await r(e,"workspace_set_default",{path:$});q!=null&&q.success?(k("info","Default workspace set from history"),(z=S.current)==null||z.call(S,$)):k("error",(q==null?void 0:q.error)||"Could not set default (path missing on disk?)")}catch(q){k("error",q.message)}finally{g(!1)}},[e,k,r]),U=o.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:b}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:b})}catch(N){k("warn",`Live nickname updated, but account sync failed: ${N.message}`)}k("info",`Nickname set to "${b||"(cleared)"}"`),p(!1)}catch(N){k("error",`Failed: ${N.message}`)}},[e,b,s,k,n,r]);return{logs:i,launchingIde:l,launchingAgentType:f,workspaceBusy:x,launchPick:w,setLaunchPick:M,editingNickname:m,setEditingNickname:p,nicknameInput:b,setNicknameInput:h,addLog:k,handleLaunchIde:j,runLaunchCliCore:v,handleLaunchCli:y,handleStopCli:E,handleRestartIde:L,handleStopIde:A,handleDetectIdes:_,handleWorkspaceAdd:B,handleWorkspaceRemove:H,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:P,handleSaveNickname:U,setOnDefaultWorkspaceChanged:R}}function Bx({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:i,sendDaemonCommand:c}){var L;const{workspaceBusy:l,handleWorkspaceAdd:u,handleWorkspaceRemove:f,handleWorkspaceSetDefault:d}=i,[x,g]=o.useState(!1),[w,M]=o.useState(""),[m,p]=o.useState([]),[b,h]=o.useState(!1),[S,R]=o.useState(""),k=o.useCallback(async A=>{h(!0),R("");try{const _=await In(c,e,A);M(_.path),p(_.directories)}catch(_){R(_ instanceof Error?_.message:"Could not load folder")}finally{h(!1)}},[e,c]),I=o.useCallback(()=>{g(!0);const A=[...r.map(B=>B.workspace),...n.map(B=>B.workspace),...a.map(B=>B.workspace)],_=Cn(s.platform,Nn(A,s.defaultWorkspacePath,(s.workspaces||[]).map(B=>B.path)));k(_)},[a,n,r,k,s.defaultWorkspacePath,s.platform,s.workspaces]),j=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,v=s.availableMem??s.freeMem??s.totalMem,y=j&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-v)/s.totalMem*100))):0,E=((L=s.loadavg)==null?void 0:L[0])||0;return t.jsxs("div",{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[t.jsx(Dr,{icon:t.jsx(Zi,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Mu(s.uptime):"Waiting…"}),t.jsx(Dr,{icon:t.jsx(Pt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(Dr,{icon:t.jsx(yn,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(Dr,{icon:t.jsx(Gd,{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(Bo,{value:j?Math.min(Math.round(E/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:j?`${E.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(Bo,{value:y,max:100,label:"Memory",color:"#3b82f6",detail:j?`${Bn(s.totalMem-v)} / ${Bn(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Bn(s.totalMem)} total`})]})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[t.jsx(Bs,{size:14})," Workspaces"]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[t.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),t.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:l,value:s.defaultWorkspaceId||"",onChange:A=>void d(A.target.value===""?null:A.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(A=>t.jsx("option",{value:A.id,children:A.label||A.path},A.id))]}),s.defaultWorkspacePath&&t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:l,onClick:I,children:"Select workspace…"}),t.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&t.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(A=>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:[A.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:kn(A.path,A.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:A.path,children:A.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:l,onClick:()=>void f(A.id),children:"Remove"})]},A.id))})]}),x&&t.jsx(An,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:m,busy:b,error:S,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:A=>{k(A)},onConfirm:A=>{(async()=>{if(!A)return;await u(A)&&g(!1)})()}})]})}function Ox(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 Wx(e,s,r){const n=[];for(const[a,i]of Object.entries(e.settings)){const c=i;if(c.length===0)continue;const l=s.find(u=>u.type===a);n.push({type:a,displayName:(l==null?void 0:l.displayName)||a,icon:(l==null?void 0:l.icon)||"",category:(l==null?void 0:l.category)||"unknown",schema:c,values:e.values[a]||{}})}return n}function ra(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 Li(e){if(!e||typeof e!="object")return null;if(ra(e))return e;const s=e,r=s.result;return ra(r)?r:ra(s.sourceConfig)?s.sourceConfig:null}function Hx(e){const s=e.trim();return s||null}const Ri=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Fx=[{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 Ux({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,i]=o.useState("config"),[c,l]=o.useState("codex-cli"),[u,f]=o.useState([]),[d,x]=o.useState(""),[g,w]=o.useState([]),[M,m]=o.useState(""),p=o.useRef(null),b=o.useRef(null),h=v=>{f(y=>y.includes(v)?y.filter(E=>E!==v):[...y,v])},S=()=>f([...Ri]),R=()=>f([]);o.useEffect(()=>{var v;(v=p.current)==null||v.scrollIntoView({behavior:"smooth"})},[g]),o.useEffect(()=>()=>{b.current&&clearInterval(b.current)},[]);const k=o.useCallback(()=>{b.current&&clearInterval(b.current),b.current=setInterval(async()=>{try{const v=await r(e,"provider_auto_fix_status",{providerType:s.type});(v==null?void 0:v.running)===!1&&a==="running"&&(i("done"),w(y=>[...y,`
|
|
64
|
-
✅ Auto-fix completed!`]),b.current&&clearInterval(b.current))}catch{}},3e3)},[e,s.type,r,a]),I=async()=>{if(u.length!==0){i("running"),w(["🚀 Starting auto-fix...",`Agent: ${c}`,`Scripts: ${u.join(", ")}`,d?`💬 Comment: ${d}`:"",""]),m("");try{const v=await r(e,"provider_auto_fix",{providerType:s.type,functions:u,agent:c,...d?{comment:d}:{}});v!=null&&v.success&&(v!=null&&v.started||v!=null&&v.running)?(w(y=>[...y,"✅ Agent started. Monitoring progress..."]),k()):(i("error"),m((v==null?void 0:v.error)||"Failed to start auto-fix"))}catch(v){i("error"),m((v==null?void 0:v.message)||"Connection failed")}}},j=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),w(v=>[...v,`
|
|
65
|
-
⚠️ Auto-fix cancelled.`]),i("done"),b.current&&clearInterval(b.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:v=>v.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:Fx.map(v=>t.jsxs("button",{onClick:()=>l(v.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:c===v.value?v.color+"66":"var(--border-subtle)",background:c===v.value?v.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:c===v.value?v.color:"var(--text-primary)"},children:v.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:v.desc})]},v.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:S,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:R,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Ri.map(v=>t.jsxs("button",{onClick:()=>h(v),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:u.includes(v)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:u.includes(v)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:u.includes(v)?"#a78bfa":"var(--text-secondary)"},children:[u.includes(v)?"☑ ":"☐ ",v]},v))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:d,onChange:v=>x(v.target.value),placeholder:"e.g. Also search buttons inside Shadow DOM, preserve code block formatting in readChat...",rows:2,className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] resize-none placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]})]}),(a==="running"||a==="done"||a==="error")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-[#0d0d0d] p-3 font-mono text-[11px] leading-relaxed text-text-secondary overflow-y-auto",style:{maxHeight:320,minHeight:200},children:[g.map((v,y)=>t.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},y)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:p})]}),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"&&u.length>0&&`${u.length} script(s) selected`,a==="running"&&"Agent is generating...",a==="done"&&"Run `adhdev provider verify` to validate"]}),t.jsxs("div",{className:"flex gap-2",children:[a==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:I,disabled:u.length===0,className:"machine-btn",style:{background:u.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:u.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:u.length>0?"#a78bfa":void 0,opacity:u.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&t.jsx("button",{onClick:j,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{i("config"),w([]),m("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function zx({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var k;const i=s.filter(I=>I.category==="ide"),[c,l]=o.useState(((k=i[0])==null?void 0:k.type)||""),[u,f]=o.useState(""),[d,x]=o.useState(""),[g,w]=o.useState(!1),[M,m]=o.useState(""),[p,b]=o.useState(!1),h=I=>{const j=I.toLowerCase().replace(/[^a-z0-9-]/g,"");f(j),(!d||d===S(u))&&x(S(j))},S=I=>I.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),R=async()=>{if(!(!u||!d||!c)){w(!0),m("");try{const I=await r(e,"provider_clone",{type:u,name:d,category:"ide",location:"user",cloneFrom:c});I!=null&&I.success||I!=null&&I.created?(b(!0),a==null||a(u)):m((I==null?void 0:I.error)||"Failed to create provider")}catch(I){m((I==null?void 0:I.message)||"Connection failed")}w(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:I=>I.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:p?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:u})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",u,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",u]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(I=>t.jsxs("button",{onClick:()=>l(I.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===I.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===I.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:I.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===I.type?"#a78bfa":"var(--text-secondary)"},children:I.displayName})]},I.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:u,onChange:I=>h(I.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",u||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:d,onChange:I=>x(I.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),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:p?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:R,disabled:!u||!d||g,className:"machine-btn",style:{background:u&&d?"rgba(34,197,94,0.12)":void 0,borderColor:u&&d?"rgba(34,197,94,0.3)":void 0,color:u&&d?"#86efac":void 0,opacity:!u||!d||g?.4:1},children:g?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Vx({machineId:e,providers:s,sendDaemonCommand:r}){var L;const[n,a]=o.useState([]),[i,c]=o.useState(!1),[l,u]=o.useState(null),[f,d]=o.useState("all"),[x,g]=o.useState(null),[w,M]=o.useState(!1),[m,p]=o.useState(null),[b,h]=o.useState("normal"),[S,R]=o.useState(""),[k,I]=o.useState(!1),j=o.useCallback(async()=>{if(e)try{const A=await r(e,"get_provider_source_config",{}),_=Li(A);_&&(p(_),h(_.sourceMode),R(_.explicitProviderDir||""))}catch{}},[e,r]),v=o.useCallback(async()=>{if(e){c(!0);try{const A=await r(e,"get_provider_settings",{}),_=Ox(A);if(_){const B=Wx(_,s);B.sort((H,C)=>H.category.localeCompare(C.category)||H.displayName.localeCompare(C.displayName)),a(B)}}catch{}c(!1)}},[e,s,r]);o.useEffect(()=>{n.length===0&&v(),m||j()},[]);const y=async(A,_,B)=>{u(`${A}.${_}`),a(H=>H.map(C=>C.type===A?{...C,values:{...C.values,[_]:B}}:C));try{const H=await r(e,"set_provider_setting",{providerType:A,key:_,value:B});H!=null&&H.success||v()}catch{v()}u(null)},E=async()=>{I(!0);try{const A=await r(e,"set_provider_source_config",{providerSourceMode:b,providerDir:Hx(S)}),_=Li(A);_?(p(_),h(_.sourceMode),R(_.explicitProviderDir||"")):await j(),await v()}catch{await j()}I(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(A=>t.jsx("button",{onClick:()=>d(A),className:`machine-btn text-[10px] px-2 py-0.5 ${f===A?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:A.toUpperCase()},A))]}),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:v,disabled:i,className:"machine-btn",children:i?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"Affects provider resolution, fix/verify flows, and new launches. Existing running sessions may need restart."})]}),t.jsx("button",{onClick:j,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:b,onChange:A=>h(A.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:S,onChange:A=>R(A.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void E(),disabled:k,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:k?"Applying…":"Apply + Reload"})]}),t.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(m==null?void 0:m.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(m==null?void 0:m.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((L=m==null?void 0:m.providerRoots)==null?void 0:L.join(" → "))||"loading…"]})]})]}),f!=="all"&&n.filter(A=>A.category===f).length>1&&(()=>{const A=n.filter(C=>C.category===f),_=new Map;for(const C of A)for(const P of C.schema){if(P.type!=="boolean")continue;const U=_.get(P.key),N=!!(C.values[P.key]??P.default);U?(U.onCount+=N?1:0,U.total+=1):_.set(P.key,{label:P.label||P.key,onCount:N?1:0,total:1})}const B=[..._.entries()].filter(([,C])=>C.total===A.length);if(B.length===0)return null;const H=async(C,P)=>{for(const U of A)await y(U.type,C,P)};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 ",f.toUpperCase()," providers (",A.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:B.map(([C,P])=>{const U=P.onCount===P.total,N=P.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:P.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",P.onCount,"/",P.total,")"]}),t.jsx("button",{onClick:()=>void H(C,!0),disabled:U,className:`machine-btn text-[9px] px-1.5 py-px ${U?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void H(C,!1),disabled:N,className:`machine-btn text-[9px] px-1.5 py-px ${N?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},C)})})]})})(),i&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(A=>f==="all"||A.category===f).map(A=>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:A.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:A.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:A.category==="acp"?"rgba(139,92,246,0.08)":A.category==="cli"?"rgba(59,130,246,0.08)":A.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:A.category==="acp"?"#a78bfa":A.category==="cli"?"#60a5fa":A.category==="ide"?"#86efac":"var(--status-warning)"},children:A.category}),A.category==="ide"&&t.jsx("button",{onClick:()=>g(s.find(_=>_.type===A.type)||{type:A.type,name:A.displayName,displayName:A.displayName,icon:A.icon,category:A.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:A.schema.map(_=>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:[_.label||_.key,l===`${A.type}.${_.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),_.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:_.description})]}),t.jsx("div",{className:"shrink-0",children:_.type==="boolean"?t.jsx("button",{onClick:()=>y(A.type,_.key,!(A.values[_.key]??_.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:A.values[_.key]??_.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:A.values[_.key]??_.default?21:3}})}):_.type==="number"?t.jsx("input",{type:"number",value:Number(A.values[_.key]??_.default??0)||0,min:_.min,max:_.max,onChange:B=>{const H=parseInt(B.target.value)||0;_.min!==void 0&&H<_.min||_.max!==void 0&&H>_.max||y(A.type,_.key,H)},className:"machine-input w-20 text-center text-[11px]"}):_.type==="select"&&_.options?t.jsx("select",{value:String(A.values[_.key]??_.default??""),onChange:B=>y(A.type,_.key,B.target.value),className:"machine-input text-[11px]",children:_.options.map(B=>t.jsx("option",{value:B,children:B},B))}):t.jsx("input",{type:"text",value:String(A.values[_.key]??_.default??""),onBlur:B=>y(A.type,_.key,B.target.value),className:"machine-input w-[120px] text-[11px]"})})]},_.key))})]},A.type))}),x&&t.jsx(Ux,{machineId:e,provider:x,sendDaemonCommand:r,onClose:()=>g(null)}),w&&t.jsx(zx,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>M(!1),onCreated:()=>{M(!1),v()}})]})}const Gx=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function qx({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function Yx(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Xx(e){return e.trim().toLowerCase()}function Tn(e,s){const r=Xx(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function yo(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function vr(e,s=220){const r=yo(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function Jx(e){const s=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(s))return{kind:s.length>0?"structured":"empty",entries:s.map(r=>{const n=r;return{timestamp:Number(n.ts)||0,level:n.level||"info",message:`[${String(n.category||"daemon")}] ${String(n.message||"")}`.trim()}}),rawText:""};if(typeof s=="string"){const r=s.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function Dl(e,s){return e.filter(r=>Tn([r.level,r.message],s))}function Qx(e,s){return e.split(`
|
|
66
|
-
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Tn([r],s))}function El(e,s){return e.filter(r=>Tn([r.level,r.category,r.stage,r.interactionId,yo(r.payload)],s))}function $l(e,s){return e.filter(r=>Tn([r.kind,r.topic,r.interactionId,yo(r.payload)],s))}function _i(e){return e==="warn"||e==="error"}function Zx({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){return{all:e.length+s.length+r.length+n.length,info:e.filter(a=>a.level!=="debug").length+r.filter(a=>a.level!=="debug").length+n.length,issues:e.filter(a=>_i(a.level)).length+r.filter(a=>_i(a.level)).length}}function eb({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(i=>`${new Date(i.timestamp).toISOString()} ${i.level.toUpperCase()} ${i.message}`)].join(`
|
|
67
|
-
`)):s.length>0&&a.push(["[daemon logs]",...s].join(`
|
|
68
|
-
`)),r.length>0&&a.push(["[trace]",...r.map(i=>`${new Date(i.ts).toISOString()} ${i.level.toUpperCase()} ${i.category}.${i.stage} ${vr(i.payload,500)}`.trim())].join(`
|
|
69
|
-
`)),n.length>0&&a.push(["[browser events]",...n.map(i=>`${new Date(i.ts).toISOString()} ${i.kind}${i.topic?` topic=${i.topic}`:""} ${vr(i.payload,500)}`.trim())].join(`
|
|
70
|
-
`)),a.join(`
|
|
71
|
-
|
|
72
|
-
`)}function tb({daemonLogs:e,trace:s,webEvents:r,daemonLogKind:n,daemonFetchError:a,traceFetchError:i,searchQuery:c}){const l=Dl(e,c),u=El(s,c),f=$l(r,c),d=l.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"daemon",level:w.level,timestamp:w.timestamp,label:"daemon",detail:w.message})),x=u.filter(w=>w.level==="warn"||w.level==="error").map(w=>({source:"trace",level:w.level,timestamp:w.ts,label:`${w.category}.${w.stage}`,detail:vr(w.payload,320)||`${w.category}.${w.stage}`})),g=[...d,...x].sort((w,M)=>M.timestamp-w.timestamp);return{daemonCount:l.length,traceCount:u.length,webCount:f.length,issueCount:g.length,latestIssue:g[0]||null,hasAnyData:n==="text"||l.length>0||u.length>0||f.length>0,hasBlockingError:!!(a||i)}}function Pi(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Di(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function na(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function sb({machineId:e,sendDaemonCommand:s}){var we,Te;const[r,n]=o.useState([]),[a,i]=o.useState("empty"),[c,l]=o.useState(""),[u,f]=o.useState([]),[d,x]=o.useState([]),[g,w]=o.useState(0),[M,m]=o.useState(0),[p,b]=o.useState(null),[h,S]=o.useState(!0),[R,k]=o.useState("info"),[I,j]=o.useState("info"),[v,y]=o.useState("all"),[E,L]=o.useState(""),[A,_]=o.useState(!0),[B,H]=o.useState(!0),[C,P]=o.useState(""),[U,N]=o.useState(""),[$,z]=o.useState(0),[q,W]=o.useState({daemon:!0,trace:!1,web:!1}),ne=o.useRef(null),ae=o.useRef(!1),ke=o.useMemo(()=>Yx(u,v),[u,v]),X=o.useMemo(()=>Dl(r,E),[r,E]),pe=o.useMemo(()=>Qx(c,E),[c,E]),Y=o.useMemo(()=>El(ke,E),[ke,E]),J=o.useMemo(()=>$l(d,E),[d,E]),ue=o.useMemo(()=>I==="issues"?X.filter(T=>T.level==="warn"||T.level==="error"):I==="info"?X.filter(T=>T.level!=="debug"):X,[X,I]),le=o.useMemo(()=>I==="all"?pe:[],[pe,I]),V=o.useMemo(()=>I==="issues"?Y.filter(T=>T.level==="warn"||T.level==="error"):I==="info"?Y.filter(T=>T.level!=="debug"):Y,[Y,I]),ve=o.useMemo(()=>I==="issues"?[]:J,[J,I]),ie=o.useMemo(()=>Zx({daemonLogs:X,daemonRawLines:pe,trace:Y,webEvents:J}),[X,pe,Y,J]),ce=o.useMemo(()=>tb({daemonLogs:r,trace:ke,webEvents:d,daemonLogKind:a,daemonFetchError:C,traceFetchError:U,searchQuery:E}),[C,a,r,ke,E,U,d]),te=o.useCallback(async()=>{if(!e)return;const[T,fe]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:R,since:g}),s(e,"get_debug_trace",qx({count:120,since:M,category:v}))]);if(T.status==="fulfilled"){const be=T.value,Q=(be==null?void 0:be.result)||be,Se=Jx(Q);if(_(!1),P((be==null?void 0:be.success)===!1?String((be==null?void 0:be.error)||"Could not load daemon logs"):""),i(Se.kind),l(Se.rawText),Se.entries.length>0){n(Oe=>(g>0?[...Oe,...Se.entries]:Se.entries).slice(-300));const De=Se.entries.reduce((Oe,$e)=>Math.max(Oe,Number($e.timestamp||0)),g);De>g&&w(De)}else Se.kind!=="structured"&&g===0&&n([])}else _(!1),P(T.reason instanceof Error?T.reason.message:"Could not load daemon logs");if(fe.status==="fulfilled"){const be=fe.value,Q=(be==null?void 0:be.result)||be;if((be==null?void 0:be.success)===!1)N(String((be==null?void 0:be.error)||"Could not load daemon trace"));else if(Array.isArray(Q==null?void 0:Q.trace)){N(""),f(Q.trace.slice(-120));const Se=Q.trace.reduce((De,Oe)=>Math.max(De,Number(Oe.ts||0)),M);Se>M&&m(Se)}else N(""),f([]);H(!1)}else H(!1),N(fe.reason instanceof Error?fe.reason.message:"Could not load daemon trace");x(Ks.list({limit:120})),b(Date.now())},[g,M,R,e,s,v]);o.useEffect(()=>{if(!e||(te(),!h))return;const T=setInterval(()=>{te()},3e3);return()=>clearInterval(T)},[h,te,e,$]),o.useEffect(()=>{if(h&&(ue.length>0||le.length>0||V.length>0||ve.length>0)){const T=ae.current?"smooth":"instant";setTimeout(()=>{var fe;(fe=ne.current)==null||fe.scrollIntoView({behavior:T}),ae.current=!0},50)}},[ue.length,le.length,V.length,ve.length,h]),o.useEffect(()=>{f([]),m(0),H(!0)},[v]);const me=((we=ce.latestIssue)==null?void 0:we.level)==="error"?"danger":((Te=ce.latestIssue)==null?void 0:Te.level)==="warn"?"warning":"good",re=C||U?"danger":h?"good":"neutral",je=o.useCallback(async()=>{var fe;const T=eb({daemonLogs:ue,daemonRawLines:le,trace:V,webEvents:ve});if(!T.trim()){st.showToast("복사할 visible logs가 없습니다.","info");return}try{await((fe=navigator.clipboard)==null?void 0:fe.writeText(T)),st.showToast("Visible logs를 클립보드에 복사했습니다.","success")}catch(be){st.showToast(be instanceof Error?be.message:"Could not copy visible logs","warning")}},[ue,le,V,ve]);return t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"Level"}),["debug","info","warn","error"].map(T=>t.jsx("button",{onClick:()=>{k(T),n([]),l(""),i("empty"),w(0),_(!0)},className:`machine-btn text-[10px] px-2 py-0.5 ${R===T?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:T.toUpperCase()},T)),t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider ml-3 mr-1",children:"Trace"}),Gx.map(T=>t.jsx("button",{onClick:()=>y(T.value),className:`machine-btn text-[10px] px-2 py-0.5 ${v===T.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:T.label},T.value))]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${ie.info})`},{id:"issues",label:`Issues (${ie.issues})`},{id:"all",label:`All (${ie.all})`}].map(T=>t.jsx("button",{type:"button",onClick:()=>j(T.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${I===T.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:T.label},T.id))}),t.jsx("input",{value:E,onChange:T=>L(T.target.value),placeholder:"Search visible logs, trace, events…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"}),t.jsx("button",{onClick:()=>{je()},className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:()=>S(T=>!T),className:`machine-btn ${h?"text-green-500 border-green-500/30":""}`,children:h?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:()=>z(T=>T+1),className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:()=>{n([]),l(""),i("empty"),f([]),x([]),w(0),m(0),b(null),P(""),N(""),_(!0),H(!0),Ks.clear()},className:"machine-btn",children:"Clear"})]})]}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${na(ce.issueCount>0?"warning":"good")}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Visible signals"}),t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:["daemon ",ue.length+le.length," · trace ",V.length," · web ",ve.length]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:E.trim()?`Filtered by “${E.trim()}”`:"Showing the latest buffered entries"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${na(me)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Attention needed"}),ce.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[ce.latestIssue.source," · ",ce.latestIssue.label]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:ce.latestIssue.detail}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-2",children:[ce.issueCount," warn/error signal(s) · ",Pi(ce.latestIssue.timestamp)]})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No recent warn/error signal"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use search or lower the log level if you need more context."})]})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${na(re)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Fetch status"}),t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:C||U?"Needs attention":h?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",Pi(p)]}),(C||U)&&t.jsxs("div",{className:"text-[11px] text-red-300 mt-2 space-y-1",children:[C&&t.jsxs("div",{children:["Daemon logs: ",C]}),U&&t.jsxs("div",{children:["Daemon trace: ",U]})]})]})]}),t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>W(T=>({...T,daemon:!T.daemon})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Daemon logs"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:a==="text"?`${le.length} visible raw line(s) from file fallback`:`${ue.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:q.daemon?"Hide":"Show"})]}),q.daemon&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[A&&!ce.hasAnyData&&!C&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!A&&C&&a==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:C}),!A&&a==="empty"&&!C&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),a==="text"&&le.length===0&&c&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:I==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),a==="structured"&&ue.length===0&&r.length>0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),a==="text"&&le.map((T,fe)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:T},`raw-${fe}`)),a!=="text"&&ue.map((T,fe)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Di(T.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(T.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:T.level==="error"?"ERR":T.level==="warn"?"WRN":T.level==="debug"?"DBG":"INF"}),t.jsx("span",{className:"break-words",children:T.message})]},`log-${fe}`))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>W(T=>({...T,trace:!T.trace})),children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Structured daemon trace",v==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[V.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:q.trace?"Hide":"Show"})]}),q.trace&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[B&&V.length===0&&!U&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!B&&U&&V.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:U}),!B&&V.length===0&&!U&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No trace entries match the current search.":v==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),V.map(T=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Di(T.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(T.ts).toLocaleTimeString()}),t.jsx("span",{children:T.level.toUpperCase()}),t.jsxs("span",{children:[T.category,".",T.stage]}),T.interactionId&&t.jsxs("span",{children:["ix=",T.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:vr(T.payload,360)||"No payload"})]},T.id))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>W(T=>({...T,web:!T.web})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Browser debug events"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[ve.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:q.web?"Hide":"Show"})]}),q.web&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[ve.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:E.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),ve.map(T=>t.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(T.ts).toLocaleTimeString()}),t.jsx("span",{children:T.kind}),T.topic&&t.jsxs("span",{children:["topic=",T.topic]}),T.interactionId&&t.jsxs("span",{children:["ix=",T.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:vr(T.payload,360)||"No payload"})]},T.id))]})]})]}),t.jsx("div",{ref:ne})]})}function aa(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function oa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ei(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 rb(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function nb(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 ab(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 ob({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=o.useState(""),[i,c]=o.useState(null),[l,u]=o.useState(!1),f=sl(e,{enabled:!!e,includeSessions:!0,limit:Go,intervalMs:_m}),d=f.diagnostics,x=f.loading,g=f.applyDiagnostics,w=o.useMemo(()=>fx({diagnostics:d,loading:x,refreshing:l,error:n}),[d,x,l,n]),M=o.useMemo(()=>new Map(s.map(L=>[L.sessionId||L.id,L])),[s]),m=o.useCallback(async()=>{if(e){u(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Go}),A=aa(L);if(!(A!=null&&A.success))throw new Error((A==null?void 0:A.error)||"Could not load hosted runtime diagnostics");g(A.diagnostics||A.result||null),a("")}catch(L){const A=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(A)}finally{u(!1)}}},[g,e,r]);o.useEffect(()=>{!e||d||x||l||m()},[d,x,e,m,l]);const p=o.useCallback(async(L,A)=>{const _=`${L}:${A.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${A.displayName}?
|
|
73
|
-
This will terminate the hosted runtime.`))){c(_);try{const B=await r(e,L,{sessionId:A.sessionId}),H=aa(B);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Session host action failed");const C=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";st.showToast(`Session host ${C}: ${A.displayName}`,"success"),await m()}catch(B){const H=B instanceof Error?B.message:"Session host action failed";st.showToast(H,"warning"),a(H)}finally{c(B=>B===_?null:B)}}},[e,m,r]),b=o.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
74
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){c("session_host_prune_duplicate_sessions");try{const A=await r(e,"session_host_prune_duplicate_sessions",{}),_=aa(A);if(!(_!=null&&_.success))throw new Error((_==null?void 0:_.error)||"Duplicate prune failed");const B=_.result||{},H=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,C=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;st.showToast(`Pruned ${H} duplicate runtime(s) across ${C} group(s)`,"success"),await m()}catch(A){const _=A instanceof Error?A.message:"Duplicate prune failed";st.showToast(_,"warning"),a(_)}finally{c(A=>A==="session_host_prune_duplicate_sessions"?null:A)}}},[e,m,r]),h=o.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((L,A)=>(A.lastActivityAt||0)-(L.lastActivityAt||0)),[d==null?void 0:d.sessions]),S=o.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:Ll(h),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,h]),R=S.liveRuntimes,k=S.recoverySnapshots,I=S.inactiveRecords,j=o.useMemo(()=>ab(R),[R]),v=o.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),y=o.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[d==null?void 0:d.recentLogs]),E=(L,A)=>{var z;const _=i===`session_host_resume_session:${L.sessionId}`,B=i===`session_host_restart_session:${L.sessionId}`,H=i===`session_host_stop_session:${L.sessionId}`,C=go(L.meta),P=M.get(L.sessionId),U=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,N=A==="recovery"?"Recover":"Resume",$=Rl(A);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:L.displayName||(P==null?void 0:P.cliName)||L.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${nb(L.lifecycle)}`,children:L.lifecycle}),C&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:L.workspaceLabel||(P==null?void 0:P.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((z=L.writeOwner)==null?void 0:z.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:rb(L.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(Ea,{size:11})," ",U]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Ei(L.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[A==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{p("session_host_resume_session",L)},children:_?`${N}ing…`:N}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!i,onClick:()=>{p("session_host_restart_session",L)},children:B?"Restarting…":"Restart"}),A==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!i,onClick:()=>{p("session_host_stop_session",L)},children:H?"Stopping…":"Stop"})]})]})},L.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(Zt,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Sp()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[j>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{b()},disabled:i==="session_host_prune_duplicate_sessions",children:i==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${j})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{m()},disabled:x||l,children:[t.jsx(Gs,{size:13}),x||l?"Refreshing…":"Refresh"]})]})]}),n&&!d&&t.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(ks,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),d&&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:d.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:k.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.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:Ei(d.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:oa(d.hostStartedAt)})]})]}),y&&t.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(ks,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:y.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[oa(y.timestamp),y.sessionId?` · ${y.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(yn,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$s("live")}),R.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:R.map(L=>E(L,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(Zt,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$s("recovery")}),k.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):t.jsx("div",{className:"space-y-2",children:k.map(L=>E(L,"recovery"))})]}),I.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:$s("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:I.map(L=>E(L,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),v.length===0?t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:v.map(L=>{var _;const A=h.find(B=>B.sessionId===L.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(A==null?void 0:A.displayName)||((_=M.get(L.sessionId))==null?void 0:_.cliName)||L.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:oa(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function ib({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 ia({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 ca({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 cb({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:i,onOpenConversation:c}){const l=n.slice(0,6),u=r.slice(0,4),d=dr(e,"0.8.93");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(ia,{icon:t.jsx(es,{size:13}),children:"Current Chats"}),t.jsx(ca,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:l.map(x=>{const g=ya(x);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(x),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:lt(x)}),g>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:wn(g)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Cs(x)})]},x.tabKey)})})})]}),u.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ia,{icon:t.jsx(Zi,{size:13}),children:"Recent Launches"}),t.jsx(ca,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(x=>{const{metaText:g,updatedLabel:w}=xl(x);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(x),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:x.label}),w&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},x.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(ia,{icon:t.jsx(ks,{size:13}),children:"Daemon Update"}),t.jsx(ca,{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:d?"Daemon update required":"Version mismatch detected"}),t.jsx("div",{className:"text-xs text-text-secondary leading-relaxed",children:d?"This machine is on an incompatible daemon version. Update it before starting more sessions.":"This machine is running a different daemon version than the current app. Update it before starting more sessions."}),t.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[t.jsx(Gs,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:"Update daemon"})]})]})})]})]})}function lb(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}const db={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 la({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:i,actions:c,sendDaemonCommand:l,initialWorkspaceId:u,initialWorkspacePath:f}){const d=Vs(),{handleLaunchIde:x,handleStopCli:g,handleRestartIde:w,handleStopIde:M,handleDetectIdes:m,launchingIde:p,launchingAgentType:b,addLog:h}=c,[S,R]=o.useState(null),k=o.useCallback(K=>{K&&d(as(K))},[d]),I=db[e],j=e==="ide",v=e==="acp",y=o.useMemo(()=>n.filter(K=>K.category===e&&(e==="ide"||K.installed!==!1)),[e,n]),E=o.useMemo(()=>new Map(y.map(K=>[K.type,K.displayName||K.type])),[y]),[L,A]=o.useState(""),[_,B]=o.useState(""),[H,C]=o.useState([]),[P,U]=o.useState(""),[N,$]=o.useState(""),[z,q]=o.useState([]),[W,ne]=o.useState(!1),[ae,ke]=o.useState(!1),[X,pe]=o.useState(""),[Y,J]=o.useState(!1),[ue,le]=o.useState(()=>wt()),[V,ve]=o.useState(null),[ie,ce]=o.useState(f?"__custom__":u||s.defaultWorkspaceId||""),[te,me]=o.useState(f||""),[re,je]=o.useState([]),[we,Te]=o.useState(!1),[T,fe]=o.useState(""),[be,Q]=o.useState([]),[Se,De]=o.useState(!1),[Oe,$e]=o.useState(""),Ue=o.useRef(null),[ze,mt]=o.useState(null),it=o.useRef("__home__"),[xt,Ve]=o.useState("__home__"),[pt,bt]=o.useState(!1),ct=o.useRef(0),Me=re.filter(K=>!a.some(ee=>ee.type===K&&St(ee.status)!=="stopped")),Je=o.useRef({});o.useEffect(()=>{s.defaultWorkspaceId&&!ie&&ce(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),o.useEffect(()=>{if(f){ce("__custom__"),me(f);return}u&&(ce(u),me(""))},[u,f]),o.useEffect(()=>{j||L&&(y.some(K=>K.type===L)||(A(""),$("")))},[y,j,L]);const Ye=(()=>{if(ie==="__custom__")return te.trim();if(!ie)return"";const K=(s.workspaces||[]).find(ee=>ee.id===ie);return(K==null?void 0:K.path)||""})(),Fe=o.useCallback(K=>{const ee=Je.current[K];ee&&(clearTimeout(ee),delete Je.current[K]),je(xe=>xe.includes(K)?xe.filter(Ee=>Ee!==K):xe)},[]),dt=o.useRef(new Set),vt=o.useCallback(async K=>{if(l){De(!0),$e("");try{const ee=await In(l,r,K);fe(ee.path),me(ee.path),Q(ee.directories)}catch(ee){$e(ee instanceof Error?ee.message:"Could not load folder")}finally{De(!1)}}},[r,l]),jt=o.useCallback(()=>{if(!l)return;ce("__custom__"),Te(!0);const K=a.map(xe=>xe.workspace),ee=Cn(s.platform,Nn(te.trim(),Ye,f,K,s.defaultWorkspacePath,(s.workspaces||[]).map(xe=>xe.path)));vt(ee)},[te,f,vt,s.defaultWorkspacePath,s.platform,s.workspaces,a,Ye,l]),Lt=o.useCallback(K=>{const ee=String(K.workspace||"").trim();if(!ee)return;const xe=(s.workspaces||[]).find(Ee=>Jr(Ee.path)===Jr(ee));if(xe){ce(xe.id),me("");return}ce("__custom__"),me(ee)},[s.workspaces]),Mt=o.useCallback(K=>{const ee=String(K.workspace||"").trim();if(!ee)return{workspaceId:null,workspacePath:"",useHome:!0};const xe=(s.workspaces||[]).find(Ee=>Jr(Ee.path)===Jr(ee));return xe?{workspaceId:xe.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:ee,useHome:!1}},[s.workspaces]),Ct=o.useCallback(async K=>{if(!l||!K||e!=="cli"){q([]),ne(!1),ke(!1),pe("");return}const ee=ct.current+1;ct.current=ee,ne(!0),pe("");try{const xe=await l(r,"list_saved_sessions",{providerType:K,kind:"cli",limit:30});if(ct.current!==ee)return;const Ee=(xe==null?void 0:xe.result)??xe;q(Array.isArray(Ee==null?void 0:Ee.sessions)?Ee.sessions:[])}catch(xe){if(ct.current!==ee)return;q([]),pe(xe instanceof Error?xe.message:"Could not load saved sessions")}finally{ct.current===ee&&(ne(!1),ke(!0))}},[e,r,l]),Dt=o.useMemo(()=>{if(e!=="cli"||!L)return null;const K=E.get(L)||L;return{routeId:r,daemonId:r,providerSessionId:N||void 0,transport:"pty",mode:"chat",agentName:K,agentType:L,status:"idle",title:K,messages:[],ideType:L,workspaceName:Ye,displayPrimary:K,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${L}`}},[e,r,E,Ye,N,L]),Z=o.useCallback(K=>{if(e==="ide"||!K){C([]);return}C(Ml(r,K))},[e,r]);o.useEffect(()=>{ct.current+=1,$(""),Z(L),ke(!1),q([]),pe(""),ne(!1)},[e,Z,Ct,L]);const Ke=o.useMemo(()=>z.find(K=>K.providerSessionId===N)||null,[z,N]);o.useEffect(()=>{if(!N)return;const K=z.find(ee=>ee.providerSessionId===N);K!=null&&K.canResume||$("")},[z,N]);const D=o.useCallback((K,ee)=>{Ue.current=ee,it.current=K.selectedWorkspaceKey||"__home__",Ve(K.selectedWorkspaceKey||"__home__"),mt(K)},[]),O=o.useCallback(()=>{Ue.current&&(bt(!0),Ue.current().finally(()=>{Ue.current=null,bt(!1),mt(null)}))},[]),F=o.useCallback(K=>{if(!K)return;je(xe=>xe.includes(K)?xe:[...xe,K]);const ee=Je.current[K];ee&&clearTimeout(ee),Je.current[K]=setTimeout(()=>{je(xe=>xe.includes(K)?xe.filter(Ee=>Ee!==K):xe),delete Je.current[K]},2e4)},[]);o.useEffect(()=>{for(const ee of a)St(ee.status)!=="stopped"&&(re.includes(ee.type)&&!dt.current.has(ee.type)&&(dt.current.add(ee.type),h("info",`${E.get(ee.type)||ee.type} launched`,!0)),Fe(ee.type));const K=new Set(a.filter(ee=>St(ee.status)!=="stopped").map(ee=>ee.type));dt.current.forEach(ee=>{!re.includes(ee)&&!K.has(ee)&&dt.current.delete(ee)})},[h,Fe,a,re,E]),o.useEffect(()=>()=>{Object.values(Je.current).forEach(clearTimeout),Je.current={}},[]);const[G,oe]=o.useState({}),[Ie,Le]=o.useState(null);o.useEffect(()=>{if(!j||!r||!l)return;(async()=>{try{const ee=await l(r,"get_ide_extensions",{}),xe=(ee==null?void 0:ee.result)||ee;xe!=null&&xe.success&&(xe!=null&&xe.ideExtensions)&&oe(xe.ideExtensions)}catch{}})()},[j,r,l]);const Ae=K=>j?ot(K.type):e==="cli"?K.cliName:K.acpName,We=j?s.detectedIdes||[]:[],Be=o.useCallback(async K=>{const ee=(K==null?void 0:K.type)||L,xe=(K==null?void 0:K.workspacePath)??Ye;if(j){await x(ee,xe?{workspace:xe}:void 0)&&F(ee);return}const Ee=await c.runLaunchCliCore({cliType:ee,dir:K!=null&&K.workspaceId?void 0:xe||void 0,workspaceId:(K==null?void 0:K.workspaceId)||void 0,useHome:(K==null?void 0:K.useHome)||!(K!=null&&K.workspaceId)&&!xe,argsStr:(K==null?void 0:K.argsStr)??(_||void 0),model:(K==null?void 0:K.model)??(v&&P||void 0),resumeSessionId:(K==null?void 0:K.resumeSessionId)||!v&&e==="cli"&&ee===L&&N||void 0});if(Ee.success||Ee.pending){const Re=(K==null?void 0:K.argsStr)??_;!j&&(Re!=null&&Re.trim())&&(Tl(r,ee,Re),Z(ee)),F(ee),Ee.success&&Ee.sessionId&&k(Ee.sessionId)}},[c,x,v,j,_,P,Z,F,r,k,Ye,N,L]),Ge=Oc(j?"ide":v?"acp":"cli",!j&&!v&&!!N),Ze=Wc(j?"ide":v?"acp":"cli",!j&&!v&&!!N),se=()=>{var Re;const K=j?ot(L):E.get(L)||L,ee=!j&&!v&&!!N,{options:xe,selectedKey:Ee}=vs({machine:s,currentWorkspaceId:ie&&ie!=="__custom__"?ie:null,currentWorkspacePath:Ye});D({title:ee?eo(K):xs("start-fresh",K),description:ee?to():bs("start-fresh"),confirmLabel:Ge,busyLabel:Ze,workspaceOptions:xe,selectedWorkspaceKey:Ee,details:[{label:"Mode",value:I.label},{label:"Provider",value:K},...!j&&e==="cli"&&N?[{label:"Resume",value:((Re=z.find(Ce=>Ce.providerSessionId===N))==null?void 0:Re.title)||N}]:[],...!j&&_.trim()?[{label:"Arguments",value:_.trim()}]:[],...v&&P.trim()?[{label:"Model",value:P.trim()}]:[]]},async()=>{const Ce=xe.find(et=>et.key===it.current);Ce!=null&&Ce.workspaceId?(ce(Ce.workspaceId),me("")):Ce!=null&&Ce.workspacePath?(ce("__custom__"),me(Ce.workspacePath)):(ce(""),me("")),await Be({workspaceId:(Ce==null?void 0:Ce.workspaceId)??null,workspacePath:(Ce==null?void 0:Ce.workspacePath)??"",useHome:!(Ce!=null&&Ce.workspaceId)&&!(Ce!=null&&Ce.workspacePath)})})},Ne=K=>{j?M(K):g(K.type,K.workspace,K.id)},_e=o.useCallback(async(K,ee,xe=!1)=>{if(K.mode===ee){xe&&K.sessionId&&k(K.sessionId);return}if(!l||!K.sessionId){xe&&K.sessionId&&k(K.sessionId);return}try{await l(r,"set_cli_view_mode",{targetSessionId:K.sessionId,cliType:K.type,mode:ee}),xe&&k(K.sessionId)}catch(Ee){const Re=uo(Ee);lo(Ee)?console.warn(Re?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",Ee instanceof Error?Ee.message:String(Ee)):console.error("Failed to switch CLI view mode:",Ee)}},[r,k,l]),rt=t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:ie,onChange:K=>{const ee=K.target.value;if(ce(ee),ee==="__custom__"&&l){jt();return}ee!=="__custom__"&&me("")},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(K=>t.jsxs("option",{value:K.id,children:[K.id===s.defaultWorkspaceId?"⭐ ":"",kn(K.path,K.label)]},K.id)),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:l?"📁 Select workspace…":"✏️ Custom path…"})]})}),ie==="__custom__"&&(l?t.jsx("button",{type:"button",className:"px-3 py-1.5 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] hover:border-accent-primary text-text-secondary hover:text-text-primary transition-colors",onClick:jt,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:te,onChange:K=>me(K.target.value),className:"px-3 py-1.5 rounded-md flex-1 min-w-[200px] text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors",autoFocus:!0}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:ie==="__custom__"?Ye?t.jsx("span",{className:"font-mono truncate block",title:Ye,children:Ye}):l?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":Ye?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:ie===s.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:Ye,children:Ye})]}):"No workspace selected. This launches in the home directory."})]});return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${I.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",I.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:j?We.length>0?We.map(K=>{const ee=a.find(et=>(et.type||"").toLowerCase()===(K.type||"").toLowerCase()&&St(et.status)!=="stopped"),xe=K.running||!!ee,Ee=!!ee&&ee.cdpConnected,Re=re.includes(K.type||K.id||""),Ce=L===(K.type||"");return t.jsxs("button",{onClick:()=>{if(Ee&&ee){const et=ee.sessionId;et?d(as(et),{state:{openRemoteForTabKey:et}}):d("/dashboard",{state:{openRemoteForTabKey:ee.id}});return}Re||A(et=>et===(K.type||"")?"":K.type||"")},disabled:!!p||Re,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Ee?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ce?"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:p&&p!==K.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(K.type)}),xe&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${Ee?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:K.name||ot(K.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${Ee?"text-green-400":Re?"text-orange-400":Ce?"text-accent-primary":"text-text-muted"}`,children:Ee?"Open Session":Re?"Starting...":Ce?"Configure":"Select"})]})]},K.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:m,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(Hd,{size:14})," Scan System"]})]}):y.length>0?y.map(K=>{const ee=L===K.type,xe=re.includes(K.type),Re=!!a.find(Ce=>Ce.type===K.type&&St(Ce.status)!=="stopped");return t.jsxs("button",{onClick:()=>A(Ce=>Ce===K.type?"":K.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${ee?"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:K.icon}),Re&&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:K.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${xe?"text-orange-400":ee?"text-accent-primary":"text-text-muted"}`,children:xe?"Starting...":ee?"Configure":"Select"})]})]},K.type)}):t.jsxs("div",{className:"col-span-full py-6 text-center bg-bg-primary/50 border border-dashed border-[#ffffff1a] rounded-xl text-xs text-text-muted",children:["No usable ",e.toUpperCase()," providers available.",t.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:"Set a custom executable path in Providers if the binary is installed outside the default location."})]})}),L&&(j?We.find(K=>K.type===L):y.find(K=>K.type===L))&&t.jsxs("div",{className:"mt-5 pt-5 border-t border-[#ffffff1a] flex flex-col gap-4 animate-in slide-in-from-top-2 fade-in duration-200",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:j?ot(L):E.get(L)||L})]}),rt,!j&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!v&&e==="cli"&&t.jsx(Pl,{busy:!!b||!!p||re.includes(L),savedSessionsLoading:W,savedSessionsError:X,selectedSession:Ke,onRefresh:()=>void Ct(L),onOpenHistory:()=>{L&&(J(!0),_l({hasLoadedInitialResults:ae,isLoading:W})&&Ct(L))},onClearSelection:()=>$("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[v&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:P,onChange:K=>U(K.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:_,onChange:K=>B(K.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),H.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:H.map(K=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>B(K),title:K,children:K},K))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:se,disabled:!!b||!!p||re.includes(L),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:b===L||p===L?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+re.filter(K=>!a.some(ee=>ee.type===K&&St(ee.status)!=="stopped")).length,")"]}),a.length===0&&Me.length===0?t.jsxs("div",{className:"py-7.5 px-5 text-center rounded-xl bg-bg-secondary border border-dashed border-border-subtle text-text-muted text-[13px] mb-5",children:["No ",I.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Me.map(K=>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(K)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:j?ot(K):E.get(K)||K}),t.jsx("div",{className:"text-[11px] text-text-muted",children:b===K?"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:${K}`)),a.map(K=>{const ee=j?K:null,xe=!j&&!v?K:null,Ee=St(K.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(K.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[Ae(K),(ee==null?void 0:ee.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",ee.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex gap-2",children:[t.jsx("span",{children:K.workspace||"—"}),(xe==null?void 0:xe.mode)&&t.jsx("span",{className:xe.mode==="chat"?"text-violet-400":"text-text-secondary",children:xe.mode==="chat"?"Chat view":"Terminal view"})]}),xe&&(xe.runtimeKey||xe.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[xe.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 ",xe.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 Re;(Re=navigator.clipboard)==null||Re.writeText(`adhdev attach ${xe.runtimeKey}`),R(xe.runtimeKey||null),window.setTimeout(()=>{R(Ce=>Ce===xe.runtimeKey?null:Ce)},1200)},children:S===xe.runtimeKey?"Copied":"Copy"})]}),xe.runtimeWriteOwner&&t.jsx("span",{style:{color:xe.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:xe.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:lb(xe.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Ee==="stopped"?"bg-red-500/[0.08] text-red-500":Ee==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:Ee}),j&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Re=K.sessionId;if(Re){d(as(Re),{state:{openRemoteForTabKey:Re}});return}d("/dashboard",{state:{openRemoteForTabKey:K.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(Pt,{size:13})}),t.jsx("button",{onClick:()=>{const Re=K.workspace||"",{options:Ce,selectedKey:et}=vs({machine:s,currentWorkspacePath:Re});D({title:xs("restart-ide",ot(K.type)),description:bs("restart-ide"),confirmLabel:Us("restart-ide"),busyLabel:zs("restart-ide"),workspaceOptions:Ce,selectedWorkspaceKey:et,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:ot(K.type)}]},async()=>{const It=Ce.find(qt=>qt.key===it.current),Pe=(It==null?void 0:It.workspacePath)??"";if(Pe&&Pe!==Re){await Be({type:K.type,workspacePath:Pe});return}await w(K)})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-orange-500/20 text-orange-400 transition-colors cursor-pointer",title:"Restart",children:t.jsx(Gs,{size:14})})]}),v&&t.jsx("button",{onClick:()=>{const Re=K.sessionId;Re&&k(Re)},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:!K.sessionId,children:t.jsx(es,{size:14})}),xe&&Ee!=="stopped"&&t.jsxs(t.Fragment,{children:[xe.mode&&t.jsx(Ja,{mode:xe.mode,onChange:Re=>void _e(xe,Re,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Re=K.sessionId;Re&&k(Re)},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:!K.sessionId,children:xe.mode==="chat"?t.jsx(es,{size:14}):t.jsx(Pt,{size:13})})]}),Ee==="stopped"?t.jsx("button",{onClick:()=>{const Re=K.workspace||"",Ce=j?ot(K.type):Ae(K),{options:et,selectedKey:It}=vs({machine:s,currentWorkspacePath:Re});D({title:xs("restart-stopped",Ce),description:bs("restart-stopped"),confirmLabel:Us("restart-stopped"),busyLabel:zs("restart-stopped"),workspaceOptions:et,selectedWorkspaceKey:It,details:[{label:"Mode",value:I.label},{label:"Provider",value:Ce}]},async()=>{const Pe=et.find(qt=>qt.key===it.current);await Be({type:K.type,workspaceId:(Pe==null?void 0:Pe.workspaceId)??null,workspacePath:(Pe==null?void 0:Pe.workspacePath)??"",useHome:!(Pe!=null&&Pe.workspaceId)&&!(Pe!=null&&Pe.workspacePath)})})},disabled:re.includes(K.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:re.includes(K.type)?"⏳":t.jsx(Ka,{size:14})}):t.jsx("button",{onClick:()=>Ne(K),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-red-500/20 text-red-400 transition-colors cursor-pointer",title:"Stop",children:t.jsx(At,{size:14})})]})]}),ee&&ee.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:ee.aiAgents.map(Re=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${lc(Re.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Re.name," · ",St(Re.status)]},Re.id))}),ee&&(G[ee.type]||[]).length>0&&l&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(G[ee.type]||[]).map(Re=>t.jsxs("button",{disabled:Ie===`${ee.type}.${Re.type}`,onClick:async()=>{const Ce=`${ee.type}.${Re.type}`;Le(Ce);try{await l(r,"set_ide_extension",{ideType:ee.type,extensionType:Re.type,enabled:!Re.enabled}),oe(et=>({...et,[ee.type]:(et[ee.type]||[]).map(It=>It.type===Re.type?{...It,enabled:!It.enabled}:It)}))}catch(et){console.error("Extension toggle failed:",et)}finally{Le(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 ${Re.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 ${Re.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Re.name,t.jsx("span",{className:"text-[9px] font-normal",children:Re.enabled?"ON":"OFF"})]},Re.type))})]})]},K.id)})]}),we&&l&&t.jsx(An,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:T,directories:be,busy:Se,error:Oe,confirmLabel:"Use this folder",onClose:()=>Te(!1),onNavigate:K=>{vt(K)},onConfirm:K=>{me(K),ce("__custom__"),Te(!1)}}),ze&&t.jsx(xo,{title:ze.title,description:ze.description,details:ze.details,workspaceOptions:ze.workspaceOptions,selectedWorkspaceKey:xt,onWorkspaceChange:K=>{it.current=K,Ve(K)},confirmLabel:ze.confirmLabel,busyLabel:ze.busyLabel,busy:pt,onConfirm:O,onCancel:()=>{Ue.current=null,mt(null)}}),Y&&Dt&&t.jsx(so,{activeConv:Dt,ides:[],isCreatingChat:!1,isRefreshingHistory:W,savedSessions:z,isSavedSessionsLoading:W,isResumingSavedSessionId:V,savedHistoryFilters:ue,onSavedHistoryFiltersChange:le,onClose:()=>J(!1),onNewChat:()=>{$(""),J(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Ct(L)},onResumeSavedSession:K=>{if(!K.canResume||V)return;const ee=Mt(K);$(K.providerSessionId),Lt(K),ve(K.providerSessionId),J(!1),Be({type:K.providerType,workspaceId:ee.workspaceId,workspacePath:ee.workspacePath,useHome:ee.useHome,resumeSessionId:K.providerSessionId}).finally(()=>{ve(xe=>xe===K.providerSessionId?null:xe)})}})]})}const $i=[{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 ub({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:i,actions:c,getIcon:l,initialCategory:u="ide",initialWorkspaceId:f,initialWorkspacePath:d,sendDaemonCommand:x}){var m;const[g,w]=o.useState(u);o.useEffect(()=>{w(u)},[u]);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:$i.map(p=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${g===p.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>w(p.id),children:[t.jsx("span",{children:p.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${g===p.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:M[p.id]})]},p.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(m=$i.find(p=>p.id===g))==null?void 0:m.helper})]}),g==="ide"&&t.jsx(la,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:d}),g==="cli"&&t.jsx(la,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:d}),g==="acp"&&t.jsx(la,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:i,getIcon:l,actions:c,sendDaemonCommand:x,initialWorkspaceId:f,initialWorkspacePath:d})]})}function mb({onNicknameSynced:e}={}){var ve,ie,ce,te,me,re,je,we,Te;const{id:s}=wd(),r=Vs(),n=Pa(),{sendCommand:a}=Tt(),i=Nr(),c=tl(),l=Rc(),u=l.ides||[],f=l.initialLoaded??!0,d=u.find(T=>T.id===s&&T.type==="adhdev-daemon"),x=u.some(T=>T.type==="adhdev-daemon"),[g,w]=o.useState("workspace"),[M,m]=o.useState("ide"),p=o.useRef(null),[b,h]=o.useState(null),S=o.useRef("__home__"),[R,k]=o.useState("__home__"),[I,j]=o.useState(!1),v=o.useRef(null);o.useEffect(()=>{!s||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||i(s,{minFreshMs:3e4}).catch(()=>{})},[i,d,s]),o.useEffect(()=>{if(!s||!d||g!=="overview")return;const T=d.machine;(typeof(T==null?void 0:T.cpus)!="number"||typeof(T==null?void 0:T.totalMem)!="number"||typeof(T==null?void 0:T.arch)!="string"||typeof(T==null?void 0:T.release)!="string")&&c(s,{minFreshMs:3e4}).catch(()=>{})},[g,c,d,s]),gf(s&&g==="overview"?[s]:[],{enabled:g==="overview",intervalMs:Mm});const y=()=>{if(x){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},E=Kx({machineId:s,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:v});o.useEffect(()=>st.onToast(fe=>{l.setToasts(Q=>{if(Q.some(Oe=>Oe.message===fe.message&&fe.timestamp-Oe.timestamp<3e3))return Q;const De={id:fe.id,message:fe.message,type:fe.type,timestamp:fe.timestamp,targetKey:fe.targetKey,actions:fe.actions};return[...Q.slice(-4),De]});const be=fe.duration||5e3;setTimeout(()=>l.setToasts(Q=>Q.filter(Se=>Se.id!==fe.id)),be)}),[l]);const L=(d==null?void 0:d.availableProviders)||[],A={};for(const T of L)A[T.type]=T.icon;const _=T=>A[T]||"",B=d?{id:d.id,hostname:dc(d,{fallbackId:d.id}),platform:((ve=d.machine)==null?void 0:ve.platform)||"unknown",arch:((ie=d.machine)==null?void 0:ie.arch)||"",cpus:((ce=d.machine)==null?void 0:ce.cpus)||0,totalMem:((te=d.machine)==null?void 0:te.totalMem)||0,freeMem:(me=d.machine)==null?void 0:me.freeMem,availableMem:(re=d.machine)==null?void 0:re.availableMem,loadavg:(je=d.machine)==null?void 0:je.loadavg,uptime:(we=d.machine)==null?void 0:we.uptime,release:((Te=d.machine)==null?void 0:Te.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,H=u.filter(T=>T.daemonId===s&&T.type!=="adhdev-daemon").filter(T=>!br(T)&&!Ps(T)).map(T=>({id:T.id,sessionId:T.sessionId,type:T.type,version:T.version||"",instanceId:T.instanceId||"",status:T.status,workspace:T.workspace||null,terminals:T.terminals||0,aiAgents:Eu(T.aiAgents||(T.agents||[]).map(fe=>({id:fe.name,name:fe.name,status:fe.status,version:fe.version}))),activeChat:T.activeChat||null,chats:T.chats||[],childSessions:T.childSessions||[],cdpConnected:T.cdpConnected||!1,daemonId:s})),C=u.filter(T=>T.daemonId===s&&br(T)).map(T=>({id:T.id,sessionId:T.sessionId,type:T.type,cliName:T.cliName||T.type,status:T.status,workspace:T.workspace||"",activeChat:T.activeChat||null,providerSessionId:T.providerSessionId,mode:T.mode,runtimeKey:T.runtimeKey,runtimeDisplayName:T.runtimeDisplayName,runtimeWorkspaceLabel:T.runtimeWorkspaceLabel,runtimeWriteOwner:T.runtimeWriteOwner||null,runtimeAttachedClients:T.runtimeAttachedClients||[],daemonId:s})),P=u.filter(T=>T.daemonId===s&&Ps(T)).map(T=>({id:T.id,sessionId:T.sessionId,type:T.type,acpName:T.cliName||T.type,status:T.status,workspace:T.workspace||"",activeChat:T.activeChat||null,providerSessionId:T.providerSessionId,daemonId:s})),U=d?_t(d,{fallbackId:s}):"",N="workspace",$=n.state,z=$==null?void 0:$.initialMachineTab,q=$==null?void 0:$.initialWorkspaceCategory,W=$==null?void 0:$.initialWorkspaceId,ne=$==null?void 0:$.initialWorkspacePath,ae=z==="ides"||z==="clis"||z==="acps"?"workspace":z||N,ke=z==="ides"?"ide":z==="clis"?"cli":z==="acps"?"acp":q,X=[...H.map(T=>{var fe,be,Q,Se,De;return{id:`ide:${T.type}:${T.workspace||""}`,label:((fe=T.activeChat)==null?void 0:fe.title)||T.type,kind:"ide",providerType:T.type,subtitle:T.workspace||void 0,workspace:T.workspace||void 0,lastLaunchedAt:((De=(Se=(Q=(be=T.activeChat)==null?void 0:be.messages)==null?void 0:Q.at)==null?void 0:Se.call(Q,-1))==null?void 0:De.timestamp)||0}}),...C.map(T=>{var fe,be,Q,Se,De;return{id:`cli:${T.type}:${T.workspace||""}`,label:((fe=T.activeChat)==null?void 0:fe.title)||T.cliName,kind:"cli",providerType:T.type,providerSessionId:T.providerSessionId,subtitle:T.workspace||void 0,workspace:T.workspace||void 0,lastLaunchedAt:((De=(Se=(Q=(be=T.activeChat)==null?void 0:be.messages)==null?void 0:Q.at)==null?void 0:Se.call(Q,-1))==null?void 0:De.timestamp)||0}}),...P.map(T=>{var fe,be,Q,Se,De;return{id:`acp:${T.type}:${T.workspace||""}`,label:((fe=T.activeChat)==null?void 0:fe.title)||T.acpName,kind:"acp",providerType:T.type,providerSessionId:T.providerSessionId,subtitle:Ss(T.summaryMetadata)||T.workspace||void 0,workspace:T.workspace||void 0,lastLaunchedAt:((De=(Se=(Q=(be=T.activeChat)==null?void 0:be.messages)==null?void 0:Q.at)==null?void 0:Se.call(Q,-1))==null?void 0:De.timestamp)||0}})].sort((T,fe)=>(fe.lastLaunchedAt||0)-(T.lastLaunchedAt||0)),pe=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(T=>({id:T.id,label:T.title||T.providerName||T.providerType,kind:T.kind,providerType:T.providerType,providerSessionId:T.providerSessionId,subtitle:Ss(T.summaryMetadata)||T.workspace||void 0,workspace:T.workspace,summaryMetadata:T.summaryMetadata,lastLaunchedAt:T.lastLaunchedAt})):X,Y=o.useMemo(()=>{var fe;const T=((fe=l.connectionStates)==null?void 0:fe[s||""])||void 0;return u.filter(be=>be.daemonId===s&&be.type!=="adhdev-daemon").flatMap(be=>ro(be,{},{connectionStates:s&&T?{[s]:T}:void 0,defaultConnectionState:T})).filter(be=>!(be.transport==="pty"&&be.mode==="terminal")).sort((be,Q)=>ya(Q)-ya(be))},[u,l.connectionStates,s]),J=o.useCallback(T=>{const fe=Ga(T);fe&&r(as(fe))},[r]),ue=o.useCallback(()=>{p.current&&(j(!0),p.current().finally(()=>{p.current=null,j(!1),h(null)}))},[]),le=o.useCallback(T=>{if(!B)return;const{options:fe,selectedKey:be}=vs({machine:B,currentWorkspacePath:T.workspace}),Q=async()=>{m(T.kind),w("workspace")};p.current=async()=>{const Se=fe.find($e=>$e.key===S.current),De=(Se==null?void 0:Se.workspacePath)??null,Oe=(Se==null?void 0:Se.workspaceId)??null;if(T.kind==="ide"&&T.providerType){await E.handleLaunchIde(T.providerType,De?{workspace:De}:void 0);return}if((T.kind==="cli"||T.kind==="acp")&&T.providerType){await E.runLaunchCliCore({cliType:T.providerType,dir:Oe?void 0:De||"",workspaceId:Oe||void 0,model:T.kind==="acp"&&mc(T.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:T.providerSessionId});return}await Q()},S.current=be,k(be),h({title:T.kind==="ide"?xs("restart-ide",T.label):T.providerSessionId?eo(T.label):xs("start-fresh",T.label),description:T.kind==="ide"?bs("restart-ide"):T.providerSessionId?to():bs("start-fresh"),confirmLabel:T.kind==="ide"?Us("restart-ide"):T.providerSessionId?pn(!0):Us("start-fresh"),busyLabel:T.kind==="ide"?zs("restart-ide"):T.providerSessionId?Qa(!0):zs("start-fresh"),workspaceOptions:fe,details:[{label:"Mode",value:T.kind.toUpperCase()},...T.providerType?[{label:"Provider",value:T.providerType}]:[]]})},[E,B]);if(o.useEffect(()=>{w(ae)},[N,ae,s]),o.useEffect(()=>{ke&&m(ke)},[ke,s]),!B)return f?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:y,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 V=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Pt,{size:14})," Workspace"]}),count:H.length+C.length+P.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Zt,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(gn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Fd,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Od,{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:y,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:[E.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:E.nicknameInput,onChange:T=>E.setNicknameInput(T.target.value),onKeyDown:T=>{T.key==="Enter"&&E.handleSaveNickname(),T.key==="Escape"&&E.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:E.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:()=>E.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:()=>{E.setEditingNickname(!0),E.setNicknameInput(B.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:[B.platform," · ",B.arch]}),t.jsxs("span",{children:[B.cpus," cores"]}),(d==null?void 0:d.version)&&t.jsxs("span",{children:["v",d.version]}),B.p2p.available&&t.jsxs("span",{children:["P2P ",B.p2p.state==="connected"?"connected":B.p2p.state]}),B.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:B.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:V.map(T=>t.jsxs("button",{onClick:()=>w(T.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${g===T.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[T.label,T.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${g===T.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:T.count})]},T.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:[g==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(cb,{machineEntry:d,providers:L,recentLaunches:pe,currentConversations:Y,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",{})}catch{}},onOpenRecent:le,onOpenConversation:J}),t.jsx(ub,{machine:B,machineId:s,providers:L,ideSessions:H,cliSessions:C,acpSessions:P,actions:E,getIcon:_,initialCategory:M,initialWorkspaceId:W,initialWorkspacePath:ne,sendDaemonCommand:a})]}),g==="providers"&&t.jsx(Vx,{machineId:s,providers:L,sendDaemonCommand:a}),g==="overview"&&t.jsx(Bx,{machineId:s,machine:B,ideSessions:H,cliSessions:C,acpSessions:P,actions:E,sendDaemonCommand:a}),g==="session-host"&&t.jsx(ob,{machineId:s,cliSessions:C,sendDaemonCommand:a}),g==="logs"&&t.jsx(sb,{machineId:s,sendDaemonCommand:a})]})})}),E.launchPick&&B&&t.jsx(ib,{machine:B,launchPick:E.launchPick,actions:E}),b&&t.jsx(xo,{title:b.title,description:b.description,details:b.details,workspaceOptions:b.workspaceOptions,selectedWorkspaceKey:R,onWorkspaceChange:T=>{S.current=T,k(T)},confirmLabel:b.confirmLabel,busyLabel:b.busyLabel,busy:I,onConfirm:ue,onCancel:()=>{p.current=null,h(null)}}),t.jsx(Hc,{toasts:l.toasts||[],onDismiss:T=>l.setToasts(fe=>fe.filter(be=>be.id!==T)),onClickToast:T=>{T.targetKey&&r(as(T.targetKey))}}),t.jsx("style",{children:`
|
|
75
|
-
@keyframes toast-in {
|
|
76
|
-
from { opacity: 0; transform: translateX(40px); }
|
|
77
|
-
to { opacity: 1; transform: translateX(0); }
|
|
78
|
-
}
|
|
79
|
-
`})]})}function vo(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function pb(e){if(typeof window>"u")return e;const s=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=vo();return r&&!s.searchParams.has("token")&&s.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?s.toString():`${s.pathname}${s.search}${s.hash}`}async function Ut(e,s){return await fetch(pb(e),{credentials:"same-origin",...s})}function Kl(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class fb{constructor(){qe(this,"adapters",new Map);qe(this,"states",new Map);qe(this,"runtimeListeners",new Map);qe(this,"screenshotCallbacks",new Map);qe(this,"statusCallbacks",new Set)}resolveDaemonId(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const a=this.runtimeListeners.get(s);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r){if(!r)return;const n=await Ut(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`);if(!n.ok)return;const a=await n.json();this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof a.seq=="number"?a.seq:0,text:typeof a.text=="string"?a.text:"",truncated:!!a.truncated,cols:typeof a.cols=="number"?a.cols:void 0,rows:typeof a.rows=="number"?a.rows:void 0})}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Xt=new fb;function hb(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=vo();return r?`${s}?token=${encodeURIComponent(r)}`:s}const Qr=hb(),Ki=3e3,xb=3e4;let zt=null,bb=0;const bn=new Map;let ds=null,mr=null;function Bi(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function rr(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function gb(e){return e==="connected"?"connected":e}async function an(e,s,r){const n=Ep(e,r||{}),a=zt;if(a&&a.readyState===WebSocket.OPEN){const i=`req_${++bb}_${Date.now()}`;return new Promise((c,l)=>{const u=setTimeout(()=>{bn.delete(i),l(new Error(`WS command timeout: ${s}`))},3e4);bn.set(i,{resolve:f=>{clearTimeout(u),c(f)},reject:f=>{clearTimeout(u),l(f)}}),a.send(JSON.stringify({type:"command",requestId:i,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function Ta(e,s){const r=zt;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}class yb{constructor(s){qe(this,"daemonId");qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(zt==null?void 0:zt.readyState)===WebSocket.OPEN}get connectionState(){return(zt==null?void 0:zt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return an(this.daemonId,s,r)}async sendInput(s,r){return an(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,ds&&(clearInterval(ds),ds=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await an(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());Xt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ds=setInterval(r,2e3)}stopScreenshots(s){ds&&(clearInterval(ds),ds=null)}}let Bt=null;function vb(e){return(!Bt||Bt.daemonId!==e)&&(Bt=new yb(e)),Bt}function wb({children:e}){const s=o.useRef(fr()),r=fr();s.current=r;const{setUserName:n}=js(),a=o.useRef(n);a.current=n;const i=o.useRef(null),c=o.useRef(null),[,l]=o.useState("disconnected"),u=o.useCallback((m,p)=>{l(m),mr==null||mr(m,p)},[]),f=o.useRef(null),d=o.useRef(),x=o.useRef(Ki),g=o.useRef(!0),w=o.useRef(!1),M=o.useRef("initial_connect");return o.useEffect(()=>{g.current=!0,w.current=!1;function m(){var h,S;if(!g.current||((h=f.current)==null?void 0:h.readyState)===WebSocket.OPEN||((S=f.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Qr}...`),rr("connect_attempt",{url:Qr,reason:M.current,delayMs:x.current});let b;try{b=new WebSocket(Qr)}catch(R){console.error("[Standalone WS] Failed to create WebSocket:",R),p();return}f.current=b,b.onopen=()=>{if(!g.current){b.close();return}u("connected"),x.current=Ki,rr("open",{url:Qr,reason:M.current}),os.resubscribeAll({sendData:Ta}),console.log("[Standalone WS] Connected")},zt=b,b.onmessage=R=>{var k,I;try{const j=JSON.parse(R.data);if((j.type==="command_result"||j.type==="error")&&j.requestId){const v=bn.get(j.requestId);v&&(bn.delete(j.requestId),j.type==="error"?v.reject(new Error(((k=j.data)==null?void 0:k.message)||"Command failed")):v.resolve(j.data));return}if(j.type==="session_output"){const v=j.sessionId||j.cliId||j.cliType;v&&Xt.emitSessionOutput(v,typeof j.data=="string"?j.data:"",typeof j.seq=="number"?j.seq:void 0);return}if(j.type==="runtime_snapshot"){Xt.emitRuntimeSnapshot(j.sessionId,typeof j.text=="string"?j.text:"",typeof j.seq=="number"?j.seq:0,!!j.truncated);return}if(j.type==="topic_update"){const v=j.update;v&&os.publish(v);return}if(j.type==="status"||j.type==="initial_state"){const v=j.data;if(!v)return;const{injectEntries:y,markLoaded:E,getIdes:L}=s.current,A=v.instanceId||"standalone",_=L().find(C=>C.id===A),B=vb(A);Xt.register(A,B),Xt.setState(A,"connected"),u("connected",A),Xt.emitStatus(A,v);const H=mn(v,{daemonId:A,existingDaemon:_,existingEntries:L()});Bi("ws_status",{type:j.type,daemonId:A,sessions:(v.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(v.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Bi("entries",{daemonId:A,entries:H.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),H.length>0&&y(H,{authoritativeDaemonIds:[A]}),E(),c.current!==A&&((I=i.current)==null||I.call(i),c.current=A,i.current=os.subscribe({sendData:Ta},A,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${A}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const P=s.current.getIdes(),U=P.find($=>$.id===A),N=mn(C.status,{daemonId:A,existingDaemon:U,existingEntries:P,timestamp:C.timestamp});N.length>0&&s.current.injectEntries(N),C.userName&&a.current&&a.current(C.userName)}))}}catch(j){console.error("[Standalone WS] Parse error:",j)}},b.onclose=R=>{g.current&&(Bt==null||Bt.stopScreenshots(),Bt&&Xt.setState(Bt.daemonId,"disconnected"),u("disconnected"),f.current=null,M.current=`close:${R.code}${R.wasClean?":clean":":unclean"}`,rr("close",{code:R.code,reason:R.reason||"",wasClean:R.wasClean}),p())},b.onerror=R=>{w.current||!g.current||(M.current="error",rr("error",{message:R instanceof Event?"event":String(R),readyState:b.readyState}),console.warn("[Standalone WS] Error, will reconnect:",R))}}function p(){if(!g.current)return;clearTimeout(d.current);const b=x.current;console.log(`[Standalone WS] Reconnecting in ${b}ms...`),rr("schedule_reconnect",{reason:M.current,delayMs:b}),d.current=setTimeout(()=>{x.current=Math.min(x.current*1.5,xb),m()},b)}return m(),()=>{var b;g.current=!1,w.current=!0,(b=i.current)==null||b.call(i),i.current=null,c.current=null,clearTimeout(d.current),f.current&&(f.current.onerror=null,f.current.onclose=null,f.current.close(),f.current=null,zt=null),Bt&&(Bt.stopScreenshots(),Xt.unregister(Bt.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function jb({children:e}){const[s,r]=o.useState("disconnected"),[n,a]=o.useState(null);o.useEffect(()=>(mr=(c,l)=>{r(c),l&&a(l)},()=>{mr=null}),[]);const i=o.useMemo(()=>{const c=s==="connected",l=gb(s),u={};return n&&(u[n]=l),u.standalone=l,{wsStatus:s,isConnected:c,connectionStates:u}},[s,n]);return t.jsx(Td,{connectionOverrides:i,children:t.jsx(wb,{children:e})})}const Bl="adhdev_standalone_font_preferences",ws={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Ln=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],wr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],kb=new Set(Ln.map(e=>e.id)),Sb=new Set(wr.map(e=>e.id));function Vt(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:on("chat",s.chat),code:on("code",s.code),terminal:on("terminal",s.terminal)}}function on(e,s){const r=ws[e],n=s&&typeof s=="object"&&!Array.isArray(s)?s:{},a=typeof n.preset=="string"?n.preset.trim():"",i=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?kb:Sb).has(a)?a==="custom"?i?{preset:"custom",customFamily:i}:r:{preset:a}:r}function cn(e,s){var a;const r=on(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Ln:wr;return((a=n.find(i=>i.id===r.preset))==null?void 0:a.family)||n[0].family}function Nb(e){const s=Vt(e),r=cn("chat",s.chat),n=cn("code",s.code),a=cn("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ms(e,s=document.documentElement){const r=Vt(e),n=Nb(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,i]of Object.entries(n))s.style.setProperty(a,i);return r}function La(e){const s=Vt(e);try{localStorage.setItem(Bl,JSON.stringify(s))}catch{}return s}function Cb(){try{const e=localStorage.getItem(Bl);if(e)return Vt(JSON.parse(e))}catch{}return ws}function Ib(){return ms(Cb())}function nr(e,s){var n;const r=e==="chat"?Ln:wr;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const Ab=[{id:"dashboard",path:"/dashboard",icon:t.jsx(qi,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(Zt,{}),label:"Burrow"},{id:"settings",path:"/settings",icon:t.jsx(gn,{}),label:"Settings"}];function Mb({children:e}){const s=Vs(),r=Pa(),[n,a]=o.useState(!1),[i,c]=o.useState(()=>{try{return localStorage.getItem("sidebar-collapsed")==="1"}catch{return!1}}),l=d=>{s(d),a(!1)},u=()=>{c(d=>{const x=!d;try{localStorage.setItem("sidebar-collapsed",x?"1":"0")}catch{}return x})},f=d=>`nav-item${r.pathname.startsWith(d)?" 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:d=>d.key==="Escape"&&a(!1)}),t.jsxs("aside",{className:`sidebar ${n?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsxs("div",{className:`sidebar-logo ${i?"justify-center gap-0":""}`,children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&t.jsx("span",{children:"ADHDev"})]}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:()=>a(!1),children:t.jsx(At,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:Ab.map(d=>t.jsxs("div",{className:f(d.path),id:`nav-${d.id}`,onClick:()=>l(d.path),title:i?d.label:void 0,children:[t.jsx("span",{className:"nav-icon",children:d.icon}),!i&&d.label]},d.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(Yi,{})}),!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(Xi,{})}),!i&&"About"]}),!i&&t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.8.93"]}),t.jsx(qp,{collapsed:i}),t.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:u,title:i?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&t.jsx("span",{className:"text-xs",children:"Collapse"})]})]})]}),t.jsx("main",{className:"main-content relative",children:t.jsx("div",{className:"main-content-inner",children:e})})]})}const Tb=[{icon:t.jsx(Zt,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(es,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(Ji,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Pt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(hr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(Yi,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Lb=[{icon:t.jsx(Vd,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(qi,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(vn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Bd,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(Ea,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Wd,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Rb=[{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 _b(){return t.jsxs(qc,{icon:t.jsx(Xi,{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.93"]}),children:[t.jsx(Rt,{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(Rt,{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:Tb.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(Rt,{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:zc.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:Gc.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:Vc.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(Rt,{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:Lb.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(Rt,{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:Rb.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(Yc,{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(su,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function da(e,s,r){return{...e,[s]:r}}function ua({surface:e,title:s,description:r,value:n,options:a,onChange:i}){return t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:s}),t.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx("select",{className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",value:n.preset,onChange:c=>{const l=c.target.value;i(l==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:l})},children:a.map(c=>t.jsx("option",{value:c.id,children:c.label},c.id))}),n.preset==="custom"&&t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:n.customFamily||"",onChange:c=>i({preset:"custom",customFamily:c.target.value})}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",t.jsx("span",{className:"font-mono break-all",children:cn(e,n)})]})]})]})}function Pb({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:i,onSave:c,onResetToSaved:l,onResetToDefaults:u}){const f=JSON.stringify(e)!==JSON.stringify(s);return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below."}),n&&t.jsx("div",{className:"rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-300",children:n}),a&&t.jsx("div",{className:"rounded-xl border border-green-500/30 bg-green-500/10 px-4 py-3 text-sm text-green-300",children:a}),t.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[t.jsx(ua,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Ln,onChange:d=>i(da(e,"chat",d))}),t.jsx(ua,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:wr,onChange:d=>i(da(e,"code",d))}),t.jsx(ua,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:wr,onChange:d=>i(da(e,"terminal",d))})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),t.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",nr("chat",e.chat.preset)," · Code: ",nr("code",e.code.preset)," · Terminal: ",nr("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",nr("chat",ws.chat.preset)," / ",nr("code",ws.code.preset)]})]}),t.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:t.jsxs("div",{className:"chat-container-content",children:[t.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:t.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[t.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[t.jsx("span",{className:"chat-sender",children:"Hermes"}),t.jsx("span",{className:"chat-time",children:"now"})]}),t.jsxs("div",{className:"chat-markdown",children:[t.jsxs("p",{children:["Readable prose, ",t.jsx("strong",{children:"bold text"}),", and ",t.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),t.jsx("pre",{children:t.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),t.jsxs("div",{className:"chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"▸"}),t.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),t.jsxs("div",{className:"chat-msg-terminal",children:[t.jsx("div",{className:"chat-msg-header",children:"Terminal"}),t.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:c,disabled:r||!f,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Saving…":"Save font settings"}),t.jsx("button",{type:"button",onClick:l,disabled:r||!f,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Revert to saved"}),t.jsx("button",{type:"button",onClick:u,disabled:r,className:"rounded-lg border border-border-subtle bg-bg-glass px-3 py-2 text-sm font-medium text-text-secondary disabled:opacity-50 disabled:cursor-not-allowed",children:"Reset to defaults"})]})]})}function Db(){const{ides:e}=js(),s=e.find(Y=>Y.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=Tt(),{userName:a}=js(),[i,c]=o.useState(a||""),[l,u]=o.useState(null),[f,d]=o.useState(null),[x,g]=o.useState(ws),[w,M]=o.useState(!1),[m,p]=o.useState(""),[b,h]=o.useState(""),[S,R]=o.useState("127.0.0.1"),[k,I]=o.useState(""),[j,v]=o.useState(""),[y,E]=o.useState(""),[L,A]=o.useState(""),[_,B]=o.useState(""),[H,C]=o.useState(!1),P=async()=>{const J=await(await Ut("/auth/session")).json();u(J)},U=async()=>{const J=await(await Ut("/api/v1/standalone/preferences")).json();d(J),R(J.standaloneBindHost);const ue=Vt(J.standaloneFontPreferences);g(ue),ms(ue),La(ue)};o.useEffect(()=>{a!==void 0&&c(a)},[a]),o.useEffect(()=>{Promise.all([P(),U()]).catch(Y=>{A(Y instanceof Error?Y.message:String(Y))})},[]),o.useEffect(()=>{ms(x)},[x]);const N=Y=>{const J=Y.target.value.trim();s!=null&&s.id&&J!==a&&n(s.id,"set_user_name",{userName:J}).catch(console.error)},[$,z]=o.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),q=Y=>{z(Y);try{localStorage.setItem("adhdev_sound",Y?"1":"0")}catch{}},W=async()=>{p(""),h(""),M(!0);try{const Y=Vt(x),J=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:Y})}),ue=await J.json();if(!J.ok)throw new Error((ue==null?void 0:ue.error)||"Failed to save standalone font preferences");const le=Vt(ue.standaloneFontPreferences);d(ue),g(le),ms(le),La(le),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(Y){p(Y instanceof Error?Y.message:String(Y))}finally{M(!1)}},ne=()=>{const Y=Vt(f==null?void 0:f.standaloneFontPreferences);p(""),h(""),g(Y),ms(Y)},ae=()=>{p(""),h(""),g(ws),ms(ws)},ke=async()=>{A(""),B(""),C(!0);try{const Y=await Ut("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:S})}),J=await Y.json();if(!Y.ok)throw new Error((J==null?void 0:J.error)||"Failed to save standalone network preference");d(J),R(J.standaloneBindHost),B(J.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(Y){A(Y instanceof Error?Y.message:String(Y))}finally{C(!1)}},X=async()=>{if(A(""),B(""),j.trim().length<4){A("Password must be at least 4 characters.");return}if(j!==y){A("New password and confirmation do not match.");return}C(!0);try{const Y=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,newPassword:j})}),J=await Y.json();if(!Y.ok)throw new Error((J==null?void 0:J.error)||"Failed to save password");u(J),await U(),I(""),v(""),E(""),B(l!=null&&l.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Kl()}catch(Y){A(Y instanceof Error?Y.message:String(Y))}finally{C(!1)}},pe=async()=>{A(""),B(""),C(!0);try{const Y=await Ut("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:k,clear:!0})}),J=await Y.json();if(!Y.ok)throw new Error((J==null?void 0:J.error)||"Failed to clear password");u(J),await U(),I(""),v(""),E(""),B("Standalone password disabled.")}catch(Y){A(Y instanceof Error?Y.message:String(Y))}finally{C(!1)}};return t.jsxs(qc,{icon:t.jsx(gn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Wr,{variant:"info",children:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint."}),(l==null?void 0:l.publicHostWarning)&&t.jsx(Wr,{variant:"warning",children:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token."}),t.jsx(Rt,{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.93"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(f==null?void 0:f.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:l!=null&&l.hasPasswordAuth?"Password enabled":l!=null&&l.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(Rt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="127.0.0.1",onChange:()=>R("127.0.0.1")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 127.0.0.1. Best when only this machine should open the dashboard."})]})]}),t.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="0.0.0.0",onChange:()=>R("0.0.0.0")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),t.jsx("span",{className:"block text-text-muted text-xs mt-1",children:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points."})]})]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:()=>{ke()},disabled:H,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:H?"Saving…":"Save default network mode"}),t.jsxs("span",{className:"text-xs text-text-muted",children:["Applies on next standalone restart. Current run stays bound to ",(f==null?void 0:f.currentBindHost)||(l==null?void 0:l.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(Rt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:l!=null&&l.hasPasswordAuth?"A local password is currently required for browser access. Existing sessions are rotated when you change it.":"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended."}),L&&t.jsx(Wr,{variant:"error",children:L}),_&&t.jsx(Wr,{variant:"success",children:_}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:k,onChange:Y=>I(Y.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:l!=null&&l.hasPasswordAuth?"New password":"New standalone password",value:j,onChange:Y=>v(Y.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:y,onChange:Y=>E(Y.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{X()},disabled:H,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:H?"Saving…":l!=null&&l.hasPasswordAuth?"Update password":"Enable password"}),(l==null?void 0:l.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{pe()},disabled:H,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),t.jsx(Rt,{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(Y=>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 ${Y.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:Y.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:Y.type})]},Y.type))})}),t.jsx(Rt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Qp,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(Rt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(sf,{})]}),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(uf,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),t.jsx(Pb,{value:x,savedValue:Vt(f==null?void 0:f.standaloneFontPreferences),saving:w,error:m,notice:b,onChange:g,onSave:()=>{W()},onResetToSaved:ne,onResetToDefaults:ae})]}),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(ff,{})]})]})}),t.jsx(Rt,{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(Yp,{}),t.jsx(us,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(tu,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:q})]})}),t.jsx(Rt,{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(Kd,{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:Y=>c(Y.target.value),onBlur:N,onKeyDown:Y=>{Y.key==="Enter"&&Y.currentTarget.blur()}})]})})})]})}Gp();lf();Ib();const Eb=zi({baseUrl:"",getToken:vo});function $b({children:e}){const[s,r]=o.useState(null),[n,a]=o.useState(!0),[i,c]=o.useState(""),[l,u]=o.useState(""),[f,d]=o.useState(!1),x=async()=>{a(!0),u("");try{const M=await(await Ut("/auth/session")).json();r(M)}catch(w){u(w instanceof Error?w.message:String(w))}finally{a(!1)}};o.useEffect(()=>{x()},[]),o.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let w=!1;return(async()=>{try{const M=await Ut("/api/v1/standalone/preferences");if(!M.ok)return;const m=await M.json();if(w)return;const p=Vt(m.standaloneFontPreferences);ms(p),La(p)}catch{}})(),()=>{w=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const g=async w=>{w.preventDefault(),d(!0),u("");try{const M=await Ut("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),m=await M.json();if(!M.ok)throw new Error((m==null?void 0:m.error)||"Login failed");r(m),c(""),Kl()}catch(M){u(M instanceof Error?M.message:String(M))}finally{d(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.hasPasswordAuth?"This self-hosted dashboard is protected by a local password.":"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[t.jsx("input",{type:"password",value:i,onChange:w=>c(w.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),t.jsx("button",{type:"submit",disabled:f||!i,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:f?"Signing in…":"Unlock dashboard"})]}):t.jsx("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-500/10 px-3 py-2 text-sm text-yellow-300",children:"Password login is not enabled on this server."}),l&&t.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:l})]})}):t.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",l||"unknown error"]})}function Oi(){const{ides:e,initialLoaded:s}=js();if(!s)return t.jsx("div",{className:"p-10 text-center text-text-muted",children:"⏳ Loading machine..."});const r=e.find(n=>n.daemonMode||n.type==="adhdev-daemon");return r?t.jsx(fa,{to:`/machines/${r.id}`,replace:!0}):t.jsx(fa,{to:"/dashboard",replace:!0})}function Kb(){const e=o.useMemo(()=>({sendCommand:an,sendData:Ta}),[]);return t.jsx(jd,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(_d,{client:Eb,children:t.jsx($b,{children:t.jsx(jb,{children:t.jsx(Dd,{value:e,children:t.jsx(Mb,{children:t.jsxs(kd,{children:[t.jsx(cs,{path:"/dashboard",element:t.jsx($x,{})}),t.jsx(cs,{path:"/machine",element:t.jsx(Oi,{})}),t.jsx(cs,{path:"/machines/:id",element:t.jsx(mb,{})}),t.jsx(cs,{path:"/machines",element:t.jsx(Oi,{})}),t.jsx(cs,{path:"/about",element:t.jsx(_b,{})}),t.jsx(cs,{path:"/settings",element:t.jsx(Db,{})}),t.jsx(cs,{path:"*",element:t.jsx(fa,{to:"/dashboard",replace:!0})})]})})})})})})})}cp({connectionManager:Xt});Sd(document.getElementById("root")).render(t.jsx(Kb,{}));
|