@adhdev/daemon-standalone 0.9.82-rc.9 → 0.9.82-rc.91
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 +25384 -21200
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-BFF2C2J9.js +99 -0
- package/public/assets/index-Bso1b8Lh.css +1 -0
- package/public/assets/{terminal-CfAvHQvJ.js → terminal-D46M5EWH.js} +3 -3
- package/public/index.html +2 -2
- package/vendor/mcp-server/index.js +705 -70
- package/vendor/mcp-server/index.js.map +1 -1
- package/public/assets/index-C6PWDloP.js +0 -98
- package/public/assets/index-DC6YELcC.css +0 -1
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-CfAvHQvJ.js","assets/vendor-CgiI0UIA.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var Ku=Object.defineProperty;var Wu=(e,s,r)=>s in e?Ku(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Je=(e,s,r)=>Wu(e,typeof s!="symbol"?s+"":s,r);import{r as i,j as t,M as vo,a as Hu,b as Uu,c as zu,R as kt,d as kr,t as Vu,e as Gu,u as ls,D as qu,f as qa,g as Ya,i as Yu,h as Xu,C as Ju,B as Qu,k as Zu,l as em,H as bi,P as gi,m as tm,n as sm,o as wo,p as rm,q as nm,s as am,v as om,w as es,N as Xa,x as im}from"./vendor-CgiI0UIA.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 o of a)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function r(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(a){if(a.ep)return;a.ep=!0;const o=r(a);fetch(a.href,o)}})();function lm(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(o=>!n.interactionId||o.interactionId===n.interactionId).filter(o=>!n.topic||o.topic===n.topic).filter(o=>!n.kind||o.kind===n.kind).slice(-a).map(o=>({...o,payload:o.payload?{...o.payload}:{}}))},clear(){r.splice(0,r.length)}}}const Fs=lm();function yi(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 cm(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function vi(e){return Array.isArray(e)?[...e]:[]}function Jl(e,s){if(!e)return s??null;const r=Object.prototype.hasOwnProperty.call(e,"messages"),n=Object.prototype.hasOwnProperty.call(e,"activeModal");return s?{...s,...e,messages:r?vi(e.messages):s.messages,activeModal:n?e.activeModal??null:s.activeModal,inputContent:e.inputContent??s.inputContent}:{...e,...r?{messages:vi(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function mr(e,s){const r=cm(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:Jl(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),settings:e.settings??(s==null?void 0:s.settings)}}function Ql(e,s,r){if(!(s!=null&&s.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(s)?s:e;if(!(e!=null&&e.length))return s;const n=s.map(a=>{const o=e.find(l=>l.id===a.id);return o?mr(a,o):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(s.map(o=>o.id));for(const o of e)a.has(o.id)||n.push(o)}return n}function wi(e){return!!e&&typeof e=="object"&&"text"in e}function jo(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(o=>typeof o=="string"?o:wi(o)?String(o.text||""):"").join(r):wi(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Ks(e){return jo(e,{normalizeWhitespace:!0})}const Zl=i.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,connectionRetryStatuses:void 0}),ec=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function ji(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 tc(e,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=s.version??r.version??e.version,o=s.serverVersion??e.serverVersion??r.serverVersion,l=s.versionMismatch===!0||e.versionMismatch===!0,c=s.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=s.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),d&&(n.versionUpdateReason=d),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((s.versionMismatch===!0||l&&a&&o&&a!==o)&&(n.versionMismatch=!0),c&&(n.versionUpdateRequired=!0),n)}function dm(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 Jn(e){if(!e||typeof e!="object")return"";const s=e,r=dm(Ks(s.content).slice(0,512));return[String(s.id||""),String(s._localId||""),String(s._turnKey||""),String(s.index??""),String(s.role||""),String(s.receivedAt??s.timestamp??""),r].join(":")}function um(e,s){if(!Array.isArray(e))return e;if(s!=null&&s.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=Jn(n);for(let o=0;o<a.length;o+=1)r^=a.charCodeAt(o),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:Jn(e[0]),last:Jn(e[e.length-1])}}function Ja(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Qa(e,s,r){if(!e||!s||typeof e!="object"||typeof s!="object")return;if(Ja(e)&&Ja(s)){const l=e.messages;Array.isArray(l)&&l===s.messages&&r.add(l)}if(Array.isArray(e)&&Array.isArray(s)){const l=Math.min(e.length,s.length);for(let c=0;c<l;c+=1)Qa(e[c],s[c],r);return}const n=e,a=s,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const l of o)l!=="messages"&&Qa(n[l],a[l],r)}function hr(e,s){return Array.isArray(e)?e.map(r=>hr(r,s)):!e||typeof e!="object"?e:Ja(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?um(a,s):hr(a,s)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,hr(n,s)]))}function mm(e,s){try{const r=new WeakSet;return Qa(e,s,r),JSON.stringify(hr(e,r))===JSON.stringify(hr(s,r))}catch{return!1}}function Za(e,s,r){return mm(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function sc(e){var s;return e.daemonId||((s=e.id)==null?void 0:s.split(":")[0])||e.id}function pm(e,s,r){s[r]!==void 0&&(e[r]=s[r])}function ki(e,s,r,n){var c;const a=(c=s.chats)!=null&&c.length?s.chats:e.chats,o=Ql(e.childSessions,s.childSessions,{preserveMissing:n}),l=Jl(s.activeChat,e.activeChat);return tc(e,s,{...e,...s,chats:a,childSessions:o,activeChat:l,_lastUpdate:r})}function fm(e,s,r){var a,o;const n={};s.status&&s.status!==e.status&&(n.status=s.status),s.cdpConnected!==void 0&&(n.cdpConnected=s.cdpConnected),s.childSessions!==void 0&&(n.childSessions=Ql(e.childSessions,s.childSessions,{preserveMissing:r})),(a=s.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=s.chats);for(const l of["title","workspace","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])pm(n,s,l);return s.machineNickname!==void 0&&s.machineNickname!==e.machineNickname&&(n.machineNickname=s.machineNickname),s.versionMismatch===!0&&(n.versionMismatch=!0),n}function hm(e,s,r,n){const a=fm(e,s,n),o=Object.keys(a).length>0?tc(e,s,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Za(e,o,r)}function xm(e){const s=new Set(e.map(o=>o.id)),r=new Set,n=new Set,a=new Set;for(const o of e){const l=sc(o);l&&r.add(l),l&&o.type!=="adhdev-daemon"&&n.add(l),l&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(l)}return{incomingIds:s,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function bm(e,s,r,n,a,o){return!a.has(s)||!o.has(s)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function gm(e,s,r,n,a){return e.transport?r.has(s)&&!n.has(s)?!0:a.has(s):!1}function ym(e,s,r){var u,h;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(g=>({...g,_lastUpdate:n}));const o=new Map;for(const g of s)o.set(g.id,g);const{incomingIds:l,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=xm(e);for(const g of e){const k=o.get(g.id);if(!k){o.set(g.id,{...g,_lastUpdate:n});continue}const f=ji(g),p=ji(k),b=sc(g),y=!a.has(b);if(f>p){const N=ki(k,g,n,y);o.set(g.id,Za(k,N,n));continue}if(f<p){o.set(g.id,hm(k,g,n,y));continue}const x=g.timestamp||n,I=k._lastUpdate||k.timestamp||0;if(x>=I){const N=ki(k,g,n,y);o.set(g.id,Za(k,N,n));continue}(u=g.chats)!=null&&u.length&&!((h=k.chats)!=null&&h.length)&&o.set(g.id,{...k,chats:g.chats})}for(const[g,k]of o){const f=k.daemonId||g.split(":")[0];if(!c.has(f))continue;if(a.has(f)&&m.has(f)&&!l.has(g)){o.delete(g);continue}const p=n-(k._lastUpdate||k.timestamp||0);bm(k,f,p,l,a,d)&&o.delete(g)}for(const[g,k]of o){const f=k.daemonId||g.split(":")[0];if(gm(k,f,c,d,o))continue;n-(k._lastUpdate||k.timestamp||0)>3e5&&k.status!=="online"&&o.delete(g)}return Array.from(o.values())}function vm(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 wm({children:e,connectionOverrides:s}){const[r,n]=i.useState([]),[a,o]=i.useState(!1),[l,c]=i.useState([]),[d,m]=i.useState(void 0),u=i.useRef(r);i.useEffect(()=>{u.current=r},[r]);const h=i.useCallback((y,x)=>{n(I=>{let N=!1;const j=I.map(A=>A.id!==y||A.chats===x?A:(N=!0,{...A,chats:x}));return N?j:I})},[]),g=i.useCallback((y,x)=>{n(I=>{const N=I.length===0?y:ym(y,I,x),j=!vm(I,N);return j&&Fs.record({kind:"dashboard.entries_applied",payload:{incoming:yi(y),next:yi(N)}}),j?N:I})},[]),k=i.useCallback(()=>o(!0),[]),f=i.useMemo(()=>({injectEntries:g,markLoaded:k,getIdes:()=>u.current}),[g,k]),p=s,b=i.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:l,setToasts:c,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,connectionRetryStatuses:p==null?void 0:p.connectionRetryStatuses,userName:d,setUserName:m}),[r,h,a,l,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,p==null?void 0:p.connectionRetryStatuses,d]);return t.jsx(ec.Provider,{value:f,children:t.jsx(Zl.Provider,{value:b,children:e})})}function is(){return i.useContext(Zl)}function Nr(){return i.useContext(ec)}function rc(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function a(c){return c.startsWith("http")?c:`${s}${c.startsWith("/")?"":"/"}${c}`}function o(c){const d=r==null?void 0:r(),m=a(c),u=c.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!c.startsWith("http")&&!s?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function l(c,d={}){const m={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(m.Authorization=`Bearer ${u}`);const h=a(c),g=new AbortController,k=setTimeout(()=>g.abort(),15e3);try{const f=await fetch(h,{...d,headers:m,signal:g.signal});if(f.status===401)throw n==null||n(),new Error("Unauthorized");if(!f.ok){const p=await f.json().catch(()=>({error:f.statusText}));throw new Error(p.error||`API Error: ${f.status}`)}return f.json()}finally{clearTimeout(k)}}return{getDaemons:()=>l("/api/v1/daemons"),getDaemonStatus:c=>l(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,m={})=>l(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),execTerminal:(c,d,m)=>l(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:m})}),sendAgentMessage:(c,d,m)=>l(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:m})}),getAgentStatus:c=>l(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,m)=>l(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:m?"approve":"reject"})}),getMuxState:c=>l(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>l(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,d,m={})=>l(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:l}}const jm=rc({baseUrl:"http://localhost:3847"}),km=i.createContext(jm);function Nm({client:e,children:s}){return t.jsx(km.Provider,{value:e,children:s})}const Sm={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},nc=i.createContext(Sm);function Cm({value:e,children:s}){return t.jsx(nc.Provider,{value:e,children:s})}function wt(){return i.useContext(nc)}function Im(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 Tm(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Am(e){return e?Im([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Tm(e.content)]):""}const Fe={size:18};function ac({size:e=Fe.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 ko({size:e=Fe.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 as({size:e=Fe.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 oc({size:e=Fe.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 Mm({size:e=Fe.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 Lm({size:e=Fe.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 ic({size:e=Fe.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 Rm({size:e=Fe.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 Dn({size:e=Fe.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 lc({size:e=Fe.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 _m({size:e=Fe.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 Jt({size:e=Fe.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 Mt({size:e=Fe.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 No({size:e=Fe.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 Pm({size:e=Fe.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 ks({size:e=Fe.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 Tr({size:e=Fe.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 Sr({size:e=Fe.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 Ws({size:e=Fe.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 rs({size:e=Fe.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:"5",r:"2"}),t.jsx("circle",{cx:"5",cy:"19",r:"2"}),t.jsx("circle",{cx:"19",cy:"19",r:"2"}),t.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),t.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),t.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function Dm({size:e=Fe.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:"12 2 2 7 12 12 22 7 12 2"}),t.jsx("polyline",{points:"2 12 12 17 22 12"}),t.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function cc({size:e=Fe.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 So({size:e=Fe.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 dc({size:e=Fe.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 Em({size:e=Fe.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 Co({size:e=Fe.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 $m({size:e=Fe.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 Io({size:e=Fe.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 uc({size:e=Fe.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 vt({size:e=Fe.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 Bm({size:e=Fe.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 Om({size:e=Fe.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 Fm({size:e=Fe.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 Km({size:e=Fe.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 En({size:e=Fe.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 Wm({size:e=Fe.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 Hm({size:e=Fe.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 Um({size:e=Fe.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 zm({size:e=Fe.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 Vm({size:e=Fe.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 Gm({size:e=Fe.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 qm({size:e=Fe.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 Ym({size:e=Fe.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 Xm({size:e=Fe.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 Jm({size:e=Fe.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 Qm({size:e=Fe.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 Zm({size:e=Fe.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"})]})}const To="adhdev_chat_activity_visible",Ni=new Set(["hidden","debug","internal"]),Si=new Set(["visible","user","chat"]),ep=new Set(["debug","trace","internal"]),tp=new Set(["tool_call","terminal_command","runtime_activity"]),sp=new Set(["runtime_status","provider_chrome","control"]),rp=new Set(["thought","tool","terminal"]);function mc(e){const s=e.meta;return s&&typeof s=="object"&&!Array.isArray(s)?s:null}function Ls(e){return typeof e=="string"?e.trim().toLowerCase():""}function Qn(e,s,r){return e[r]??(s==null?void 0:s[r])}function Ci(e,s,r){const n=e;return r.some(a=>n[a]===!0||(s==null?void 0:s[a])===!0)}function np(e,s){const r=Ls(e.kind);return r||(s==="tool"?"tool":"standard")}function Zn(e,s,r){const n=mc(e),a=typeof(n==null?void 0:n.label)=="string"?n.label.trim():"";return a||(s==="terminal"||r==="terminal_command"?"Terminal":s==="tool"||r==="tool_call"?"Tool":s==="thought"?"Thought":r==="runtime_activity"?"Runtime":"Activity")}function ap(e){const s=e.content;return Array.isArray(s)&&s.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function Ao(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const s=mc(e),r=Ls(e.role),n=np(e,r),a=Ls(Qn(e,s,"visibility")),o=Ls(e.transcriptVisibility??(s==null?void 0:s.transcriptVisibility)??a),l=Ls(Qn(e,s,"audience")),c=Ls(Qn(e,s,"source")),d=Ni.has(a)||Ni.has(o)||ep.has(l)||Ci(e,s,["internal","isInternal","debug","statusOnly","controlOnly"]),m=Si.has(a)||Si.has(o)||l==="chat"||Ci(e,s,["userFacing"]),u=rp.has(n)||tp.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:Zn(e,n,c)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:Zn(e,n,c)};if((r==="system"||n==="system")&&ap(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(sp.has(c)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(u)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:Zn(e,n,c)};const h=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:h?"chat":"internal",isUserFacing:h,isActivityFacing:!1,isInternal:!h,role:r,kind:n,label:h?"Chat":"Internal"}}function op(e){return(Array.isArray(e)?e:[]).filter(s=>Ao(s).isUserFacing)}function pc(e){return(Array.isArray(e)?e:[]).filter(s=>Ao(s).isActivityFacing)}function ip(e,s,r){return!r||s.length===0?e:[...e,...s].sort((n,a)=>{const o=Number(n.receivedAt??n.timestamp??0)||0,l=Number(a.receivedAt??a.timestamp??0)||0;if(o!==l)return o-l;const c=Number(n.index??0)||0,d=Number(a.index??0)||0;return c-d})}function Ii(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(To))==="1"}catch{return!1}}function lp(e,s=typeof localStorage<"u"?localStorage:void 0){try{s==null||s.setItem(To,e?"1":"0")}catch{}}const fc=[Hu,{singleTilde:!1}],hc=[fc,Uu,zu],cp=[fc],Mo=200,dp=80,Ti=650,Qs=new Map;function vn(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function up(e,s){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(s||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${Am(n)}`}function mp(e,s,r,n){return e||!s?!1:vn(r,n)}function pp({scrollTop:e,scrollHeight:s,clientHeight:r,topThresholdPx:n=dp,bottomThresholdPx:a=Mo}){const o=Math.max(0,Number(e)||0),l=Math.max(0,Number(s)||0),c=Math.max(0,Number(r)||0);return Math.max(0,l-c)<=0?{showTop:!1,showBottom:!1}:{showTop:o>n,showBottom:Math.max(0,l-o-c)>a}}function fp(e){return pp({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function pr(e,s=Mo){return!!e&&e.fromBottom>=s}function hp(e,s){return vn(e,s)?!pr(e):!0}function xp({hasSelection:e,userScrolledUp:s,hasChatContentChanged:r=!0}){return!(e||s||!r)}function bp({hasSelection:e,userScrolledUp:s,contextAutoScrollActive:r}){return e?!1:r||!s}function ea(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function xc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function gp(e,s,r){return Number(e.receivedAt||r[wn(e,s)]||0)||0}function bc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function yp(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function Zs(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 ta(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 Wr(e,s,r){return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[t.jsx("span",{className:"font-medium",children:e}),s?t.jsx("span",{className:"ml-1 break-all",children:s}):null,r?t.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:r}):null]})}function Ai(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):bc(e)?t.jsx(vo,{remarkPlugins:hc,children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function er({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:Ai(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=ta(r),o=r.alt||r.description||Zs(r.uri,"image");return a?t.jsx("img",{src:a,alt:o,className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):t.jsx("div",{children:Wr("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=ta(r);return a?t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),r.transcript?t.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r.transcript}):null]},`audio-${n}`):t.jsx("div",{children:Wr("Audio",Zs(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=ta(r),o=r.title||r.name||r.alt||Zs(r.uri,"video"),l=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
|
|
3
|
-
`);return t.jsxs("div",{className:"flex flex-col gap-1",children:[a?t.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):Wr("Video",o,l),a&&l?t.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:l}):null]},`video-${n}`)}if(r.type==="resource_link"){const a=r.title||r.name||Zs(r.uri,"resource"),o=[r.description,r.mimeType].filter(Boolean).join(`
|
|
4
|
-
`);return t.jsxs("div",{className:"flex flex-col gap-1",children:[r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:a}):Wr("Resource",a,o),r.uri&&o?t.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]},`resource-link-${n}`)}if(r.type==="resource"&&r.resource){const a=Zs(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}),Ai(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 wn(e,s){const r=e,n=jo(e.content,{joiner:`
|
|
5
|
-
`});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 vp=i.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(vo,{remarkPlugins:cp,children:s.text}),t.jsx("span",{className:"action-time",children:xc(s.timestamp)})]})},(e,s)=>e.log===s.log),wp=i.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:l,onToggleTextExpanded:c}){var v,w,B;const d=(s.role||"").toLowerCase(),m=d==="user"||d==="human",u=s.kind||(d==="tool"?"tool":"standard"),h=Ao(s),g=yp(s.content)?s.content:null,k=!!(g!=null&&g.some(R=>R.type!=="text")),f=jo(s.content,{joiner:`
|
|
6
|
-
`});if(h.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const R=h.label||"Activity";return t.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[t.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[t.jsx("span",{className:"activity-dot"}),t.jsx("span",{children:R})]}),k&&g?t.jsx("div",{className:"chat-msg-activity-body",children:t.jsx(er,{parts:g,renderAsPreformatted:!1})}):t.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:f})]})}if(u==="thought"){const R=typeof((v=s.meta)==null?void 0:v.label)=="string"?s.meta.label:"Thought";return t.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx(Fm,{size:13}),t.jsx("span",{children:R})]}),t.jsx("div",{className:"chat-msg-body",children:f})]})}if(u==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[t.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),t.jsx("span",{className:"tool-label",children:"Tool"})]}),k&&g?t.jsx("div",{className:"tool-text w-full",children:t.jsx(er,{parts:g,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:f})]});if(u==="terminal"){const R=(w=s.meta)!=null&&w.isRunning?"⏳":"✅",T=typeof((B=s.meta)==null?void 0:B.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:R}),t.jsx("span",{children:T})]}),k&&g?t.jsx("div",{className:"chat-msg-body",children:t.jsx(er,{parts:g,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:f})]})}if(u==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:k&&g?t.jsx(er,{parts:g,renderAsPreformatted:!1}):f.slice(0,100)});const p=s.meta,y=(typeof(p==null?void 0:p.renderMode)=="string"?p.renderMode.trim():"")==="preformatted",x=f,I=!1,N=x,j=y,A=!j&&bc(N),M=["chat-message-row",m?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return t.jsx("div",{className:M,children:(x||k||m)&&t.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${x||k?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:m?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:xc(r)})]}),(x||k)&&t.jsx("div",{className:"chat-markdown",children:k&&g?t.jsx(er,{parts:g,renderAsPreformatted:j}):j?t.jsx("pre",{className:"chat-preformatted",children:N}):A?t.jsx(vo,{remarkPlugins:hc,children:N}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:N})}),I]})})},(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),jp=i.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:l=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:m,showActivityMessages:u=!1,emptyState:h,onLoadMore:g,isLoadingMore:k,hasMoreHistory:f,hiddenLiveCount:p=0,loadError:b,scrollToBottomRequestNonce:y,isVisible:x=!0},I){const N=i.useRef(null),j=i.useRef(null),A=i.useRef(null),M=i.useRef(0),v=i.useRef(""),w=i.useRef(""),B=i.useRef(!1),R=i.useRef(null),T=i.useRef(!1),H=i.useRef(null),E=i.useRef(!1),[D,S]=i.useState(new Set),[C,W]=i.useState({showTop:!1,showBottom:!1}),_=i.useRef(!1),O=i.useRef(!1),V=i.useRef(x),X=i.useRef(x),ye=i.useRef(null);X.current=x;const he=()=>{const J=N.current;return J?J.scrollHeight-J.scrollTop-J.clientHeight<Mo:!0},ne=i.useCallback(()=>{const J=N.current,oe=J?fp(J):{showTop:!1,showBottom:!1};W(ee=>ee.showTop===oe.showTop&&ee.showBottom===oe.showBottom?ee:oe)},[]),pe=i.useCallback((J="auto")=>{var ee;const oe=N.current;oe&&(oe.scrollTo({top:oe.scrollHeight,behavior:J}),(ee=oe.ownerDocument.defaultView)==null||ee.requestAnimationFrame(()=>ne()))},[ne]),ke=i.useCallback((J="auto")=>{var ee;const oe=N.current;oe&&(oe.scrollTo({top:0,behavior:J}),(ee=oe.ownerDocument.defaultView)==null||ee.requestAnimationFrame(()=>ne()))},[ne]),Se=i.useCallback(()=>{var Ce;const J=N.current,oe=(Ce=window.getSelection)==null?void 0:Ce.call(window);if(!J||!oe||oe.rangeCount===0||oe.isCollapsed){E.current=!1;return}const ee=oe.anchorNode,Ne=oe.focusNode;E.current=!!(ee&&Ne&&J.contains(ee)&&J.contains(Ne))},[]),G=i.useMemo(()=>{const J=op(s),oe=pc(s);return ip(J,oe,u)},[s,u]),be=G.length===s.length?m:void 0,fe=up(G,be),ve=i.useCallback(()=>{const J=N.current;if(!J||!c||!X.current)return;const oe={top:J.scrollTop,fromBottom:Math.max(0,J.scrollHeight-J.scrollTop-J.clientHeight),messageFingerprint:fe};ye.current={contextKey:c,snapshot:oe},Qs.set(c,oe)},[c,fe]),P=i.useCallback((J="auto")=>{R.current!=null&&cancelAnimationFrame(R.current),R.current=requestAnimationFrame(()=>{R.current=null,pe(J)})},[pe]),me=i.useCallback(()=>{_.current=!1,T.current=!0,O.current=!0,H.current!=null&&window.clearTimeout(H.current),H.current=window.setTimeout(()=>{T.current=!1,H.current=null},Ti)},[]);i.useEffect(()=>{const J=!B.current,oe=w.current!==c;if(w.current=c,J||oe){B.current=!0;const Ne=c?Qs.get(c):null,Ce=!!Ne&&vn(Ne,fe);_.current=Ce?pr(Ne):!1,T.current=hp(Ne,fe),E.current||(Ce?requestAnimationFrame(()=>{const we=N.current;we&&(ea(we,Ne),_.current=pr(Ne),ne(),O.current=!0)}):P("auto")),M.current=G.length,v.current=fe;return}G.length>M.current;const ee=fe!==v.current;xp({hasSelection:E.current,userScrolledUp:_.current,hasChatContentChanged:ee})&&P("auto"),M.current=G.length,v.current=fe},[fe,c,G.length,P,ne]),i.useEffect(()=>{y&&(me(),E.current||P("auto"))},[me,P,y]),i.useEffect(()=>{const J=V.current;J&&!x&&ve(),X.current=x,V.current=x;const oe=c?Qs.get(c):null;if(mp(J,x,oe,fe)){if(!oe)return;_.current=pr(oe),T.current=!1,E.current||requestAnimationFrame(()=>{const ee=N.current;ee&&(ea(ee,oe),ne())});return}},[x,c,fe,me,ve,P,ne]),i.useEffect(()=>()=>{const J=ye.current;J&&Qs.set(J.contextKey,J.snapshot),R.current!=null&&cancelAnimationFrame(R.current),H.current!=null&&window.clearTimeout(H.current)},[]),i.useEffect(()=>{const J=j.current,oe=N.current;if(!J||!oe)return;const ee=()=>{H.current!=null&&window.clearTimeout(H.current),H.current=window.setTimeout(()=>{T.current=!1,H.current=null},Ti)},Ne=new ResizeObserver(()=>{ne();const Ce=T.current;bp({hasSelection:E.current,userScrolledUp:_.current,contextAutoScrollActive:Ce})&&(P("auto"),Ce&&ee())});return Ne.observe(J),oe!==J&&Ne.observe(oe),()=>{Ne.disconnect(),H.current!=null&&(window.clearTimeout(H.current),H.current=null)}},[P,c,ne]),i.useImperativeHandle(I,()=>({scrollToBottom:(J="smooth")=>{pe(J)}}),[pe]),i.useEffect(()=>{const J=N.current;if(!J)return;let oe;const ee=()=>{ve(),clearTimeout(oe),oe=setTimeout(()=>{_.current=!he(),ne()},50)};return J.addEventListener("scroll",ee,{passive:!0}),()=>{J.removeEventListener("scroll",ee),clearTimeout(oe)}},[ve,ne]),i.useEffect(()=>(document.addEventListener("selectionchange",Se),()=>document.removeEventListener("selectionchange",Se)),[Se]);const q=i.useRef(0),de=i.useRef(!1);i.useEffect(()=>{const J=N.current;if(!J||!de.current||q.current===0)return;const oe=J.scrollHeight-q.current;oe>0&&(J.scrollTop=oe),ne(),ve(),q.current=0,de.current=!1},[G.length,ve,ne]),i.useEffect(()=>{if(O.current||!c)return;const J=Qs.get(c),oe=N.current;if(!(!J||!oe)){if(!vn(J,fe)){pe("auto"),O.current=!0;return}ea(oe,J),_.current=pr(J),ne(),O.current=!0}},[c,fe,G.length,pe,ne]);const ae=()=>{const J=N.current;J&&(q.current=J.scrollHeight),de.current=!0,g==null||g()},xe=()=>{_.current=!0,ke("smooth"),ve()},ue=()=>{me(),pe("smooth"),ve()},ce=i.useMemo(()=>{const J=G.map((Ce,we)=>({type:"message",data:Ce,index:we,ts:gp(Ce,we,d)}));if(!r||r.length===0)return J;const oe=[...r].sort((Ce,we)=>Ce.timestamp-we.timestamp).map((Ce,we)=>({type:"action",data:Ce,index:we,ts:Ce.timestamp})),ee=[];let Ne=0;for(const Ce of J){for(;Ne<oe.length&&Ce.ts>0&&oe[Ne].ts<Ce.ts;)ee.push(oe[Ne++]);ee.push(Ce)}for(;Ne<oe.length;)ee.push(oe[Ne++]);return ee},[G,r,d]),te=p>0||!!f,$=p>0?`↑ Show ${Math.min(p,80)} earlier messages${p>80?` (${p} hidden)`:""}`:b?`↻ ${b}`:"↑ Load older messages";return t.jsxs("div",{className:"chat-scroll-frame",children:[t.jsx("div",{ref:N,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:j,className:"chat-container-content",children:[k&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),te&&!k&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{type:"button",onClick:ae,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${b&&p===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:$})}),ce.length===0&&!te&&(h||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),ce.map(J=>{if(J.type==="action"){const Ie=J.data;return t.jsx(vp,{log:Ie},`action-${J.index}`)}const oe=J.data,ee=J.index,Ne=wn(oe,ee),Ce=oe.receivedAt||d[Ne],we=`${c}-${Ne}`,K=D.has(we);return t.jsx(wp,{message:oe,receivedAt:Ce,agentName:n,userName:a,isCliMode:o,isTextExpanded:K,onToggleTextExpanded:()=>S(Ie=>{const Re=new Set(Ie);return K?Re.delete(we):Re.add(we),Re})},`msg-${Ne}`)}),l&&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:A})]})}),(C.showTop||C.showBottom)&&t.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[C.showTop&&t.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:xe,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),C.showBottom&&t.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:ue,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),kp=i.memo(jp,(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.lastMessageHash===s.lastMessageHash&&e.showActivityMessages===s.showActivityMessages&&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&&e.isVisible===s.isVisible),Np="modulepreload",Sp=function(e){return"/"+e},Mi={},Cp=function(s,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=Sp(d),d in Mi)return;Mi[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":Np,m||(h.as="script"),h.crossOrigin="",h.href=d,c&&h.setAttribute("nonce",c),document.head.appendChild(h),m)return new Promise((g,k)=>{h.addEventListener("load",g),h.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return a.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return s().catch(o)})};let Li=!1;const gc=i.forwardRef(({onInput:e,onViewportMetrics:s,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},l)=>{const c=i.useRef(null),[d,m]=i.useState(null),u=i.useRef([]),h=i.useRef(!1),g=i.useRef(!1),k=i.useRef(!1),f=i.useRef(!1),p=()=>{const b=c.current;if(b){h.current&&(b.clear(),h.current=!1);for(const y of u.current)b.write(y.data,y.onProcessed);u.current=[],g.current&&(b.fit(),g.current=!1),k.current&&(b.bumpResize(),k.current=!1),f.current&&(b.scrollToTop(),f.current=!1)}};return i.useImperativeHandle(l,()=>({write:(b,y)=>{c.current?c.current.write(b,y):u.current.push({data:b,onProcessed:y})},clear:()=>{c.current?c.current.clear():(u.current=[],h.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],h.current=!0)},resize:(b,y)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(b,y)},fit:()=>{c.current?c.current.fit():g.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():k.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():f.current=!0},getSelection:()=>{var b,y;return((y=(b=c.current)==null?void 0:b.getSelection)==null?void 0:y.call(b))||""},getVisibleText:()=>{var b,y;return((y=(b=c.current)==null?void 0:b.getVisibleText)==null?void 0:y.call(b))||""}}),[]),i.useEffect(()=>{d&&p()},[d]),i.useEffect(()=>{let b=!1;return Cp(()=>import("./terminal-CfAvHQvJ.js"),__vite__mapDeps([0,1,2])).then(y=>{Li||(Li=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),b||m(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{b=!0}},[]),d?t.jsx(d,{ref:c,onInput:e,onViewportMetrics:s,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,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"}})});gc.displayName="CliTerminal";function Hr({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 Ri({value:e,max:s,label:r,color:n="#8b5cf6",detail:a,compact:o=!1}){const l=s>0?Math.min(Math.round(e/s*100),100):0,c=l>85?"#ef4444":l>60?"var(--status-warning)":n;return o?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:[l,"%"]})]}),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:`${l}%`,background:c}})})]}):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:[l,"%"]})]}),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:`${l}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),a&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Ip({cursorPos:e,viewportRef:s,imgRef:r}){var x;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(x=s.current)==null?void 0:x.getBoundingClientRect();if(!o)return null;const l=n.naturalWidth||a.width,c=n.naturalHeight||a.height,d=l/c,m=a.width/a.height;let u,h,g,k;d>m?(u=a.width,h=a.width/d,g=0,k=(a.height-h)/2):(h=a.height,u=a.height*d,g=(a.width-u)/2,k=0);const f=a.left-o.left+g+u*e.nx,p=a.top-o.top+k+h*e.ny,b=Math.max(8,Math.min(o.width-8,f)),y=Math.max(8,Math.min(o.height-8,p));return t.jsxs("div",{style:{position:"absolute",left:b-8,top:y-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[t.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function Tp({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:l,setImeText:c,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:h,mobileFillZoom:g,onZoomOut:k,onZoomReset:f,onZoomIn:p,transportType:b,screenshotUsage:y,lastActionStatus:x}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:I=>I.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(I=>!I),o(!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:l,autoFocus:!0,onTouchStart:I=>I.stopPropagation(),onChange:I=>c(I.target.value),onKeyDown:I=>{d(I)},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:()=>{o(I=>!I),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:m?"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:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),u>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),b==="direct"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:"Direct P2P connection",children:"Direct"}),b==="relay"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),y&&y.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),x&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:x})]})]}),a&&t.jsxs("div",{onTouchStart:I=>I.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(h?g:1)+.01?h?"FILL":"FIT":`${Math.round(u*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:I=>{I.stopPropagation(),k()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),t.jsx("button",{onClick:I=>{I.stopPropagation(),f()},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:h?"FILL":"FIT"}),t.jsx("button",{onClick:I=>{I.stopPropagation(),p()},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 Ap({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 Mp(){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 _i(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 Ar(e,s){const r=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{if(!Mp())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(([l,c])=>[l,_i(c)]))}),r.current=s;return}const o=Object.keys({...a,...s}).filter(l=>!Object.is(a[l],s[l]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(l=>[l,_i(s[l])]))}),r.current=s})}function Lp({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:l,panXRef:c,panYRef:d,setPanX:m,setPanY:u,setZoom:h,lastWheelTimeRef:g,onAction:k,setLastActionStatus:f,spawnRippleFromNormalized:p,clampPan:b,isMobile:y,mobileFillZoom:x}){const[I,N]=i.useState(null),j=i.useRef(null),A=i.useRef(null),M=i.useRef(null),v=i.useRef(!1),w=i.useRef(null),B=i.useRef(0),R=i.useRef(null),T=i.useRef(1),H=i.useRef({x:0,y:0}),E=i.useRef(!1),D=i.useRef(n),S=i.useRef(k),C=30,W=550,_=18,O=60,V=400,X=12,ye=()=>{if(j.current)return;const pe={nx:.5,ny:.5};j.current=pe,N(pe)};return i.useEffect(()=>{D.current=n,n==="mouse"&&ye()},[n]),i.useEffect(()=>{S.current=k},[k]),i.useEffect(()=>{const pe=e.current;if(!pe)return;const ke=P=>{if(!r.current)return null;const me=r.current.getBoundingClientRect();return!me.width||!me.height?null:{nx:Math.max(0,Math.min(1,(P.clientX-me.left)/me.width)),ny:Math.max(0,Math.min(1,(P.clientY-me.top)/me.height))}},Se=(P,me)=>{if(!r.current)return{dnx:0,dny:0};const q=r.current,de=q.getBoundingClientRect(),ae=q.naturalWidth||de.width,xe=q.naturalHeight||de.height,ue=ae/xe,ce=de.width/de.height;let te,$;return ue>ce?(te=de.width,$=de.width/ue):($=de.height,te=de.height*ue),{dnx:P/te,dny:me/$}},G=(P,me,q)=>{if(q<=1.05)return;const de=-(P-.5)*100,ae=-(me-.5)*100,xe=b(de,ae,q);(Math.abs(xe.x-c.current)>.1||Math.abs(xe.y-d.current)>.1)&&(m(xe.x),u(xe.y),c.current=xe.x,d.current=xe.y)},be=P=>{const me=s.current;if(me&&P.target instanceof Node&&me.contains(P.target))P.preventDefault();else return;if(P.touches.length===1){const q=P.touches[0];A.current={x:q.clientX,y:q.clientY,time:Date.now()},M.current={x:q.clientX,y:q.clientY},E.current||(v.current=!1),w.current=setTimeout(()=>{if(!v.current&&!E.current)if(v.current=!0,D.current==="mouse"){const de=j.current||{nx:.5,ny:.5};f("Right Click"),p(de.nx,de.ny,"right"),S.current("input_click",{...de,button:"right"}).catch(()=>{})}else{const de=ke(q);de&&(f("Right Click"),p(de.nx,de.ny,"right"),S.current("input_click",{...de,button:"right"}).catch(()=>{}))}},500);return}if(P.touches.length===2){w.current&&clearTimeout(w.current),v.current=!0,E.current=!0;const q=P.touches[1].clientX-P.touches[0].clientX,de=P.touches[1].clientY-P.touches[0].clientY;R.current=Math.sqrt(q*q+de*de),T.current=l.current,H.current={x:(P.touches[0].clientX+P.touches[1].clientX)/2,y:(P.touches[0].clientY+P.touches[1].clientY)/2}}},fe=P=>{const me=s.current;if(me&&P.target instanceof Node&&me.contains(P.target)&&P.preventDefault(),P.touches.length===1&&M.current){const q=P.touches[0],de=q.clientX-M.current.x,ae=q.clientY-M.current.y;if(!v.current&&A.current){const xe=q.clientX-A.current.x,ue=q.clientY-A.current.y;Math.sqrt(xe*xe+ue*ue)>8&&(v.current=!0,w.current&&clearTimeout(w.current))}if(v.current)if(D.current==="mouse"){const xe=Se(de,ae),ue=j.current||{nx:.5,ny:.5},ce=Math.max(0,Math.min(1,ue.nx+xe.dnx)),te=Math.max(0,Math.min(1,ue.ny+xe.dny));j.current={nx:ce,ny:te},N({nx:ce,ny:te}),f(`Cursor: ${Math.round(ce*100)}%, ${Math.round(te*100)}%`),G(ce,te,l.current);const $=Date.now();$-g.current>=30&&(g.current=$,S.current("input_mouseMoved",{nx:ce,ny:te}).catch(()=>{}))}else if(l.current>1){const xe=s.current;if(xe){const ue=xe.clientWidth,ce=xe.clientHeight,te=c.current+de/ue*100,$=d.current+ae/ce*100,J=b(te,$,l.current);m(J.x),u(J.y),c.current=J.x,d.current=J.y}}else{const xe=ke(q);if(xe){const ue=Date.now();ue-g.current>=40&&(g.current=ue,f("Scroll"),S.current("input_wheel",{nx:xe.nx,ny:xe.ny,deltaX:Math.round(-de*2.5),deltaY:Math.round(-ae*2.5)}).catch(()=>{}))}}M.current={x:q.clientX,y:q.clientY};return}if(P.touches.length===2&&R.current!==null){const q=P.touches[1].clientX-P.touches[0].clientX,de=P.touches[1].clientY-P.touches[0].clientY,xe=Math.sqrt(q*q+de*de)/R.current,ue=(P.touches[0].clientX+P.touches[1].clientX)/2,ce=(P.touches[0].clientY+P.touches[1].clientY)/2,te=ue-H.current.x,$=ce-H.current.y,J=Math.abs(xe-1)>.03;if(D.current==="mouse"){if(J){const oe=Math.max(o,Math.min(5,T.current*xe));h(oe),l.current=oe}else if(Math.abs(te)>2||Math.abs($)>2){const oe=j.current||{nx:.5,ny:.5},ee=Date.now();ee-g.current>=30&&(g.current=ee,f("Scroll"),S.current("input_wheel",{nx:oe.nx,ny:oe.ny,deltaX:Math.round(-te*3),deltaY:Math.round(-$*3)}).catch(()=>{}))}}else{const oe=Math.max(o,Math.min(5,T.current*xe));h(oe),l.current=oe;const ee=s.current;if(ee&&oe>1){const Ne=ee.clientWidth,Ce=ee.clientHeight,we=c.current+te/Ne*100,K=d.current+$/Ce*100,Ie=b(we,K,oe);m(Ie.x),u(Ie.y),c.current=Ie.x,d.current=Ie.y}}H.current={x:ue,y:ce}}},ve=P=>{var me;if(w.current&&clearTimeout(w.current),R.current=null,P.touches.length===1&&E.current){const q=P.touches[0];A.current={x:q.clientX,y:q.clientY,time:Date.now()},M.current={x:q.clientX,y:q.clientY},v.current=!0;return}if(P.touches.length===0){if(E.current){E.current=!1,v.current=!1;return}if(P.changedTouches.length===1){const q=P.changedTouches[0],de=Date.now(),ae=de-(((me=A.current)==null?void 0:me.time)||0),xe=A.current?q.clientX-A.current.x:0,ue=A.current?q.clientY-A.current.y:0,ce=Math.sqrt(xe*xe+ue*ue);if(D.current==="mouse"){if(ae<C||ae>W||ce>_){v.current=!1;return}const te=j.current||ke(q);te&&(f(`Click: ${Math.round(te.nx*100)}%, ${Math.round(te.ny*100)}%`),p(te.nx,te.ny,"left"),S.current("input_click",{...te}).catch(()=>{}))}else{if(v.current){v.current=!1;return}if(ae<O||ae>V||ce>X){v.current=!1;return}const te=ke(q);if(!te)return;de-B.current<300?(f("Double tap"),p(te.nx,te.ny,"double"),S.current("input_click",{...te,clickCount:2}).catch(()=>{}),B.current=0):(f(`Tap: ${Math.round(te.nx*100)}%, ${Math.round(te.ny*100)}%`),p(te.nx,te.ny,"left"),S.current("input_click",{...te}).catch(()=>{}),B.current=de)}}v.current=!1}};return pe.addEventListener("touchstart",be,{passive:!1}),pe.addEventListener("touchmove",fe,{passive:!1}),pe.addEventListener("touchend",ve,{passive:!1}),()=>{pe.removeEventListener("touchstart",be),pe.removeEventListener("touchmove",fe),pe.removeEventListener("touchend",ve),w.current&&clearTimeout(w.current)}},[e,s,r,o,l,c,d,m,u,h,g,f,p,b]),{cursorPos:I,cursorPosRef:j,handleToggleInputMode:()=>{a(pe=>{const ke=pe==="touch"?"mouse":"touch";return ke==="mouse"&&ye(),ke})},handleZoomReset:()=>{const pe=y?x:1;h(pe),l.current=pe,m(0),u(0),c.current=0,d.current=0}}}function yc({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const l=i.useRef(null),c=i.useRef(null),d=i.useRef(null),[m,u]=i.useState(null),[h,g]=i.useState(""),[,k]=i.useState(!1),[f,p]=i.useState([]),b=i.useRef(0),[y,x]=i.useState(!1),[I,N]=i.useState(!1),j=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[A,M]=i.useState(j?"mouse":"touch"),[v,w]=i.useState(1),B=i.useRef(!1),[R,T]=i.useState(1),[H,E]=i.useState(0),[D,S]=i.useState(0);Ar("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:A,zoom:R,panX:H,panY:D,isMenuOpen:y,isImeOpen:I});const C=i.useRef(0),W=i.useRef(R),_=i.useRef(H),O=i.useRef(D);i.useEffect(()=>{W.current=R},[R]),i.useEffect(()=>{_.current=H},[H]),i.useEffect(()=>{O.current=D},[D]),i.useEffect(()=>{var ae;(ae=l.current)==null||ae.focus()},[]);const V=r==="connected",X=n,ye=V?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",he=V?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!j||B.current||!X)return;const ae=d.current,xe=c.current;if(!ae||!xe)return;const ue=()=>{const ce=xe.clientWidth,te=xe.clientHeight,$=ae.naturalWidth,J=ae.naturalHeight;if(!$||!J||!ce||!te)return;const oe=Math.min(ce/$,te/J),Ne=Math.max(ce/$,te/J)/oe;Ne>1.01&&(w(Ne),T(Ne),W.current=Ne),B.current=!0};ae.complete&&ae.naturalWidth?ue():ae.addEventListener("load",ue,{once:!0})},[X,j]);const ne=.5;i.useEffect(()=>{R<=ne&&(E(0),S(0))},[R,ne]);const pe=(ae,xe,ue)=>{if(ue<=ne)return{x:0,y:0};const ce=(ue-1)/(2*ue)*100,te=(ue-1)/(2*ue)*100;return{x:Math.max(-ce,Math.min(ce,ae)),y:Math.max(-te,Math.min(te,xe))}},ke=(ae,xe)=>{if(!d.current)return null;const ue=d.current.getBoundingClientRect();return!ue.width||!ue.height?null:{nx:Math.max(0,Math.min(1,(ae-ue.left)/ue.width)),ny:Math.max(0,Math.min(1,(xe-ue.top)/ue.height))}},Se=(ae,xe,ue)=>{const ce=c.current;if(!ce)return;const te=ce.getBoundingClientRect(),$=++b.current;p(J=>[...J,{id:$,x:ae-te.left,y:xe-te.top,type:ue}]),setTimeout(()=>p(J=>J.filter(oe=>oe.id!==$)),600)},G=(ae,xe,ue)=>{const ce=d.current,te=c.current;if(!ce||!te)return;const $=ce.getBoundingClientRect(),J=te.getBoundingClientRect(),oe=ce.naturalWidth||$.width,ee=ce.naturalHeight||$.height,Ne=oe/ee,Ce=$.width/$.height;let we,K,Ie,Re;Ne>Ce?(we=$.width,K=$.width/Ne,Ie=0,Re=($.height-K)/2):(K=$.height,we=$.height*Ne,Ie=($.width-we)/2,Re=0);const Ke=$.left-J.left+Ie+we*ae,He=$.top-J.top+Re+K*xe,qe=++b.current;p(Ye=>[...Ye,{id:qe,x:Ke,y:He,type:ue}]),setTimeout(()=>p(Ye=>Ye.filter(st=>st.id!==qe)),600)},be=async ae=>{var ue;const xe=ke(ae.clientX,ae.clientY);if(xe){u(`Click: ${Math.round(xe.nx*100)}%, ${Math.round(xe.ny*100)}%`),Se(ae.clientX,ae.clientY,"left"),(ue=l.current)==null||ue.focus();try{const ce=await e("input_click",{nx:xe.nx,ny:xe.ny});ce!=null&&ce.success||s(`❌ Click failed: ${ce==null?void 0:ce.error}`)}catch(ce){s(`❌ Click error: ${ce.message||ce}`)}}},fe=async(ae,xe,ue,ce=0)=>{try{await e("input_key",{type:ue?"char":"keyDown",key:ae,code:xe,text:ue?ae:void 0,unmodifiedText:ue?ae:void 0,modifiers:ce})}catch(te){s(`❌ Key error: ${te.message||te}`)}},ve=async ae=>{if(ae.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ae.key)&&ae.preventDefault();let ue=0;ae.altKey&&(ue|=1),ae.ctrlKey&&(ue|=2),ae.metaKey&&(ue|=4),ae.shiftKey&&(ue|=8),u(`Key: ${ae.key}`),await fe(ae.key,ae.code,ae.key.length===1,ue)},P=async ae=>{if(ae.key==="Enter"){if(ae.nativeEvent.isComposing)return;if(h){const xe=h;g(""),u(`IME Sent: ${xe}`);try{const ue=await e("input_type",{text:xe});ue!=null&&ue.success||s(`❌ IME error: ${ue==null?void 0:ue.error}`)}catch(ue){s(`❌ IME error: ${ue.message}`)}}else u("Key: Enter"),await fe("Enter","Enter",!1)}};i.useEffect(()=>{const ae=l.current;if(!ae)return;const xe=ue=>{var ce;if((ce=d.current)!=null&&ce.contains(ue.target)){ue.preventDefault();const te=Date.now();if(te-C.current<40)return;C.current=te;const $=ke(ue.clientX,ue.clientY);if(!$)return;u(`Scroll: ${Math.round(ue.deltaY)}`),e("input_wheel",{nx:$.nx,ny:$.ny,deltaX:Math.round(ue.deltaX),deltaY:Math.round(ue.deltaY)}).catch(()=>{})}};return ae.addEventListener("wheel",xe,{passive:!1}),()=>ae.removeEventListener("wheel",xe)},[e]);const{cursorPos:me,handleToggleInputMode:q,handleZoomReset:de}=Lp({containerRef:l,viewportRef:c,imgRef:d,inputMode:A,setInputMode:M,minZoom:ne,zoomRef:W,panXRef:_,panYRef:O,setPanX:E,setPanY:S,setZoom:T,lastWheelTimeRef:C,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:G,clampPan:pe,isMobile:j,mobileFillZoom:v});return t.jsxs("div",{ref:l,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ve,onContextMenu:ae=>ae.preventDefault(),onFocus:()=>k(!0),onBlur:()=>k(!1),tabIndex:0,children:[t.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[X?t.jsx("img",{ref:d,src:X,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${R}) translate(${H}%, ${D}%)`,transformOrigin:"center center",cursor:A==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:be,onContextMenu:ae=>ae.preventDefault(),onDragStart:ae=>ae.preventDefault()}):t.jsx(Ap,{waitingLabel:ye,waitingHint:he,transportType:o}),A==="mouse"&&X&&t.jsx(Ip,{cursorPos:me,viewportRef:c,imgRef:d}),f.map(ae=>{const ue={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ae.type];return t.jsxs("div",{style:{position:"absolute",left:ae.x,top:ae.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ue}, 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(${ue}, 0.9)`,boxShadow:`0 0 12px rgba(${ue}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ae.id)})]}),t.jsx(Tp,{inputMode:A,onToggleInputMode:q,isImeOpen:I,setIsImeOpen:N,isMenuOpen:y,setIsMenuOpen:x,imeText:h,setImeText:g,handleImeSubmit:P,isConnActive:V,zoom:R,isMobile:j,mobileFillZoom:v,onZoomOut:()=>T(ae=>Math.max(.5,ae-.25)),onZoomReset:de,onZoomIn:()=>T(ae=>Math.min(5,ae+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),t.jsx("style",{children:`
|
|
7
|
-
@keyframes slideUp {
|
|
8
|
-
from { opacity: 0; transform: translateY(6px); }
|
|
9
|
-
to { opacity: 1; transform: translateY(0); }
|
|
10
|
-
}
|
|
11
|
-
@keyframes slideUpSidebar {
|
|
12
|
-
from { opacity: 0; transform: translateY(6px); }
|
|
13
|
-
to { opacity: 1; transform: translateY(0); }
|
|
14
|
-
}
|
|
15
|
-
@keyframes click-ripple-ring {
|
|
16
|
-
0% { transform: scale(0.3); opacity: 1; }
|
|
17
|
-
100% { transform: scale(2.2); opacity: 0; }
|
|
18
|
-
}
|
|
19
|
-
@keyframes click-ripple-dot {
|
|
20
|
-
0% { transform: scale(1); opacity: 0.9; }
|
|
21
|
-
50% { transform: scale(1.8); opacity: 0.6; }
|
|
22
|
-
100% { transform: scale(0.5); opacity: 0; }
|
|
23
|
-
}
|
|
24
|
-
@keyframes remote-float {
|
|
25
|
-
0% { transform: translateY(0px); }
|
|
26
|
-
50% { transform: translateY(-7px); }
|
|
27
|
-
100% { transform: translateY(0px); }
|
|
28
|
-
}
|
|
29
|
-
`})]})}function $n(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=s,o=Date.now()-e,l=Math.floor(o/1e3);if(l<a)return n;const c=Math.floor(l/60);if(c<60)return`${c}m${r}`;const d=Math.floor(c/60);if(d<24)return`${d}h${r}`;const m=Math.floor(d/24);return m<7?`${m}d${r}`:new Date(e).toLocaleDateString()}const vc=e=>$n(e);function Rp(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 Ys(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 _p(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...Rp(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 jn(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 Bn(e,s,r){const n=jn(e,s),a=Ys(e),o=a.isReconnecting,l=a.isConnecting,c=a.isGenerating,d=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=n.inboxBucket==="working"||c,g=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:g,requiresAction:m,isWorking:u,isReconnecting:o,isConnecting:l,isGenerating:c,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":g?"task_complete":"idle"}}function Pp(e,s,r){return Bn(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function wc({activeConv:e,onModalButton:s}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ys(e).isWaiting||!e.modalButtons)return null;const o=c=>{r||(n(c),s(c))},l=c=>c.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(Sr,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,d)=>{const m=l(c).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(m),h=/^(reject|deny|delete|remove|abort)/.test(m),g=r===c,k=r!==null;return t.jsx("button",{onClick:()=>o(c),disabled:k,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${k&&!g?"opacity-40":"opacity-100"} ${k?"cursor-not-allowed":"cursor-pointer"}`,style:u?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:h?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?"⏳ ...":l(c)},d)})})]})]})}const Lo="adhdev_controls_bar_visible",eo="adhdev:controlsbarvisibilitychange";function sa(e){if(!e)return!1;try{return e.getItem(Lo)==="1"}catch{return!1}}function Dp(e,s){if(s)try{s.setItem(Lo,e?"1":"0")}catch{}}function Ep(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(eo,{detail:{visible:e}}))}function Ro(){const[e,s]=i.useState(()=>typeof window>"u"?!1:sa(window.localStorage)),r=i.useRef(e),n=i.useCallback((l,c=!0)=>{r.current=l,s(l),typeof window<"u"&&Dp(l,window.localStorage),c&&Ep(l)},[]);i.useEffect(()=>{const l=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:sa(window.localStorage);r.current=u,s(u)},c=d=>{if(d.key!==Lo)return;const m=sa(window.localStorage);r.current=m,s(m)};return window.addEventListener(eo,l),window.addEventListener("storage",c),()=>{window.removeEventListener(eo,l),window.removeEventListener("storage",c)}},[]);const a=i.useCallback(l=>{n(l)},[n]),o=i.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var $p=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Bp(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function gt(e,s){if(Bp(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":$p.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 kn(e){return gt(e)==="generating"}function Pi(e,s){return gt(e,s)==="waiting_approval"}function lt(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function Op(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),o=r%24;return`${a}d ${o}h`}function ra(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function On(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(/[\\/]+$/,""),o=a.split(/[\\/]/).filter(Boolean);return o[o.length-1]||a}function Fp(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 Kp(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Wp(e){return Fp(e.trim().replace(/\.local$/i,""))}function Hp(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function jc(e,s={}){var a,o;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(o=e.system)==null?void 0:o.hostname].find(l=>typeof l=="string"&&l.trim().length>0&&!Kp(l));if(r&&r!=="Unknown")return Wp(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function At(e,s={}){return Hp(e)||jc(e,s)}function kc(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 Nc(e,s,r={}){const n=String(s).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(o=>String((o==null?void 0:o.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function Ns(e,s){return kc(e).join(" · ")}function Cr(e){return e.transport==="pty"}function $s(e){return e.transport==="acp"}function Up(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:lt(e)}function Di(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),l=lt(r||"").trim().toLowerCase();return n===a||n===o||n===l}function zp(e,s=[],r=[]){var d,m,u,h;const n=gt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(n==="waiting_approval")return"waiting_approval";if(n==="generating")return"generating";const a=s.find(g=>Pi(g.status,{activeModal:g.activeModal})||kn(g.status));if(a)return gt(a.status,{activeModal:a.activeModal});const o=r.find(g=>Pi(g.status,{activeModal:g.activeModal})||kn(g.status));if(o)return gt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const l=gt((d=s[0])==null?void 0:d.status,{activeModal:(m=s[0])==null?void 0:m.activeModal});if(l!=="idle")return l;const c=gt((u=r[0])==null?void 0:u.status,{activeModal:(h=r[0])==null?void 0:h.activeModal});return c!=="idle"?c:"idle"}function Vp(e){return gt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Gp(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,"-"),o=s.get(a),l=gt(n.status);if(!o){s.set(a,{...n,status:l});continue}const c=r.indexOf(o.status||"idle"),d=r.indexOf(l||"idle");d>=0&&(c<0||d<c)&&s.set(a,{...n,status:l})}return Array.from(s.values())}function qp(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 Yp(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&&qp(s.receivedAt)||0}function Xp(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function to(e){return Math.max(Xp(e),Yp(e.activeChat))}function Jp(e,s,r,n,a,o){const l=s-e;if(l!==0)return l;const c=r.localeCompare(n);return c!==0?c:a.localeCompare(o)}function _o(e,s){return Jp(to(e),to(s),At(e,{fallbackId:e.id}),At(s,{fallbackId:s.id}),e.id,s.id)}const Sc="adhdev_notification_prefs",Ei={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Qp(){try{const e=localStorage.getItem(Sc);if(e){const s=JSON.parse(e);return{...Ei,...s}}}catch{}return{...Ei}}function Zp(e){try{localStorage.setItem(Sc,JSON.stringify(e))}catch{}}let qt=Qp(),ln=[];function ef(){ln.forEach(e=>e())}function tf(e){qt={...qt,...e},Zp(qt),ef()}function sf(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return ln.push(r),()=>{ln=ln.filter(n=>n!==r)}},[]);const s=i.useCallback(r=>{tf(r)},[]);return[{...qt},s]}function xr(e){if(!qt.globalEnabled)return!1;switch(e){case"disconnect":return qt.disconnectAlert;case"completion":return qt.completionAlert;case"approval":return qt.approvalAlert;case"browser":return qt.browserNotifications;default:return!0}}const rf={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Cc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Ic(){return"Notification"in window&&Notification.permission==="granted"}let cs=null;function nf(e){return e!==!1}async function af(){if(cs!==null)return cs;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return cs=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(cs=!!await e.pushManager.getSubscription(),cs):(cs=!1,!1)}catch{return cs=!1,!1}}function so(e,s,r){if(Ic())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 of(e,s={}){const r={...rf,...s},n=i.useRef(new Map),a=i.useRef(0),[o,l]=i.useState(null);i.useEffect(()=>{let d=!1;return af().then(m=>{d||l(m)}),()=>{d=!0}},[]);const c=i.useCallback((d,m,u)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,so(d,m,u))},[r.throttleMs]);i.useEffect(()=>{var d;if(!(!r.enabled||!Ic())&&xr("browser")&&!nf(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,gt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),h=gt(m.status,{activeModal:m.activeModal}),g=m.name||m.id;if(r.onApproval&&xr("approval")&&h==="waiting_approval"&&u!=="waiting_approval"){const k=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${g} — Approval needed`,k.slice(0,120),`approval-${m.id}`)}r.onComplete&&xr("completion")&&kn(u)&&h==="idle"&&c(`✅ ${g} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&h==="error"&&u!=="error"&&c(`⚠️ ${g} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,h)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const lf=/^(run|approve|accept|yes|allow|always)/,cf=/^(run|approve|accept|yes|allow|always|proceed|save)/,df=/^(reject|deny|delete|remove|abort|cancel|no)/;function Po(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function uf(e){const s=Po(e).toLowerCase();return lf.test(s)?"primary":df.test(s)?"danger":"default"}function mf(e){return cf.test(Po(e).toLowerCase())?"approve":"reject"}function pf(e){return e.map((s,r)=>({label:Po(s),variant:uf(s),action:mf(s),button:s,buttonIndex:r}))}function ff(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function hf(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 xf{constructor(){Je(this,"dedupMap",new Map);Je(this,"DEDUP_WINDOW_MS",5e3);Je(this,"DEDUP_MAX_SIZE",50);Je(this,"DEDUP_CLEANUP_AGE_MS",1e4);Je(this,"toastCallbacks",[]);Je(this,"statusEventCallbacks",[]);Je(this,"resolveActionFn",null);Je(this,"viewRequestRespondFn",null);Je(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onStatusEvent(s){return this.statusEventCallbacks.push(s),()=>{this.statusEventCallbacks=this.statusEventCallbacks.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})}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,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(s){if(s.daemonId){const a=this.ides.find(o=>o.id===s.daemonId&&o.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 o=this.ides.find(l=>l.id===a&&l.type==="adhdev-daemon");if(o)return o}}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 f;const n=this.resolveConversationKey(s),a=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),o=n||s.daemonId||"",l=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(a),c=`${o}:${s.event}:${l}`;if(this.isDuplicate(c))return;for(const p of this.statusEventCallbacks)p(s);const d=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=lt(m);const h=this.resolveOwningDaemon(s);if(h){const p=At(h,{fallbackId:h.id});p&&(u=!m||m==="adhdev-daemon"?p:`${p}/${u}`)}let g="",k="info";if(s.event==="agent:generating_completed"){const p=s.duration?` (${s.duration}s)`:"";g=`✅ ${u} agent task completed${p}`,k="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(g=`⚡ ${u} approval needed`,k="warning",(f=s.modalButtons)!=null&&f.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(s);if(!p)return;const b=this.resolveActionFn,y=pf(s.modalButtons).map(N=>({label:N.label,variant:N.variant,onClick:()=>{b(p,"resolve_action",{action:N.action,button:N.button,buttonIndex:N.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),x=ff(u,s.modalMessage,g),I=Date.now();this.emitToast({id:I,message:x,type:k,timestamp:I,targetKey:n||p,actions:y,duration:15e3}),g=""}}else if(s.event==="monitor:long_generating"){const p=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";g=`⚠️ ${u} agent is taking a long time${p}`,k="warning",xr("browser")&&!document.hasFocus()&&so(`⚠️ ${u} — 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,y=s.orgId;if(g=`👁️ ${p} wants to view your session`,k="warning",b&&y&&this.viewRequestRespondFn){const x=Date.now(),I=hf(y,b,this.viewRequestRespondFn,(N,j)=>console.error(`[EventManager] ${N} view request failed:`,j));this.emitToast({id:x,message:g,type:k,timestamp:x,actions:I,duration:3e4}),g=""}xr("browser")&&!document.hasFocus()&&so("👁️ View Request",`${p} wants to view your session`,`view-request-${b}`)}else s.event==="team:view_request_approved"?(g="✅ View request approved",k="success"):s.event==="team:view_request_rejected"&&(g=`❌ ${s.targetName||"Team member"} declined your view request`,k="warning");if(g){const p=Date.now();this.emitToast({id:p,message:g,type:k,timestamp:p,targetKey:n||s.daemonId,duration:5e3})}}}const ot=new xf,$i=new Map;function Nn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Bs(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Fn(e){return Nn(e)?Nn(e.result)?e.result:e:null}function bf(e){const s=Fn(e);return!s||!Nn(s.controlResult)||!Array.isArray(s.controlResult.options)?null:s.controlResult}function Ur(e){const s=Fn(e);return!s||!Nn(s.controlResult)||typeof s.controlResult.ok!="boolean"?null:s.controlResult}function tr(e){const s=Fn(e);if(!(!s||typeof s.error!="string"||!s.error.trim()))return s.error}function zr(e){const s=Fn(e);return!!s&&s.success===!1}function gf(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";ot.showToast(n.toast.message,a);continue}if(n.type==="notification"&&((r=n.notification)!=null&&r.body)){const a=n.notification.level==="warning"?"warning":n.notification.level==="success"?"success":"info";ot.showToast(n.notification.body,a)}}}function yf(e,s){return e&&Bs(e.currentValue)?e.currentValue:s}function vf(e,s){return Bs(s)?Bs(e)?typeof e=="string"&&e.trim()==="":!0:!1}function wf(e,s){var o,l;if((s.now??Date.now())<s.localOverrideUntil){const c=s.localValues[e];if(Bs(c))return c}const n=(o=s.controlValues)==null?void 0:o[e];if(Bs(n))return n;const a=(l=s.defaultValues)==null?void 0:l[e];return Bs(a)?a:void 0}function cn(e,s){return e.options||s[e.id]||[]}const jf={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function kf(e,s,r){var n;return((n=jf[s])==null?void 0:n.has(r.id))===!0}function Do(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!kf(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function na(e,s){return{value:s}}function Nf(e,s,r){var a;return r?((a=cn(e,s).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Sf={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Cf({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:l}){const{sendCommand:c}=wt(),d=`${e}:${s||n}`,m=Sf[n]||"#94a3b8",[u,h]=i.useState({}),g=i.useRef({}),k=i.useRef(l);g.current=u,k.current=l;const f=i.useRef(0),p={};for(const C of o||[])C.defaultValue!==void 0&&(p[C.id]=C.defaultValue);const b={...p,...l||{},...Date.now()<f.current?u:{}};i.useEffect(()=>{l&&Date.now()>f.current&&h({})},[l]);const[y,x]=i.useState($i.get(d)||{}),[I,N]=i.useState(null),[j,A]=i.useState(null),M=i.useCallback(async(C,W={})=>{const _={...W,...s&&{targetSessionId:s}};return await c(e,C,_)},[e,s,c]),v=i.useCallback(async(C,W={})=>{const _=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await M("invoke_provider_script",{..._,scriptName:C,...W})},[M,n,r,s]),w=i.useCallback((C,W,_)=>{const O=yf(_,W);h(V=>({...V,[C.id]:O})),gf(_==null?void 0:_.effects)},[]),B=i.useCallback((C,W)=>{h(_=>{const O={..._};return W===void 0?delete O[C.id]:O[C.id]=W,O}),f.current=0},[]);if(!o||o.length===0)return null;const R=Do(o,{hostIdeType:r,providerType:n});if(R.length===0)return null;const T=async C=>{if(I===C.id){N(null);return}if(cn(C,y).length>0){N(C.id);return}if(C.dynamic&&C.listScript){A(C.id);try{const _=await v(C.listScript,{}),O=bf(_);if(!O){const ye=tr(_);ye&&ot.showToast(ye,"warning");return}const V=O.options;x(ye=>{const he={...ye,[C.id]:V};return $i.set(d,he),he});const X=wf(C.id,{localOverrideUntil:f.current,localValues:g.current,controlValues:k.current,defaultValues:p});if(vf(X,O.currentValue)){const ye=O.currentValue;h(he=>({...he,[C.id]:ye}))}N(C.id)}catch(_){const O=_ instanceof Error?_.message:`Could not load ${C.label}`;ot.showToast(O,"warning")}finally{A(null)}}},H=async(C,W)=>{N(null);const _=(l==null?void 0:l[C.id])??p[C.id];h(O=>({...O,[C.id]:W})),f.current=Date.now()+5e3;try{if(!C.setScript)return;const O=await v(C.setScript,na(C,W)),V=Ur(O);if(V&&!V.ok||zr(O))throw new Error((V==null?void 0:V.error)||tr(O)||`Could not update ${C.label}`);w(C,W,V)}catch(O){B(C,_);const V=O instanceof Error?O.message:`Could not update ${C.label}`;ot.showToast(V,"warning")}},E=async C=>{const W=cn(C,y).map(he=>he.value);if(W.length===0)return;const _=String(b[C.id]||""),V=(W.indexOf(_)+1)%W.length,X=W[V];if(typeof X!="string")return;const ye=(l==null?void 0:l[C.id])??p[C.id];h(he=>({...he,[C.id]:X})),f.current=Date.now()+5e3;try{if(!C.setScript)return;const he=await v(C.setScript,na(C,X)),ne=Ur(he);if(ne&&!ne.ok||zr(he))throw new Error((ne==null?void 0:ne.error)||tr(he)||`Could not update ${C.label}`);w(C,X,ne)}catch(he){B(C,ye);const ne=he instanceof Error?he.message:`Could not update ${C.label}`;ot.showToast(ne,"warning")}},D=async C=>{const _=!b[C.id],O=(l==null?void 0:l[C.id])??p[C.id];h(V=>({...V,[C.id]:_})),f.current=Date.now()+5e3;try{if(!C.setScript)return;const V=await v(C.setScript,na(C,_)),X=Ur(V);if(X&&!X.ok||zr(V))throw new Error((X==null?void 0:X.error)||tr(V)||`Could not update ${C.label}`);w(C,_,X)}catch(V){B(C,O);const X=V instanceof Error?V.message:`Could not update ${C.label}`;ot.showToast(X,"warning")}},S=async C=>{if(!C.invokeScript)return;if(C.confirmMessage){const _=[C.confirmTitle,C.confirmMessage,C.confirmLabel].filter(V=>typeof V=="string"&&V.trim().length>0);if(!window.confirm(_.join(`
|
|
30
|
-
|
|
31
|
-
`)))return}const W=(l==null?void 0:l[C.id])??p[C.id];try{const _=await v(C.invokeScript),O=Ur(_);if(O&&!O.ok||zr(_))throw new Error((O==null?void 0:O.error)||tr(_)||`Could not run ${C.label}`);O&&w(C,W??!0,O)}catch(_){B(C,W);const O=_ instanceof Error?_.message:`Could not run ${C.label}`;ot.showToast(O,"warning")}};return t.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),R.map(C=>{const W=String(b[C.id]||""),_=Nf(C,y,W),O=I===C.id,V=j===C.id,X=cn(C,y),ye="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(C.type){case"select":return t.jsxs("div",{className:"relative max-w-full",children:[t.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:O?`${m}55`:"var(--border-default)",background:O?`${m}10`:"var(--surface-tertiary)",color:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void T(C),title:C.label,children:[C.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:C.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:V?"Loading…":_||C.label}),t.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),O&&X.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>N(null)}),t.jsxs("div",{className:"absolute bottom-full left-0 z-[60] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[t.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:C.label}),X.map(he=>t.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:he.value===W?`${m}14`:"transparent",color:he.value===W?"var(--text-primary)":"var(--text-secondary)",borderLeft:he.value===W?`2px solid ${m}`:"2px solid transparent"},title:he.description||he.label,onMouseEnter:ne=>{ne.currentTarget.style.background=`${m}10`},onMouseLeave:ne=>{ne.currentTarget.style.background=he.value===W?`${m}14`:"transparent"},onClick:()=>void H(C,he.value),children:[t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:he.label}),he.value===W&&t.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},he.value))]})]})]},C.id);case"cycle":return t.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:W?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void E(C),title:`Click to cycle: ${X.map(he=>he.label).join(" → ")}`,children:[C.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:C.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:_||C.label}),t.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},C.id);case"toggle":return t.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:W?`${m}44`:"var(--border-default)",background:W?`${m}14`:"var(--surface-tertiary)",color:W?m:"var(--text-muted)"},onClick:()=>void D(C),"aria-pressed":!!W,children:[C.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:C.icon}),C.label]},C.id);case"action":return t.jsxs("button",{type:"button",className:`${ye} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void S(C),children:[C.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:C.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:C.resultDisplay==="inline"&&W?`${C.label}: ${W}`:C.label})]},C.id);case"display":return t.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:W?"var(--text-primary)":"var(--text-muted)"},children:[C.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:C.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?`${C.label}: ${W}`:C.label})]},C.id);default:return null}})]})})}function If({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:c,controlValues:d}){const{isVisible:m}=Ro(),u=Do(c,{hostIdeType:a,providerType:o});return!e||s||u.length===0||!m?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(Cf,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:u,controlValues:d})})}const sr=5,Tc=10*1024*1024;function Tf({hasDraft:e,isBusy:s=!1}){return!e||s}function Af(e){return new Promise((s,r)=>{const n=new FileReader;n.onload=()=>s(n.result),n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}async function Mf(e){if(e.size>Tc)return null;const s=await Af(e),r=s.indexOf(",");if(r<0)return null;const n=s.slice(r+1);return{mimeType:e.type||"image/png",data:n,name:e.name,previewUrl:s}}function Lf(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Ac=i.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:l,isActive:c=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u,messageInput:h}){const g=i.useRef(null),k=i.useRef(null),[f,p]=i.useState(""),[b,y]=i.useState([]),[x,I]=i.useState(null),[N,j]=i.useState(!1),A=i.useRef(!1),{isVisible:M,toggleVisibility:v}=Ro(),w=Lf(h),B=!!f.trim()||b.length>0;i.useEffect(()=>{p(""),y([]),I(null)},[s]),i.useEffect(()=>{var C;c&&((C=g.current)==null||C.focus({preventScroll:!0}))},[s,c]);const R=i.useCallback(async C=>{I(null);const W=Array.from(C).filter(he=>he.type.startsWith("image/"));if(W.length===0)return;const _=sr-b.length;if(_<=0){I(`Max ${sr} images`);return}const O=W.slice(0,_);if(O.filter(he=>he.size>Tc).length>0){I("Image too large (max 10 MB)");return}const ye=(await Promise.all(O.map(Mf))).filter(he=>he!==null);y(he=>[...he,...ye])},[b.length]),T=i.useCallback(C=>{y(W=>W.filter((_,O)=>O!==C))},[]),H=i.useCallback(async()=>{const C=f.trim();if(!C&&b.length===0||a||A.current)return;A.current=!0;const W=b.length>0?[...b]:void 0;try{await l(C,W)!==!1&&(p(""),y([]),I(null))}finally{A.current=!1}},[f,b,a,l]),E=i.useCallback(C=>{w&&(C.preventDefault(),j(!0))},[w]),D=i.useCallback(()=>j(!1),[]),S=i.useCallback(C=>{w&&(C.preventDefault(),j(!1),C.dataTransfer.files.length>0&&R(C.dataTransfer.files))},[w,R]);return t.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",N?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:c?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:c?200:0,opacity:c?1:0,transform:c?"translateY(0)":"translateY(10px)",padding:c?"10px 12px":"0 12px",pointerEvents:c?"auto":"none"},"aria-hidden":!c,onDragOver:E,onDragLeave:D,onDrop:S,children:[b.length>0&&t.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:b.map((C,W)=>t.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[t.jsx("img",{src:C.previewUrl,alt:C.name,className:"w-full h-full object-cover"}),t.jsx("button",{type:"button",onClick:()=>T(W),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${C.name}`,children:"✕"})]},W))}),t.jsxs("div",{className:"flex gap-2 items-center",title:c?`Send message to ${r}`:void 0,children:[d&&t.jsx("button",{type:"button",onClick:()=>{v(),u==null||u()},"aria-label":M?"Hide controls":"Show controls","aria-pressed":M,title:M?"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"})]})}),w&&t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:k,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:C=>{C.target.files&&R(C.target.files),C.target.value=""}}),t.jsx("button",{type:"button",onClick:()=>{var C;return(C=k.current)==null?void 0:C.click()},disabled:b.length>=sr,title:b.length>=sr?`Max ${sr} images`:"Attach image",className:"h-10 w-8 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 disabled:opacity-40","aria-label":"Attach image",children:t.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:g,type:"text",placeholder:o||(w&&b.length>0?"Add a message (optional)...":`Send message to ${r}...`),value:f,onChange:C=>p(C.target.value),onPaste:C=>{if(w&&C.clipboardData.files.length>0&&Array.from(C.clipboardData.files).some(O=>O.type.startsWith("image/"))){C.preventDefault(),R(C.clipboardData.files);return}const W=C.clipboardData.getData("text");W&&p(_=>_+W),C.preventDefault()},onKeyDown:C=>{if(C.key==="Enter"){if(C.nativeEvent.isComposing){C.preventDefault();return}C.preventDefault(),H()}},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:()=>{H()},disabled:Tf({hasDraft:B,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${B&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:B&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",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:B?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(x||w&&N)&&t.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${x?"text-red-400":"text-[var(--accent-primary)]"}`,children:x||"Drop image here"}),o&&!x&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})}),nt=e=>e.transport==="pty",Xs=(e,s)=>nt(e)?e.mode||"terminal":"chat",Mc=(e,s)=>nt(e)&&Xs(e)==="terminal",tt=e=>e.transport==="acp",Rf=180;function os(e){return e.streamSource!=="agent-stream"}function Ts(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function Lc(e){return e.machineName||""}function Mr(e){return Ts(e)}function Ut(e){return e.agentType||""}function Sn(e){return e.hostIdeType||""}function Eo(e){return e.displayPrimary||e.agentName||"Agent"}function Rc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function _f(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function _c(e){const s=_f(e),r=Ks(s==null?void 0:s.content),n=Ks(e.lastMessagePreview);return r||n||""}function Pf(e,s=Rf){const r=Ks(e);if(!r||s<=0)return"";const n=Array.from(r);return n.length<=s?r:`${n.slice(0,Math.max(0,s-1)).join("").trimEnd()}…`}function Df(e){return Pf(_c(e)||e.displaySecondary||"")}function Pc(e){return[e.displaySecondary,Lc(e)].filter(Boolean)}function Hs(e){return e.agentName||lt(Ut(e))}function Ef(e){var s,r;if(!os(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return lt(Sn(e)||Ut(e))}function Dc(e){return os(e)?e.sessionId:e.nativeSessionId}function Bi(e){return os(e)?"native":e.tabKey}function $f(e){return e.sessionId}function Bf(e,s){if(s)return os(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Of(e,s){const r=Ut(e),n=os(e),a=nt(e)||tt(e),o=n?a?Hs(e)||(s==null?void 0:s.cliName)||lt(Sn(e)||r):s!=null&&s.type?lt(s.type):lt(Sn(e)||r):Hs(e);return{isNativeConversation:n,isCli:nt(e),isAcp:tt(e),isCliTerminal:Mc(e),providerType:r,displayLabel:o,targetEntry:Bf(e,s)}}function fs(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:nt(e)||tt(e)?{agentType:Ut(e)}:e.streamSource==="agent-stream"?{agentType:Ut(e)}:s}function Us(e){return e?Mr(e):""}function rr(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function $o(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Ff(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."}function Ec(){return"select_session"}function Kf(){return"open_panel"}function Wf({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function Hf(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function Oi(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function Cn(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Bo(e){return e instanceof Error?e.message:String(e||"")}function Fi(e){const s=Bo(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Ki(e,s){const r=Bo(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Uf(e,s,r){const n=fs(r);if(!s||s.length===0)return{message:e,...n};const a=s.map(o=>({type:"image",mimeType:o.mimeType,data:o.data,alt:o.name}));return e&&a.push({type:"text",text:e}),{message:e,input:{parts:a,textFallback:e},...n}}function Kn({sendDaemonCommand:e,activeConv:s,setActionLogs:r,isStandalone:n}){const[a,o]=i.useState(!1),[l,c]=i.useState(!1),[d,m]=i.useState(null),u=i.useRef(!1),h=i.useRef(null);i.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const g=i.useCallback(async(b,y)=>{if(!s||u.current)return!1;const x=b.trim(),I=$o(s);if(Wf({hasMessage:!!x,blockedMessage:I,sendInFlight:u.current}))return I&&m(I),!1;const N=Date.now(),j={tabKey:s.tabKey,message:x,timestamp:N};if(Hf(h.current,j))return m(null),!0;u.current=!0,c(!0),m(null),h.current=j;try{const A=Us(s);if(!A)return h.current=Oi(h.current,j),m("Unable to send message right now."),!1;const M=await e(A,"send_chat",Uf(x,y,s)),v=Cn(M);if(v!=null&&v.deduplicated)return m(null),!0;if((v==null?void 0:v.sent)===!1)throw new Error((v==null?void 0:v.error)||"Send failed");if((v==null?void 0:v.success)===!1)throw new Error((v==null?void 0:v.error)||"Send failed");return m(null),!0}catch(A){const M=Bo(A);return M.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",M):console.warn("Send blocked/failed",A),h.current=Oi(h.current,j),m(Ff(A)),!1}finally{u.current=!1,c(!1)}},[s,e]),k=i.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]),f=i.useCallback(async b=>{if(s)try{const x=(s.modalButtons||[]).indexOf(b),I=b.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(I),j=Us(s);if(!j)return;const A=await e(j,"resolve_action",{button:b,action:N?"approve":"reject",...x>=0&&{buttonIndex:x},...fs(s)}),M=Cn(A);M.success||r(v=>[...v,{routeId:s.tabKey,text:Ki(b,M==null?void 0:M.error),timestamp:Date.now()}])}catch(y){Fi(y)||console.error("[ModalButton] Error:",y),r(x=>[...x,{routeId:s.tabKey,text:Fi(y)?Ki(b,y):`❌ **${b}** error`,timestamp:Date.now()}])}},[s,e,r]),p=i.useCallback(async()=>{if(!(!s||a)){o(!0);try{await e(s.routeId,Kf(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(b){console.error("Focus agent failed",b)}finally{o(!1)}}},[s,a,e]);return{isSendingChat:l,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:g,handleRelaunch:k,handleModalButton:f,handleFocusAgent:p}}const zf=10,Vf=8e3,Gf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function qf(e){return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s'"`]+/gi,"$1[REDACTED:bearer]").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]{12,}=*/gi,"$1[REDACTED:bearer]").replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{20,}\b/g,"[REDACTED:github-token]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:api-key]").replace(/\b(?:adk|adm)_[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:adhdev-token]").replace(/((?:api[_-]?key|token|secret|password|passwd|client[_-]?secret)\s*[:=]\s*)[^\s,'"`}&]+/gi,"$1[REDACTED:secret]").replace(/([?&](?:api[_-]?key|token|secret|password|client_secret)=)[^&#\s]+/gi,"$1[REDACTED:secret]")}function ro(e,s="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Gf.test(s)&&e.trim())return"[REDACTED:secret-field]";const n=qf(e);return n.length>8e3?`${n.slice(0,8e3)}…[truncated ${n.length-8e3} chars]`:n}if(typeof e!="object")return String(e);if(r>=6)return"[MaxDepth]";if(Array.isArray(e)){const n=e.slice(-20).map(a=>ro(a,s,r+1));return e.length>20?[{truncatedBefore:e.length-20},...n]:n}return Object.fromEntries(Object.entries(e).slice(0,80).map(([n,a])=>[n,ro(a,n,r+1)]))}function nr(e,s){return Array.isArray(e)?e.slice(-s):[]}function Yf(e,s=Date.now()){const r=e&&s-e.firstAt<=Vf,n=r?e.count+1:1;return n>=zf?{state:{count:0,firstAt:s},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:s},shouldCollect:!1}}function $c(e){var n,a;const{activeConv:s}=e,r={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:s.routeId,tabKey:s.tabKey,sessionId:s.sessionId,providerSessionId:s.providerSessionId,transport:s.transport,agentName:s.agentName,agentType:s.agentType,hostIdeType:s.hostIdeType,status:s.status,connectionState:s.connectionState,title:s.title,workspaceName:s.workspaceName,displayPrimary:s.displayPrimary,displaySecondary:s.displaySecondary,streamSource:s.streamSource,lastMessageHash:s.lastMessageHash},messageCounts:{live:((n=e.chatTailState.liveMessages)==null?void 0:n.length)??s.messages.length,activeConversation:s.messages.length,visible:e.visibleMessages.length,history:((a=e.chatTailState.historyMessages)==null?void 0:a.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:nr(e.chatTailState.liveMessages??s.messages,10),activeConversationMessagesTail:nr(s.messages,10),visibleMessagesTail:nr(e.visibleMessages,5),historyMessagesTail:nr(e.chatTailState.historyMessages,5),actionLogsTail:nr(e.actionLogs.filter(o=>o.routeId===s.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{hasLiveSnapshot:!!e.chatTailState.hasLiveSnapshot,hasMoreHistory:!!e.chatTailState.hasMoreHistory,historyError:e.chatTailState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return ro(r)}function Bc(e,s={}){const r=e&&typeof e=="object"?e:{},n=s.locatorCopyStatus??(s.locatorCopied===!1?"failed":"copied"),a=n==="copied"?"locator copied":n==="manual"?"locator shown for manual copy":"locator copy failed";return r.delivery==="daemon_file"?`Chat debug signal sent${typeof r.bundleId=="string"&&r.bundleId.trim()?` (${r.bundleId})`:""}; saved on daemon, ${a}.`:`Chat debug signal sent; ${a}.`}async function Oc(e){var s;if(typeof navigator<"u"&&((s=navigator.clipboard)!=null&&s.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(r){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",r)}if(typeof document<"u"&&document.body){let r=null;try{if(r=document.createElement("textarea"),r.value=e,r.setAttribute("readonly","true"),r.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(r),r.focus(),r.select(),document.execCommand("copy"))return"copied"}catch{}finally{r==null||r.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function Fc(e){const s=e&&typeof e=="object"?e:{};if(s.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(s.bundleId||"")}`,`savedPath: ${String(s.savedPath||"")}`,`sizeBytes: ${String(s.sizeBytes||"")}`,`createdAt: ${String(s.createdAt||"")}`];return s.summary&&typeof s.summary=="object"&&r.push("","summary:",JSON.stringify(s.summary,null,2)),Array.isArray(s.warnings)&&s.warnings.length>0&&r.push("","warnings:",...s.warnings.map(n=>`- ${String(n)}`)),r.join(`
|
|
32
|
-
`)}return typeof s.text=="string"?s.text:s.bundle&&typeof s.bundle=="object"?`# ADHDev Chat Debug Bundle
|
|
33
|
-
|
|
34
|
-
\`\`\`json
|
|
35
|
-
${JSON.stringify(s.bundle,null,2)}
|
|
36
|
-
\`\`\``:`# ADHDev Chat Debug Bundle
|
|
37
|
-
|
|
38
|
-
\`\`\`json
|
|
39
|
-
${JSON.stringify(s,null,2)}
|
|
40
|
-
\`\`\``}function aa(e,s){return`${e}:${s}`}function Xf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function ar(e,s){Xf()&&console.debug(`[subscription-manager] ${e}`,s)}class Jf{constructor(){Je(this,"active",new Map);Je(this,"retryTimers",new Map)}subscribe(s,r,n,a,o){var u;const l=aa(n.topic,n.key),c=this.active.get(l);let d=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(l,h),ar("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=s.sendData)==null?void 0:u.call(s,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(l,s,o.retryIntervalMs)}const m=()=>{var k;this.clearRetry(l);const h=this.active.get(l);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(l);const g={type:"unsubscribe",topic:n.topic,key:n.key};ar("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(k=s.sendData)==null||k.call(s,r,g)};return m.initialSendAccepted=d,m}publish(s){const r=aa(s.topic,s.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=s,Fs.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),Fs.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=aa(s,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(s){var r;ar("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(o=>o.daemonId===s);ar("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(o=>({topic:o.request.topic,key:o.request.key}))});for(const o of n)(a=r.sendData)==null||a.call(r,o.daemonId,o.request)}scheduleRetry(s,r,n){if(this.retryTimers.has(s))return;const a=setTimeout(()=>{var c;this.retryTimers.delete(s);const o=this.active.get(s);if(!o)return;const l=((c=r.sendData)==null?void 0:c.call(r,o.daemonId,o.request))??!1;ar("subscribe_retry",{id:s,accepted:l,topic:o.request.topic,key:o.request.key}),l||this.scheduleRetry(s,r,n)},n);this.retryTimers.set(s,a)}clearRetry(s){const r=this.retryTimers.get(s);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(s))}}const Xt=new Jf;function Qf(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,settings:n.settings});for(const o of n.childSessions||[]){if(!(o!=null&&o.id))continue;const l=r.get(o.id)||{};r.set(o.id,{...l,...o})}}return r}function Zf(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 oa(e,s){return s&&(s.startsWith(`${e}:`)?s:`${e}:${s}`)}function eh(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function th(e){eh()&&console.debug("[dashboard-conversations] statusPayloadToEntries",e.map(s=>({id:s.id,daemonId:s.daemonId,sessionId:s.sessionId,instanceId:s.instanceId,providerSessionId:s.providerSessionId,transport:s.transport,type:s.type})))}function In(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:l}=s,c=l||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=Zf(d),h=Qf(o,n),g=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,k=m.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),f=m.filter(b=>b.kind==="agent"&&b.transport==="pty"),p=m.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:c,...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},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:k.some(b=>!!b.cdpConnected)});for(const b of k){const y=h.get(b.id),x=mr(b,y),I=(u.get(b.id)||[]).map(N=>mr(N,h.get(N.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,status:x.cdpConnected?"online":"detected",daemonId:n,instanceId:oa(n,b.id),workspace:x.workspace,terminals:0,childSessions:I,agents:I.map(N=>({id:N.id,name:N.providerName||N.providerType,type:N.providerType,status:N.status})),activeChat:x.activeChat,chats:[],cdpConnected:x.cdpConnected,...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:c})}for(const b of f){const y=h.get(b.id),x=mr(b,y);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:oa(n,b.id),cliName:x.providerName||x.providerType,mode:x.mode||(y==null?void 0:y.mode)||"terminal",workspace:x.workspace||"",activeChat:x.activeChat,...x.resume!==void 0&&{resume:x.resume},...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:c,_isCli:!0})}for(const b of p){const y=h.get(b.id),x=mr(b,y);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:oa(n,b.id),cliName:x.providerName||x.providerType,mode:"chat",workspace:x.workspace||"",activeChat:x.activeChat,...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:c,_isAcp:!0})}return th(r),r}const sh=15e3,rh=15e3,nh=6e4,ah=1200,Wi=12,oh=8e3,ih=4e3,ia=new Map,la=new Map,Vr=new Set,br=new Map;function lh(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 Hi(e,s){const r=br.get(e);!r||r.size===0||(br.delete(e),r.forEach(n=>n(s)))}function ch(e,s){return new Promise(r=>{const n=br.get(e)||new Set;br.set(e,n);const a=l=>{clearTimeout(o),n.delete(a),n.size===0&&br.delete(e),r(l)},o=setTimeout(()=>a(!1),s);n.add(a)})}function Lr(){const{sendCommand:e,sendData:s}=wt(),{injectEntries:r,getIdes:n}=Nr();return i.useCallback(async(a,o)=>{if(!a)return;const l=(o==null?void 0:o.minFreshMs)??nh,c=la.get(a)||0;if(!(o!=null&&o.force)&&Vr.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<l)return;const d=ia.get(a);if(d)return d;const m=(async()=>{if(s&&!Vr.has(a)){const p=Xt.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},b=>{const y=n(),x=y.find(N=>N.id===a),I=In(b.status,{daemonId:a,existingDaemon:x,existingEntries:y,timestamp:b.timestamp});I.length>0&&r(I),la.set(a,Date.now()),Hi(a,!0)});if(p.initialSendAccepted?Vr.add(a):Vr.delete(a),!(o!=null&&o.force)&&p.initialSendAccepted&&await ch(a,ah))return}const u=await e(a,"get_status_metadata"),h=lh(u);if(!h)return;const g=n(),k=g.find(p=>p.id===a),f=In(h,{daemonId:a,existingDaemon:k,existingEntries:g,timestamp:h.timestamp||Date.now()});f.length>0&&r(f,{authoritativeDaemonIds:[a]}),la.set(a,Date.now()),Hi(a,!0)})().finally(()=>{ia.delete(a)});return ia.set(a,m),m},[n,r,e,s])}function dh(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}const uh=60,mh=50;function Kc(e={}){return e.isCliLike?mh:uh}function ph(e={}){return Kc(e)}function Ct(e){return(typeof e=="string"?e.trim():"")||void 0}function Yt(e,s){const r=Ct(s);return r?`${e}:${r}`:void 0}function ns(e,s,r){const n=Yt(s,r),a=Ct(r);n&&e.push(n),a&&e.push(a)}function Ds(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function Wc(e){return Ct(e.providerSessionId)||Ct(e.sessionId)||Ct(e.tabKey)||Ct(e.routeId)}function Oo(e){return Ds([Ct(e.providerSessionId),Ct(e.sessionId)])}function Os(e){const s=[];return ns(s,"provider",e.providerSessionId),ns(s,"session",e.sessionId),ns(s,"tab",e.tabKey),ns(s,"route",e.routeId),Ds(s)}function fh(e){const s=[];return Ct(e.providerSessionId)?(ns(s,"provider",e.providerSessionId),Ds(s)):Ct(e.sessionId)?(ns(s,"session",e.sessionId),Ds(s)):Ct(e.tabKey)?(ns(s,"tab",e.tabKey),Ds(s)):Ct(e.routeId)?(ns(s,"route",e.routeId),Ds(s)):[]}function Fo(e){return Yt("provider",e.providerSessionId)||Yt("session",e.sessionId)||Yt("tab",e.tabKey)||Yt("route",e.routeId)||"unknown:"}function Rr(e){return Oo(e)[0]}function hh(e){const s=Ct(e.providerSessionId),r=Ct(e.sessionId),n=Ct(e.tabKey),a=Ct(e.routeId),o=[Yt("provider",s),Yt("session",r),Yt("tab",n),Yt("route",a)].filter(d=>typeof d=="string"),l=Os({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),c=Fo({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:Wc({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:Rr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:l}}function no(e,s){const r=hh(e);return fh(s).some(n=>r.lookupKeys.includes(n))}const _r=60,xh=1e3,Ko=12e4,bh=new Set(["generating","waiting_approval","starting","streaming","working"]),Ui=new Map;function Hc(e,s){return`${e}::${s}`}function ao(e=_r){return{liveMessages:[],hasLiveSnapshot:!1,cursor:gh([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function gh(e,s=_r){return{tailLimit:s}}function zi(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("|")}class yh{constructor(s){Je(this,"manager");Je(this,"sendData");Je(this,"daemonId");Je(this,"sessionId");Je(this,"historySessionId");Je(this,"subscriptionKey");Je(this,"fallbackRecentCount");Je(this,"snapshot");Je(this,"transportSubscription",null);Je(this,"listeners",new Set);Je(this,"retainCount",0);Je(this,"loadHistoryPromise",null);Je(this,"pendingDisconnectTimer",null);this.manager=s.manager||Xt,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.fallbackRecentCount=Math.max(0,s.fallbackRecentCount??0),this.snapshot=ao(Math.max(0,s.tailLimit??_r))}updateOptions(s){if(s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId),s.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,s.fallbackRecentCount)),s.tailLimit!==void 0){const r=Math.max(0,s.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}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=this.snapshot.hasLiveSnapshot,a=n?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),o=await s({offset:this.snapshot.historyOffset,excludeRecentCount:a}),l=Array.isArray(o.messages)?o.messages:[],c=!n&&l.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0;this.snapshot={...this.snapshot,historyMessages:[...l,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+l.length,hasMoreHistory:c?!0:o.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}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}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)},{retryIntervalMs:xh}))}disconnect(){var s;(s=this.transportSubscription)==null||s.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(s=>s(this.snapshot))}handleUpdate(s){if(s.error)return;const r=Array.isArray(s.messages)?s.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};zi(this.snapshot.liveMessages)===zi(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:n},this.emit())}}function Uc(e){const s=Hc(e.daemonId,e.sessionId),r=Ui.get(s);if(r)return r.updateOptions(e),r;const n=new yh(e);return Ui.set(s,n),n}function vh(e,s){return{...e,loadHistoryPage:s}}function wh(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function jh(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(bh.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??Ko)),o=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return o>0?n-o<=a:Array.isArray(e.messages)&&e.messages.length>0}function kh(e=Ko){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Nh(e,s={}){const r=new Set,n=[];for(const a of e){if(!jh(a,s))continue;const o=Mr(a),l=a.sessionId||"";if(!o||!l)continue;const c=Hc(o,l);if(r.has(c))continue;r.add(c);const d=Rr(a);n.push({daemonId:o,sessionId:l,historySessionId:d||l,subscriptionKey:`daemon:${o}:session:${l}`})}return n.sort(wh),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Sh(e,s){const{sendData:r,sendCommand:n}=wt(),a=(s==null?void 0:s.enabled)!==!1,o=Mr(e),l=e.sessionId||"",c=Rr(e)||l,d=`daemon:${o}:session:${l}`,m=Math.max(0,(s==null?void 0:s.tailLimit)??_r),u=i.useMemo(()=>!a||!o||!l?null:Uc({daemonId:o,sessionId:l,historySessionId:c,subscriptionKey:d,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,o,a,c,r,l,d,m]),[h,g]=i.useState(()=>(u==null?void 0:u.getSnapshot())||ao(m));i.useEffect(()=>{if(!u){g(ao(m));return}u.retain(),g(u.getSnapshot());const f=u.subscribe(p=>{g(p)});return()=>{f(),u.release()}},[u,m]);const k=i.useCallback(async()=>{!u||!o||!l||await u.loadHistoryPage(async({offset:f,excludeRecentCount:p})=>{const b=e.agentType,y=await n(o,"chat_history",{agentType:b,offset:f,limit:30,targetSessionId:l,historySessionId:c,excludeRecentCount:p}),x=y&&typeof y=="object"&&"result"in y?y.result||{}:y||{};return{messages:Array.isArray(x.messages)?x.messages:[],hasMore:x.hasMore===!0}})},[e.agentType,u,o,c,n,l]);return i.useMemo(()=>vh(h,k),[k,h])}function Ch(e,s){const{sendData:r}=wt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??_r),o=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??Ko)),l=kh(o),[c,d]=i.useState(0);i.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(h=>h+1)},l);return()=>{clearInterval(u)}},[e.length,n,l]);const m=i.useMemo(()=>Nh(e,{recentActivityMs:o}),[e,o,c]);i.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(h=>Uc({...h,sendData:r,tailLimit:a}));return u.forEach(h=>{h.retain()}),()=>{u.forEach(h=>h.release())}},[m.signature,n,r,a])}function Ih(e,s){return s!=null&&s.hasLiveSnapshot?s.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Vi(e){const s=String(e.role||"").toLowerCase();if(s!=="user"&&s!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function Th(e,s){if(e.length===0)return[];if(s.some(Vi))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const o=e[a];if(!o||!Vi(o))continue;const l=String(o.role||"").toLowerCase();n.has(l)||(n.add(l),r.unshift(o))}return r}function Ah(e){const{historyMessages:s,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),o=a>0?r.slice(0,a):[],l=a>0?r.slice(-n):r,c=Th(o,l),d=c.length>0?[...c,...l]:l;return s.length===0?d:[...s,...d]}function Mh(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Lh(e){return Mh(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Rh(e,s,r=`${s}s`){return`${e} ${e===1?s:r}`}function _h(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Ph(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function zc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Vc(e){const s=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return s||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function Dh(e){return zc(e)?!1:e.inboxBucket==="task_complete"&&Vc(e).length>0}function Gi(e){return e.branch||"detached HEAD"}function Eh(e){if(e.error)return`${Gi(e)} · Git error: ${e.error}`;const s=[Gi(e)];return e.changedFiles>0?s.push(Rh(e.changedFiles,"file")+" changed"):e.dirty||s.push("clean"),e.ahead>0&&s.push(`ahead ${e.ahead}`),e.behind>0&&s.push(`behind ${e.behind}`),e.hasConflicts&&s.push("conflicts"),s.join(" · ")}function $h(e,s){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Eh(s)}`}function Bh(e,s){return e.lastUpdated||e.lastMessageAt||s.lastCheckedAt||0}function Oh(e,s={}){if(s.enabled===!1)return[];if(!Ph(e))return[];const r=zc(e)?"working":Dh(e)?"complete":null;if(!r)return[];const n=r==="complete"?Vc(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${_h(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:$h(r,e.git),timestamp:Bh(e,e.git),meta:{source:"git-system-bubble",phase:r,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const Fh=60;function oo({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:l,actionLogs:c,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:h=!0}){var me,q,de,ae,xe,ue,ce;const g=i.useRef(new Map),k=i.useRef(void 0),f=Lr(),{sendCommand:p}=wt(),{isVisible:b}=Ro();Ar("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const y=kt.useMemo(()=>Ys(e),[e.status,e.connectionState]),x=i.useMemo(()=>Of(e,s),[e,s]),I=i.useMemo(()=>{var te;return Do((te=x.targetEntry)==null?void 0:te.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(me=x.targetEntry)==null?void 0:me.providerControls]),N=Kc({isCliLike:x.isCli||x.isAcp}),j=ph({isCliLike:x.isCli||x.isAcp}),A=Sh(e,{enabled:h&&!!e.sessionId,tailLimit:j}),[M,v]=i.useState(N),[w,B]=i.useState(()=>Ii()),R=e.tabKey,T=A.historyMessages,H=A.hasMoreHistory,E=A.historyError,D=Ih(e,A),S=pc(D).length;i.useEffect(()=>{v(N)},[N,R]);const C=Math.max(0,D.length-M),W=Eo(e),_=Mr(e),O=Lh(e),V=$o(e),X=a||V,ye=!!V,[he,ne]=i.useState(!1);i.useEffect(()=>{const te=x.targetEntry;_&&(!te||te.providerControls===void 0||te.controlValues===void 0)&&f(_,{minFreshMs:3e4}).catch(()=>{})},[_,x.isAcp,(q=x.targetEntry)==null?void 0:q.providerControls,(de=x.targetEntry)==null?void 0:de.controlValues,f]);const pe=i.useCallback(async()=>{if(!he){if(D.length>M){v(te=>Math.min(D.length,te+Fh));return}ne(!0);try{await A.loadHistoryPage()}finally{ne(!1)}}},[A,he,D.length,M]),{allMessages:ke,receivedAtMap:Se}=i.useMemo(()=>{const te=Ah({historyMessages:T,liveMessages:D,visibleLiveCount:M}),$=Oh(e),J=$.length>0?[...te,...$]:te,oe={};return J.forEach((ee,Ne)=>{const Ce=`${e.tabKey}:${wn(ee,Ne)}`;let we=dh(ee)||g.current.get(Ce)||0;we||(we=Date.now(),g.current.set(Ce,we)),oe[wn(ee,Ne)]=we}),{allMessages:J,receivedAtMap:oe}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,C,T,D,M]),G=i.useMemo(()=>c.filter(te=>te.routeId===e.tabKey).sort((te,$)=>te.timestamp-$.timestamp),[c,e.tabKey]),be=i.useCallback(async()=>{var Ne,Ce;if(!_)return;const te=$c({activeConv:e,visibleMessages:ke,actionLogs:c,controls:(Ne=x.targetEntry)==null?void 0:Ne.providerControls,controlValues:(Ce=x.targetEntry)==null?void 0:Ce.controlValues,visibleBarControlCount:I.length,chatTailState:{liveMessages:A.liveMessages,hasLiveSnapshot:A.hasLiveSnapshot,hasMoreHistory:H,historyError:E,historyMessages:T},ui:{controlsVisible:b,visibleLiveCount:M,activityVisible:w,activityCount:S,hiddenLiveCount:C,isInputActive:u,isVisible:h}}),$=await p(_,"get_chat_debug_bundle",{agentType:x.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:te}),J=Cn($),oe=Fc(J),ee=await Oc(oe);ee==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ot.showToast(Bc(J,{locatorCopyStatus:ee}),ee==="failed"?"warning":"success")},[e,c,S,ke,b,A.hasLiveSnapshot,A.liveMessages,x.providerType,(ae=x.targetEntry)==null?void 0:ae.controlValues,(xe=x.targetEntry)==null?void 0:xe.providerControls,_,H,C,T,u,h,E,p,w,I.length,M]),fe=i.useCallback(()=>{B(te=>{const $=!te;return lp($),$})},[]);i.useEffect(()=>{const te=$=>{$.key===To&&B(Ii())};return window.addEventListener("storage",te),()=>window.removeEventListener("storage",te)},[]);const ve=i.useCallback(()=>{const te=Yf(k.current);k.current=te.state,te.shouldCollect&&be().catch($=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",$),ot.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[be]),P=i.useMemo(()=>{if(D.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((y.isGenerating||e.status==="streaming")&&ne(!1),e.status==="not_monitored"&&O)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(Ws,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ks,{size:14})," Open ",W," 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"&&O)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(cc,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(ks,{size:14})," Open ",W," 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"&&!he)return!H&&T.length===0?t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):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,O,o,H,T.length,l,he,D.length,W,y.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[t.jsx("div",{className:"chat-activity-toggle-bar",children:t.jsxs("button",{type:"button",className:`chat-activity-toggle ${w?"chat-activity-toggle-active":""}`,onClick:fe,"aria-pressed":w,title:"Show tool, terminal, and runtime activity rows",children:[t.jsx("span",{className:"chat-activity-toggle-dot"}),"Activity",S>0&&t.jsx("span",{className:"chat-activity-toggle-count",children:S})]})}),t.jsx(kp,{messages:ke,actionLogs:G,agentName:Hs(e)||W||"Agent",userName:d,isCliMode:x.isCli||x.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:Se,lastMessageHash:e.lastMessageHash,showActivityMessages:w,onLoadMore:pe,isLoadingMore:he,hasMoreHistory:H,hiddenLiveCount:C,loadError:E??void 0,emptyState:P,scrollToBottomRequestNonce:m,isVisible:h}),t.jsx(If,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:x.providerType,displayLabel:x.displayLabel,controls:(ue=x.targetEntry)==null?void 0:ue.providerControls,controlValues:(ce=x.targetEntry)==null?void 0:ce.controlValues,isActive:u,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&t.jsx(Ac,{contextKey:e.tabKey,panelLabel:W,isSending:n,isBusy:ye,statusMessage:X,onSend:r,isActive:u,showControlsToggle:I.length>0,onControlsToggle:ve,messageInput:e.messageInput})]})}let Gc=is;function qc(){return Gc()}class Kh{constructor(){Je(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 Yc=new Kh;class Wh{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,n){return()=>{}}requestRuntimeSnapshot(s,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let ut=new Wh;function Hh(e){e.dashboardWS&&(Yc=e.dashboardWS),e.connectionManager&&(ut=e.connectionManager),e.useDaemonsHook&&(Gc=e.useDaemonsHook)}const Uh=.5,zh=1.25;function dt(e){return Eo(e)}function Ss(e){return Pc(e).join(" · ")}function Xc(e){const s=_c(e);return s||(e.title?e.title:Ss(e)||"No messages yet")}function Jc(e,s){const{isReconnecting:r,isConnecting:n}=Ys(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Vh(e,s){const r=["Chat",...Pc(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function hs(e){return Jc(e)||Ss(e)}function Gh(e){return`${dt(e)} · ${Xc(e)}`}function qh(e){const s=Sn(e),r=s?lt(s):Hs(e);return`${dt(e)} — ${r||"Agent"}`}function Yh(e){return Hs(e)||"CLI"}function Qc(e){return Rc(e)}function Zc(e){return e?`Remote · ${dt(e)||e.workspaceName||"Session"}`:"Remote"}function Xh({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:l=!0,isInputActive:c=!0}){var ie;is();const{sendPtyInput:d}=wt(),[m,u]=i.useState(!1),h=i.useRef(!1);h.current=m;const[g,k]=i.useState("Runtime terminal unavailable"),[f,p]=i.useState(!1),[b,y]=i.useState(null),[x,I]=i.useState(!1),[N,j]=i.useState(!1),[A,M]=i.useState(1),[v,w]=i.useState(!1),[B,R]=i.useState({width:0,height:0}),[T,H]=i.useState({width:0,height:0}),[E,D]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[S,C]=i.useState(null),W=i.useRef(null),_=i.useRef(null),O=i.useRef(!1),V=i.useRef(!1),X=i.useRef(l),ye=i.useRef(0),he=i.useRef(!1),ne=i.useRef(""),pe=i.useRef(null),ke=i.useRef(!1),Se=i.useRef(!1),G=i.useRef(null),be=i.useRef(null),fe=i.useRef(null),ve=32*1024,P=()=>{var F,Y,re,le;return((Y=(F=W.current)==null?void 0:F.ownerDocument)==null?void 0:Y.defaultView)||((le=(re=_.current)==null?void 0:re.ownerDocument)==null?void 0:le.defaultView)||window},me=F=>{const Y=P();return{ownerWindow:Y,frameId:Y.requestAnimationFrame(F)}},q=()=>{const F=G.current;if(F){try{F.ownerWindow.cancelAnimationFrame(F.frameId)}catch{}G.current=null}},de=()=>{const F=be.current;if(F){try{F.ownerWindow.clearTimeout(F.timeoutId)}catch{}be.current=null}},ae=()=>{const F=fe.current;if(F){try{F.ownerWindow.clearTimeout(F.timeoutId)}catch{}fe.current=null}},xe=()=>{l&&G.current===null&&(G.current=me(()=>{st()}))},ue=e.tabKey,ce=e.sessionId||"",te=e.daemonId||((ie=e.routeId)==null?void 0:ie.split(":")[0])||e.routeId||"",$=$o(e),J=m?o||$:g,oe=Uh,ee=zh,Ne=.05,Ce=()=>{const F=T.width,Y=T.height;if(!Number.isFinite(B.width)||B.width<=0||!Number.isFinite(B.height)||B.height<=0||!Number.isFinite(F)||F<=0||!Number.isFinite(Y)||Y<=0)return 1;const re=B.width/F,le=B.height/Y;return Number(Math.min(ee,Math.max(oe,Math.min(re,le))).toFixed(2))},we=Ce(),K=O.current&&A>we,Ie=Number.isFinite(T.width)&&T.width>0?Math.max(B.width,Math.round(T.width*A)):B.width,Re=Number.isFinite(T.height)&&T.height>0?Math.max(B.height,Math.round(T.height*A)):B.height,Ke=()=>{me(()=>{const F=_.current;F&&(F.scrollLeft=0,F.scrollTop=F.scrollHeight-F.clientHeight)})},He=()=>{var F,Y;ye.current=0,he.current=!1,ne.current="",pe.current=null,ke.current=!1,Se.current=!1,O.current||(V.current=!1,M(1)),G.current!==null&&q(),u(!1),k("Runtime terminal unavailable"),ae(),de(),y(null),C(null),w(!1),p(!1),I(!1),j(!1),(Y=(F=r.current)==null?void 0:F.reset)==null||Y.call(F)},qe=()=>{var F,Y;ye.current=0,he.current=!1,ne.current="",pe.current=null,ke.current=!1,Se.current=!1,G.current!==null&&q(),u(!0),k(""),ae(),de(),y(null),C(null),w(!1),p(!1),I(!1),j(!1),(Y=(F=r.current)==null?void 0:F.reset)==null||Y.call(F)},Ye=()=>{Se.current&&(Se.current=!1,me(()=>{var F,Y;(Y=(F=r.current)==null?void 0:F.scrollToTop)==null||Y.call(F)}))},st=()=>{if(G.current=null,!l)return;const F=ne.current;if(!F)return;const Y=F.slice(0,ve);ne.current=F.slice(Y.length);const re=r.current;if(!re){ne.current=Y+ne.current,xe();return}re.write(Y,()=>{if(ne.current.length>0){xe();return}Ye()})},mt=F=>{F&&(ne.current+=F,xe())},ht=(F,Y=0,re,le,je={})=>{var De,Me,Ee,Oe;const _e=!!je.force;!_e&&Y>0&&ye.current>=Y||!_e&&Y===0&&he.current||(ye.current=Y,Y>0&&I(!0),u(!0),k(""),typeof re=="number"&&typeof le=="number"&&re>0&&le>0&&((Me=(De=r.current)==null?void 0:De.resize)==null||Me.call(De,re,le)),ne.current="",(Oe=(Ee=r.current)==null?void 0:Ee.reset)==null||Oe.call(Ee),F?mt(F):Ye())};i.useEffect(()=>{He()},[ce]),i.useEffect(()=>{var Y;if(!ce)return;const F=((Y=ut.onRuntimeEvent)==null?void 0:Y.call(ut,ce,re=>{if(!(!re||re.sessionId!==ce)){if(re.type==="runtime_snapshot"){if(!l){pe.current={text:re.text||"",seq:re.seq||0,cols:re.cols,rows:re.rows,force:!!re.force};return}ht(re.text||"",re.seq||0,re.cols,re.rows,{force:!!re.force});return}if(re.type==="session_output"){he.current=!0,typeof re.seq=="number"&&(ye.current=Math.max(ye.current,re.seq),re.seq>0&&I(!0)),h.current||u(!0),h.current||k(""),typeof re.data=="string"&&mt(re.data);return}if(re.type==="session_cleared"){if(!l){ke.current=!0,ne.current="",pe.current=null;return}qe();return}if(re.type==="session_io_error"){const le=typeof re.error=="string"&&re.error?re.error:typeof re.reason=="string"&&re.reason?re.reason:"unknown error";u(!1),k(`Runtime input failed: ${le}`);return}}},te))||(()=>{});return()=>{F()}},[te,ce,r,l]);const yt=async(F={})=>{var Y;if(!te||!ce)return{success:!1,error:"daemonId and sessionId are required"};F.preserveStatus||k(F.loadingMessage||"Loading runtime terminal...");try{const re=await((Y=ut.requestRuntimeSnapshot)==null?void 0:Y.call(ut,te,ce,{sinceSeq:F.sinceSeq,force:F.force}));return re&&re.success===!1?(F.preserveStatus||(u(!1),k(`Runtime terminal unavailable: ${re.error}`)),re):re||{success:!0}}catch(re){const le=(re==null?void 0:re.message)||String(re);return F.preserveStatus||(u(!1),k(`Runtime terminal unavailable: ${le}`)),{success:!1,error:le}}},Te=async F=>{var _e,De;const Y=((_e=W.current)==null?void 0:_e.ownerDocument)||document,re=Y.defaultView||window,le=(De=re.navigator)==null?void 0:De.clipboard;if(le!=null&&le.writeText&&re.isSecureContext)try{return await le.writeText(F),!0}catch{}let je=null;try{return je=Y.createElement("textarea"),je.value=F,je.setAttribute("readonly","true"),je.style.position="fixed",je.style.left="-9999px",je.style.top="0",Y.body.appendChild(je),je.focus(),je.select(),Y.execCommand("copy")}catch{return!1}finally{je==null||je.remove()}},Ue=F=>{de(),C(F);const Y=P();be.current={ownerWindow:Y,timeoutId:Y.setTimeout(()=>{be.current=null,C(re=>re===F?null:re)},2200)}},et=F=>{ae(),y(F);const Y=P();fe.current={ownerWindow:Y,timeoutId:Y.setTimeout(()=>{fe.current=null,y(re=>re===F?null:re)},2200)}},ze=async()=>{var je,_e,De,Me;const F=((_e=(je=r.current)==null?void 0:je.getSelection)==null?void 0:_e.call(je))||"",Y=((Me=(De=r.current)==null?void 0:De.getVisibleText)==null?void 0:Me.call(De))||"",re=F.trimEnd()||Y.trimEnd();if(!re){Ue("Nothing to copy");return}if(!await Te(re)){Ue("Copy failed");return}Ue(F.trimEnd()?"Copied selection":"Copied visible terminal")},at=F=>{if(!m||!l)return;((d==null?void 0:d(te,ce,F))??!1)||Ue("Terminal input failed")},U=async()=>{if(f)return;p(!0),y("Loading older terminal output..."),Se.current=!0;const F=await yt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(F==null?void 0:F.success)===!1){Se.current=!1,y(`Older terminal output unavailable: ${F.error}`);return}j(!0),et("Older terminal output loaded"),me(()=>{var Y;(Y=r.current)==null||Y.bumpResize()})};i.useEffect(()=>{var Y,re;if(!ce)return;te&&((Y=ut.getState)==null?void 0:Y.call(ut,te))==="connected"&&yt();const F=(re=ut.onStateChange)==null?void 0:re.call(ut,(le,je)=>{le!==te||je!=="connected"||yt()});return()=>{F==null||F()}},[te,ce,r]),i.useEffect(()=>{s&&He()},[s,ue,r]),i.useEffect(()=>{var le,je;const F=W.current,Y=(je=(le=F==null?void 0:F.ownerDocument)==null?void 0:le.defaultView)==null?void 0:je.ResizeObserver;if(!F||!Y)return;const re=new Y(_e=>{const De=_e[0];if(!De)return;const{width:Me,height:Ee}=De.contentRect;R(Oe=>{const Ae=Math.round(Me),Xe=Math.round(Ee);return Oe.width===Ae&&Oe.height===Xe?Oe:{width:Ae,height:Xe}})});return re.observe(F),()=>re.disconnect()},[]),i.useEffect(()=>{if(O.current)return;const F=Ce();!Number.isFinite(F)||F<=0||M(Y=>V.current?F<Y-Ne?F:Y:(V.current=!0,F))},[T.height,T.width,B.height,B.width]),i.useEffect(()=>{K&&Ke()},[K,Re,Ie]),i.useEffect(()=>{var re;const F=X.current;if(X.current=l,!l)return;F||j(!1),ke.current&&(ke.current=!1,qe());const Y=pe.current;Y&&(pe.current=null,ht(Y.text,Y.seq,Y.cols,Y.rows,{force:!!Y.force})),te&&ce&&((re=ut.getState)==null?void 0:re.call(ut,te))==="connected"&&yt(),ne.current&&G.current===null&&xe(),me(()=>{var le;(le=r.current)==null||le.bumpResize()})},[te,l,ce]),i.useEffect(()=>()=>{G.current!==null&&q(),de(),ae()},[]),i.useEffect(()=>{const F=le=>{var _e;const je=le.detail;je!=null&&je.sessionId&&je.sessionId!==ce||m&&((_e=r.current)==null||_e.bumpResize())},Y=P(),re=Y===window?[window]:[window,Y];for(const le of re)le.addEventListener("adhdev:fit-cli-terminal",F);return()=>{for(const le of re)le.removeEventListener("adhdev:fit-cli-terminal",F)}},[m,ce,r]);const Z=m&&x&&!N&&(E.atTop||!E.canScroll)||f||!!b;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:W,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Z&&t.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[t.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{U()},disabled:!ce||f,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:f?"Loading older...":"Load older terminal output"}),b&&t.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:b})]}),t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[S&&t.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:S}),t.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{ze()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),t.jsxs("div",{className:"relative",children:[t.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>w(F=>!F),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":v,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),v&&t.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":"Terminal control keys",className:"absolute right-0 top-10 w-56 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[t.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),t.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>w(!1),"aria-label":"Close terminal control keys",children:"×"})]}),t.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>at("\x1B"),children:"Esc"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>at(" "),children:"Tab"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>at("\r"),children:"Enter"}),t.jsx("span",{"aria-hidden":"true"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>at("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),t.jsx("span",{"aria-hidden":"true"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>at("\x1B[D"),"aria-label":"Arrow left",children:"←"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>at("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>at("\x1B[C"),"aria-label":"Arrow right",children:"→"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>at(""),children:"Ctrl-C"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>at(""),children:"Ctrl-D"}),t.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>at(""),children:"Bksp"})]})]})]}),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:()=>{O.current=!0,M(F=>{const Y=Math.max(we,Number((F-.1).toFixed(2)));return Y>we&&Ke(),Y})},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:()=>{O.current=!0,M(F=>{const Y=Math.min(ee,Number((F+.1).toFixed(2)));return Y>we&&Ke(),Y})},title:"Increase terminal viewport",children:"+"})]}),t.jsx("div",{ref:_,className:K?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:t.jsx("div",{style:{width:Ie>0?`${Ie}px`:"100%",height:Re>0?`${Re}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:t.jsx("div",{style:{width:T.width>0?`${T.width}px`:"100%",height:T.height>0?`${T.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:A},children:t.jsx(gc,{ref:r,readOnly:!m||!l,sizingMode:"measured",onViewportMetrics:H,onScrollMetrics:D,onInput:F=>{!m||(d==null||d(te,ce,F))}})})})}),!m&&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:g})]}),t.jsx(Ac,{contextKey:e.tabKey,panelLabel:dt(e),isSending:a,isBusy:!!$,statusMessage:J,onSend:async F=>$?!1:n(F),isActive:c&&l,showControlsToggle:!1,animateVisibility:!1})]})}const Jh=5e3,Qh=12e3;function Zh(e){return e==="disconnected"||e==="reconnecting"}function ex({wsStatus:e,showReconnected:s,loginUrl:r,onReconnect:n,reconnectDelayMs:a=Jh,reconnectActionDelayMs:o=Qh}){const l=Zh(e),[c,d]=i.useState(()=>!l||a<=0),[m,u]=i.useState(()=>!l||o<=0),h=i.useRef(!1);i.useEffect(()=>{if(!l){d(!1);return}if(h.current=!1,a<=0){h.current=!0,d(!0);return}d(!1);const j=setTimeout(()=>{h.current=!0,d(!0)},a);return()=>clearTimeout(j)},[a,l]),i.useEffect(()=>{if(!l){u(!1);return}if(o<=0){u(!0);return}u(!1);const j=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(j)},[o,l]);const g=l?c:e==="offline"||e==="auth_failed",k=!!(n&&e!=="auth_failed"&&(!l||m)),f=i.useMemo(()=>!s||e!=="connected"?!1:a<=0||h.current,[a,s,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",b={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))"},y={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)"},x={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},I="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",N={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return t.jsxs(t.Fragment,{children:[g&&t.jsx("div",{className:I,style:N,children:t.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:b[p],border:y[p],color:x[p]},children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",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}}),t.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&"Network offline",e==="disconnected"&&"Reconnecting",e==="reconnecting"&&"Reconnecting",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 — refresh the page or try again shortly.")]}),k&&t.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>n==null?void 0:n(),disabled:e==="offline",children:"Reconnect now"})]})}),f&&t.jsx("div",{className:I,style:N,children:t.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 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-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function tx({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const a=i.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[o,l]=i.useState(!1);if(i.useEffect(()=>{if(!a){l(!1);return}try{l(localStorage.getItem(a)==="1")}catch{l(!1)}},[a]),!s||!e||e.backend!=="xterm"||o)return null;const c=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}l(!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:[c," 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:d,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 Wo({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(Co,{size:n}):t.jsx(Jt,{size:n})})}const Wt="New session",ed="A connected machine is ready. Start a new session to begin chatting, or open a workspace to launch an IDE, CLI, or ACP session.";function sx(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const s=[e.branch||"Git"];return e.changedFiles>0&&s.push(`±${e.changedFiles}`),e.ahead>0&&s.push(`↑${e.ahead}`),e.behind>0&&s.push(`↓${e.behind}`),s.length===1&&e.dirty&&s.push("dirty"),s.join(" ")}function rx(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function nx(e){switch(e){case"conflict":return"border-red-500/25 bg-red-500/[0.08] text-red-400";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-emerald-500/15 bg-emerald-500/[0.06] text-emerald-500"}}function zs({git:e,className:s="",compact:r=!1}){const n=sx(e),a=rx(e);if(!n||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return t.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${nx(a)} ${s}`.trim(),title:o.join(" · ")||n,"data-git-tone":a,children:[t.jsx("span",{"aria-hidden":"true",children:"⑂"}),t.jsx("span",{className:"truncate",children:n})]})}function ax({wsStatus:e,isConnected:s,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),o=a.filter(c=>c==="connected").length,l=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return r>0&&l>0&&o===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:s?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function qi({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Yi({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const l=$n(e.updatedAt),c=!e.readAt;return t.jsxs("div",{className:`dashboard-header-inbox-item ${c?"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",l].filter(Boolean).join(" · ")]}),e.preview?t.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),t.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function ox({activeConv:e,wsStatus:s,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:l,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:h,onShowAllHidden:g,onResetPanelsToMain:k,inboxOpen:f,onInboxOpenChange:p,hiddenOpen:b,onHiddenOpenChange:y,onOpenNewSession:x,onOpenDashboardGuide:I,guideNudgeVisible:N=!1,actionShortcuts:j,notifications:A,notificationUnreadCount:M,onOpenNotification:v,onMarkNotificationRead:w,onMarkNotificationUnread:B,onDeleteNotification:R,onOpenGitDialog:T,onOpenMeshGraph:H}){var me;const{ides:E,p2pStates:D={}}=is(),S=!!e&&nt(e)&&!tt(e),C=!!e&&tt(e),W=!!(e!=null&&e.daemonId)&&typeof((me=e==null?void 0:e.settings)==null?void 0:me.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,_=c||(e?Mc(e)?"terminal":"chat":null),[O,V]=i.useState(!1),X=i.useRef(null),ye=i.useRef(null),he=E.filter(q=>q.type==="adhdev-daemon"),ne=ax({wsStatus:s,isConnected:r,daemonCount:he.length,p2pStates:D}),pe=ne.subtitle,ke=ne.tone==="connected"?"#22c55e":ne.tone==="limited"?"#eab308":"#ef4444",Se=ne.tone==="connected"?"0 0 4px #22c55e80":ne.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",G=i.useMemo(()=>A.filter(q=>!q.readAt),[A]),be=i.useMemo(()=>A.filter(q=>!!q.readAt),[A]),fe=i.useMemo(()=>G.slice(0,9),[G]),ve=M;i.useEffect(()=>{if(!f)return;const q=de=>{var ae;(ae=X.current)!=null&&ae.contains(de.target)||p(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[f,p]),i.useEffect(()=>{if(!b)return;const q=de=>{var ae;(ae=ye.current)!=null&&ae.contains(de.target)||y(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[b,y]),i.useEffect(()=>{if(!b&&!f)return;const q=de=>{if(!de.altKey)return;const ae=de.code.match(/^Digit([1-9])$/);if(!ae)return;const xe=Number(ae[1])-1,ue=b?u[xe]:void 0,ce=f?fe[xe]:void 0;if(!(!ue&&!ce)){if(de.preventDefault(),de.stopPropagation(),ue){h==null||h(ue),y(!1);return}ce&&(v(ce),p(!1))}};return window.addEventListener("keydown",q,!0),()=>window.removeEventListener("keydown",q,!0)},[u,b,f,fe,y,p,v,h]);const P=q=>{if(!q)return;const de=n.find(ae=>ae.tabKey===q);de&&(m==null||m(de))};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(Jt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?dt(e):"Dashboard"}),t.jsx("span",{title:ne.title,"aria-label":ne.title,className:"header-title-status-dot",style:{background:ke,boxShadow:Se}}),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:ke,boxShadow:Se}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[pe&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",pe]}),x&&t.jsx("button",{type:"button",onClick:x,className:"btn btn-secondary btn-sm ml-2",title:`${Wt}${j!=null&&j.openNewSession?` (${j.openNewSession})`:""}`,"aria-label":Wt,children:t.jsx(uc,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[I&&t.jsxs("button",{type:"button",onClick:I,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:"Dashboard guide","aria-label":"Open dashboard guide",children:[t.jsx("span",{className:"font-semibold leading-none",children:"?"}),N&&t.jsx("span",{children:"Guide"})]}),e&&(S||C||!tt(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:Ss(e)||dt(e),children:dt(e)}),T&&e.git&&e.daemonId&&e.workspacePath?t.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>T(e.daemonId,e.workspacePath),children:t.jsx(zs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):t.jsx(zs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),W&&H&&t.jsxs("button",{type:"button",onClick:()=>H(e),className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",title:"Open live repo mesh graph",children:[t.jsx(rs,{size:14}),t.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(S||C)&&l&&t.jsxs(t.Fragment,{children:[S&&d&&_&&t.jsx(Wo,{mode:_,onChange:d,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:C?"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(vt,{size:14})})]}),!tt(e)&&t.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(No,{size:14})}),!S&&!tt(e)&&t.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(Mt,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:X,children:[t.jsxs("div",{className:`dashboard-header-hidden${O?" is-drop-target":""}`,ref:ye,onDragEnter:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),V(!0))},onDragOver:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),q.dataTransfer.dropEffect="move",V(!0))},onDragLeave:q=>{q.currentTarget.contains(q.relatedTarget)||V(!1)},onDrop:q=>{const de=q.dataTransfer.getData("text/tab-key");q.preventDefault(),V(!1),P(de)},children:[t.jsxs("button",{type:"button",onClick:()=>y(!b),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${j!=null&&j.toggleHiddenTabs?` (${j.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(So,{size:16}),u.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:u.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(qi,{value:j==null?void 0:j.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[k&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:k,children:"Reset panels"}),u.length>0&&g&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{g(),y(!1)},children:"Restore all"})]})]}),e&&m&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(qi,{value:j==null?void 0:j.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:dt(e)})]}),u.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(q=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(q),y(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:dt(q)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(q)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(q)+1]}):null,Ss(q)]})]},q.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>p(!f),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(En,{size:16}),ve>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:ve})]}),f&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[G.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),G.map(q=>t.jsx(Yi,{notification:q,shortcutIndex:fe.indexOf(q)>=0?fe.indexOf(q)+1:void 0,onOpen:()=>v(q),onMarkRead:()=>w(q.id),onMarkUnread:()=>B(q.id),onDelete:()=>R(q.id)},q.id))]}),be.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),be.map(q=>t.jsx(Yi,{notification:q,onOpen:()=>v(q),onMarkRead:()=>w(q.id),onMarkUnread:()=>B(q.id),onDelete:()=>R(q.id)},q.id))]}),A.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Nt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function ix(e,s){return String(e||"")!==String(s||"")}function lx(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),o=!!s.resumableOnly;return!r&&!n&&!a&&!o?e:e.filter(l=>!(o&&!l.canResume||r&&![l.title,l.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
41
|
-
`).includes(r)||n&&!String(l.workspace||"").toLowerCase().includes(n)||a&&!kc(l.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
42
|
-
`).includes(a)))}function cx(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 o=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function td(e,s={}){return cx(lx(e,s),s.sortMode||"recent")}function Tn(e){return e?"Resume saved history":"Start fresh"}function Ho(e){return e?"Resuming saved history…":"Starting fresh…"}function dx(){return"Start fresh"}function sd(e,s=!1){return e==="cli"?Tn(s):e==="ide"?"Start IDE":"Start ACP session"}function rd(e,s=!1){return e==="cli"?Ho(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function ux(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function mx(){return"Open saved history"}function px(){return"Saved History"}function Uo(){return"Use saved history when you want continuity in the same provider conversation."}function fx(){return"No saved history found yet."}function hx(){return"Refresh saved history"}function xx(){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 Vs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Gs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function zo(e){return`Resume saved history with ${e}?`}function Vo(){return"Review or change the target workspace before resuming saved history."}function bx(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 Go({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:l=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:h,onSwitchSession:g,onRefreshHistory:k,onResumeSavedSession:f}){var R;const p=s.find(T=>T.id===e.routeId),b=(p==null?void 0:p.chats)||[],y=(R=p==null?void 0:p.activeChat)==null?void 0:R.id,x=nt(e)&&!tt(e),[I,N]=i.useState(()=>Nt()),j=c||I,A=String(d||"").trim(),M=T=>{if(m){m(T);return}N(T)},v=i.useMemo(()=>a.map(T=>{const H=String(T.workspace||"").trim();return T.canResume||H||!A?T:{...T,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,a]),w=i.useMemo(()=>td(v,{textQuery:j.textQuery,workspaceQuery:j.workspaceQuery,modelQuery:j.modelQuery,resumableOnly:j.resumableOnly,sortMode:j.sortMode}),[v,j.modelQuery,j.resumableOnly,j.sortMode,j.textQuery,j.workspaceQuery]),B=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:u,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:x?px():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:qh(e)}),x&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Uo()})]}),t.jsx("button",{onClick:u,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(vt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!x&&t.jsx("button",{onClick:h,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"}),x?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:j.textQuery,onChange:T=>M({...j,textQuery:T.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:j.workspaceQuery,onChange:T=>M({...j,workspaceQuery:T.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:j.modelQuery,onChange:T=>M({...j,modelQuery:T.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:j.sortMode,onChange:T=>M({...j,sortMode:T.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:j.resumableOnly,onChange:T=>M({...j,resumableOnly:T.target.checked})}),"Resume-ready only"]})]}),w.map(T=>{const H=e.providerSessionId===T.providerSessionId,E=H||!T.canResume||!!l,D=T.workspaceFallbackSource==="selected-workspace";return t.jsxs("button",{type:"button",onClick:()=>{E||!f||f(T)},disabled:E,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${H?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${E?"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 ${H?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:T.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:bx(T.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:T.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:[T.workspace||"Workspace unknown",D?" · selected workspace":"",Ns(T.summaryMetadata)?` · ${Ns(T.summaryMetadata)}`:"",T.messageCount>0?` · ${T.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:H?"ACTIVE":T.canResume?D?"RESUME IN SELECTED WORKSPACE":l===T.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},T.id)})]}):b.map(T=>t.jsxs("div",{onClick:()=>{g(e.routeId,T.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${y===T.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 ${y===T.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:T.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:[T.id.substring(0,12),"..."]}),y===T.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},T.id)),(x&&!o&&w.length===0||!x&&b.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(Km,{size:32})}),t.jsx("div",{className:"text-[13px]",children:x?a.length>0?"No saved history matches these filters.":fx():"No recent chat sessions found."})]}),x&&o&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:xx()})})]}),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:k,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tr,{size:13})," ",x?hx():"Refresh History"]})})})]})]});return typeof document>"u"?B:kr.createPortal(B,document.body)}const Xi={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 nd({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=Xi[n.type]||Xi.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 o;(o=n.actions)!=null&&o.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:o=>{o.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(vt,{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((o,l)=>t.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.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)"}:o.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:c=>{c.stopPropagation(),o.onClick(),s(n.id)},children:o.label},l))})]})]},n.id)})})}const gx=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function yx(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function vx(e){return e.sessionId||e.instanceId||e.agentType}function ca(e,s){return s||e||"unknown"}function ad(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=At(r,{fallbackId:r.id}));return s}function od(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 qo(e,s={}){return wx(e,od(e,s))}function wx(e,s={}){var h,g,k,f,p;const r=[],n=s.machineName,a=s.connectionState,o=yx(e),l=e.workspace||"",c=Up(e.type,{agentName:e.cliName}),d=nt(e)||tt(e)?c:lt(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(b=>{var y,x;return{sessionId:b.id,instanceId:b.id,providerSessionId:b.providerSessionId,transport:b.transport,sessionCapabilities:b.capabilities,agentType:b.providerType,agentName:b.providerName||lt(b.providerType),status:b.status,title:b.title,lastMessagePreview:b.lastMessagePreview,lastMessageRole:b.lastMessageRole,lastMessageAt:b.lastMessageAt,lastMessageHash:b.lastMessageHash,messages:((y=b.activeChat)==null?void 0:y.messages)||[],activeModal:((x=b.activeChat)==null?void 0:x.activeModal)||void 0,unread:b.unread,lastSeenAt:b.lastSeenAt,lastUpdated:b.lastUpdated,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,surfaceHidden:b.surfaceHidden,git:b.git,settings:b.settings,messageInput:b.messageInput}}):[],u=gx(e);if(u){const b=e.sessionId||e.instanceId,y=(h=e.settings)==null?void 0:h.meshCoordinatorFor,x=(g=e.settings)==null?void 0:g.meshNodeFor,I=y?" (Coordinator)":x?" (Mesh Node)":"",N=c+I,j=(k=e.activeChat)==null?void 0:k.activeModal,A=j&&Array.isArray(j.buttons)&&j.buttons.length>0,M=zp(e.activeChat,[{status:e.status,activeModal:(f=e.activeChat)==null?void 0:f.activeModal}],e.agents||[]),v=e.activeChat||{title:"",messages:[]};let w=v.title&&String(v.title).trim()?String(v.title).trim():"";const B=(p=e.activeChat)==null?void 0:p.id,R=e.chats;if(B&&Array.isArray(R)&&R.length>0){const D=R.find(S=>S.id===B||S.id&&String(S.id)===String(B));D!=null&&D.title&&String(D.title).trim()&&(w=String(D.title).trim())}const T=(nt(e)||tt(e),e.type),H=(nt(e)||tt(e))&&Di(w,N,T)?"":w,E=v.messages||[];r.push({routeId:e.id,sessionId:b,providerSessionId:e.providerSessionId,nativeSessionId:b,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:nt(e)?e.mode||"terminal":"chat",agentName:N,agentType:T,status:M,title:H,messages:E,resume:e.resume,hostIdeType:!nt(e)&&!tt(e)?e.type:void 0,workspaceName:o,workspacePath:l,git:e.git,displayPrimary:H||o||(nt(e)?e.mode==="chat"?N:`Terminal${I}`:N),displaySecondary:nt(e)&&o?N:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:A?j.buttons:void 0,modalMessage:A?j.message:void 0,streamSource:"native",tabKey:ca(b,e.id),machineName:n,connectionState:a,settings:e.settings,messageInput:e.messageInput})}if(u&&(nt(e)||tt(e)))return r;for(const b of m){const y=b.activeModal&&Array.isArray(b.activeModal.buttons)&&b.activeModal.buttons.length>0,x=Vp(b),I=vx(b),N=`${e.id}:${I}`,j=b.title&&String(b.title).trim()||"",A=Di(j,b.agentName,b.agentType)?"":j,M=b.messages||[];(b.transport==="cdp-webview"||b.sessionId||b.providerSessionId||M.length>0||y||A||!["idle","panel_hidden","disconnected","not_monitored"].includes(x))&&r.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:x,title:A,messages:M,hostIdeType:e.type,workspaceName:o,workspacePath:l,git:b.git||e.git,displayPrimary:A||o||b.agentName||d,displaySecondary:`${d} · ${b.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:b.lastMessagePreview,lastMessageRole:b.lastMessageRole,lastMessageAt:b.lastMessageAt,lastMessageHash:b.lastMessageHash,lastUpdated:b.lastUpdated||e.lastUpdated,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,modalButtons:y?b.activeModal.buttons:void 0,modalMessage:y?b.activeModal.message:void 0,streamSource:"agent-stream",tabKey:ca(b.sessionId||b.instanceId,N),machineName:n,connectionState:a,settings:b.settings,messageInput:b.messageInput})}return r.length===0&&r.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:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:l,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:ca(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function id(e){return String(e.type||e.id||"").trim()}function jx(e){var s;return e.category!=="cli"||!id(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((s=e.lastDetection)==null?void 0:s.ok)===!0||e.installed===!0||!!e.detectedPath}function kx(e){var n;const s=new Set,r=[];for(const a of e||[]){if(!jx(a))continue;const o=id(a);if(!o||s.has(o))continue;s.add(o);const l=String(a.displayName||a.name||o),c=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:l,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c})}return r}function Wn(e){const s=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of s){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function io(e,s){const r=new Set(s.map(n=>n.type));return Wn(e).filter(n=>r.has(n))}function Nx(e){return e.map(s=>s.type)}function Sx(e,s){const r=Wn(e),n=s.trim();return!n||r.includes(n)?r:[...r,n]}function Cx(e,s){return Wn(e).filter(r=>r!==s)}function Ji(e,s,r){const n=Wn(e),a=n.indexOf(s);if(a<0)return n;const o=n.filter(c=>c!==s);if(r==="top")return[s,...o];if(r==="bottom")return[...o,s];const l=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(l,0,s),o}function Qi({direction:e}){return t.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?t.jsx("polyline",{points:"18 15 12 9 6 15"}):t.jsx("polyline",{points:"6 9 12 15 18 9"})})}function Zi({value:e,availableProviders:s,onChange:r,disabled:n=!1,saveButton:a}){const[o,l]=i.useState(""),c=i.useMemo(()=>new Map(s.map(g=>[g.type,g])),[s]),d=i.useMemo(()=>io(e,s),[e,s]),m=e.length-d.length,u=s.filter(g=>!d.includes(g.type)),h=()=>{o&&(r(Sx(d,o)),l(""))};return t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[t.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?t.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((g,k)=>{const f=c.get(g);return t.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",k+1]}),(f==null?void 0:f.icon)&&t.jsx("span",{"aria-hidden":"true",children:f.icon}),t.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:g}),t.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"})]}),t.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:f?`${f.label} · ${f.statusLabel}`:g})]}),t.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||k===0,title:"Move up",onClick:()=>r(Ji(d,g,"up")),children:t.jsx(Qi,{direction:"up"})}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||k===d.length-1,title:"Move down",onClick:()=>r(Ji(d,g,"down")),children:t.jsx(Qi,{direction:"down"})}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(Cx(d,g)),children:"Remove"})]})]},g)})}),t.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[t.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),t.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:o,onChange:g=>l(g.target.value),disabled:n||u.length===0,children:[t.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(g=>t.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:h,children:"Add provider"}),a]}),t.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",m>0?` ${m} provider${m===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function Ix(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 ld(e,s){const r=Ix(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const cd=[{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:"🏄"}],dd=[{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:"🧩"}],ud=[{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:"🟠"}],Tx=cd,Ax=dd,Mx=ud;function Qt(...e){return Vu(Gu(e))}function Lx({icon:e,title:s,subtitle:r,badge:n,actions:a,className:o}){return t.jsxs("div",{className:Qt("dashboard-header",o),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 gr({icon:e,title:s,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:l,children:c}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(Lx,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:Qt("mx-auto flex w-full flex-col gap-4",o,l),children:c})})]})}const lo="adhdev:themechange";function Rx(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Rs(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function _s(e){return e==="system"?Rx():e}function md(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function dn(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(lo,{detail:{preference:e,theme:s}}))}function _x(){const e=Rs(),s=_s(e);md(s),dn(e,s)}function Yo(){const[e,s]=i.useState(Rs),[r,n]=i.useState(()=>_s(Rs()));i.useEffect(()=>{md(r)},[r]),i.useEffect(()=>{const l=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),dn("system",m)}};return l.addEventListener("change",c),()=>l.removeEventListener("change",c)},[e]),i.useEffect(()=>{const l=d=>{const m=d.detail||{},u=m.preference,h=m.theme;s(u==="dark"||u==="light"||u==="system"?u:Rs()),n(h==="dark"||h==="light"?h:_s(Rs()))},c=d=>{if(d.key!=="theme")return;const m=Rs(),u=_s(m);s(m),n(u)};return window.addEventListener(lo,l),window.addEventListener("storage",c),()=>{window.removeEventListener(lo,l),window.removeEventListener("storage",c)}},[]);const a=i.useCallback(l=>{const c=_s(l);s(l),n(c);try{localStorage.setItem("theme",l)}catch{}dn(l,c)},[]),o=i.useCallback(()=>{s(l=>{const c=l==="dark"?"light":l==="light"?"system":"dark",d=_s(c);n(d);try{localStorage.setItem("theme",c)}catch{}return dn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const el={dark:"Dark",light:"Light",system:"System"};function Px({collapsed:e}){const{preference:s,cycleTheme:r}=Yo(),n=s==="dark"?t.jsx(Hm,{size:16}):s==="light"?t.jsx(Wm,{size:16}):t.jsx(Um,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${el[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:el[s]})]})}function da(e,s){return e?typeof e=="function"?e(s):e:null}function Dx({children:e,brand:s,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:l,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=i.useState(!1),[h,g]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),k=()=>u(!0),f=()=>u(!1),p=()=>{g(I=>{const N=!I;try{localStorage.setItem(d,N?"1":"0")}catch{}return N})},b=i.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:k,closeMobileMenu:f,toggleCollapsed:p}),[h,m]),y=I=>`nav-item${I.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${I.className?` ${I.className}`:""}`,x=I=>t.jsxs("div",{className:y(I),id:`nav-${I.id}`,onClick:()=>{I.onSelect(),f()},title:h?I.title??(typeof I.label=="string"?I.label:void 0):I.title,children:[t.jsx("span",{className:"nav-icon",children:I.icon}),!h&&I.label]},I.id);return t.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:k,children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),m&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:f,onKeyDown:I=>I.key==="Escape"&&f()}),t.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:da(s,b)}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:f,children:t.jsx(vt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:r.map(x)}),n.map(I=>t.jsxs("div",{className:I.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&I.title?t.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:I.title}):null,I.items.map(x)]},I.key)),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(x),da(o,b),t.jsx(Px,{collapsed:h}),da(l,b)]})]}),t.jsx("main",{className:"main-content relative",children:t.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function jt({title:e,icon:s,description:r,accentColor:n,className:a,children:o}){return t.jsxs("div",{className:Qt("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})]}),o]})}function An({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:Qt("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 Ex={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"},$x={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Es({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:Qt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Ex[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:$x[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:"✕"})]})}function Lt({label:e,hint:s,children:r,className:n}){return t.jsxs("div",{className:Qt("mb-5",n),children:[t.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,s&&t.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:s})]})}function ua(e){const{className:s,...r}=e;return t.jsx("input",{...r,className:Qt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",s)})}const Bx={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"},Ox={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Fx({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:Qt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Bx[e],r),children:[t.jsx("span",{className:Qt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Ox[e])}),n]})}function ms({label:e,description:s,checked:r,disabled:n,onChange:a,extra:o}){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:[o,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 Kx({onPrefChange:e}){const[s,r]=sf(),[n,a]=i.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);i.useEffect(()=>{const l=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return l(),window.addEventListener("focus",l),document.addEventListener("visibilitychange",l),()=>{window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",l)}},[]);const o=(l,c)=>{r({[l]:c}),e==null||e(l,c)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(En,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:l=>o("globalEnabled",l)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Mt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:l=>o("browserNotifications",l)}),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:()=>{Cc().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(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(zm,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:l=>o("completionAlert",l)}),t.jsx(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Vm,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:l=>o("approvalAlert",l)}),t.jsx(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ws,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:l=>o("disconnectAlert",l)})]}),!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 Mn(e){const s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Wx(e,s){const r=Mn(e),n=Mn(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 pd(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function yr(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Wx(r,s)>=0)return!1;const n=Mn(r),a=Mn(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Hx(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function ma(e,s){return e instanceof Error?e.message:s}function Ux({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(l=>l.type==="adhdev-daemon");return o.length===0?t.jsx(An,{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:o.map(l=>t.jsx(Vx,{ide:l,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},l.id))})}function tl({title:e,message:s,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const l=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return kr.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,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:c=>c.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:o,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 ${l}`,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 zx(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Tx,...Ax,...Mx].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 Vx({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var E,D;const[o,l]=i.useState("idle"),[c,d]=i.useState(""),[m,u]=i.useState(null),[h,g]=i.useState("idle"),[k,f]=i.useState(""),p=e.version||null,b=((E=e.machine)==null?void 0:E.platform)||((D=e.system)==null?void 0:D.platform)||"",y=At(e,{fallbackId:e.id}),x=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",I=s.filter(S=>S.daemonId===e.id&&S.transport==="cdp-page"),N=s.filter(S=>S.daemonId===e.id&&S.transport==="pty"),j=s.filter(S=>S.daemonId===e.id&&S.transport==="acp"),A=e.p2p,M=async()=>{if(r){l("upgrading"),d("Starting upgrade...");try{const S=Hx(await r(e.id,"daemon_upgrade",{}));S.alreadyLatest?(l("done"),d(`Already on v${S.version||"latest"}.`)):S.upgraded||S.success?(l("done"),d(`Upgrade to v${S.version||"latest"} started. Daemon is restarting...`)):(l("error"),d(S.error||"Upgrade failed"))}catch(S){l("error"),d(ma(S,"Connection lost during upgrade"))}}},v=async()=>{if(u(null),!!n){g("loading");try{await n(e.id),g("done"),f("Machine disconnected.")}catch(S){g("error"),f(ma(S,"Failed to disconnect"))}}},w=async()=>{if(u(null),!!a){g("loading");try{await a(e.id),g("done"),f("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(S){g("error"),f(ma(S,"Failed to revoke token"))}}},B="0.9.81",R=pd(e,B),T=yr(e,B),H=I.length+N.length+j.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:x}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:y}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&t.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",p,!R&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&R&&t.jsx("button",{onClick:M,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${B}`,children:o==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${T?"↑ Update now":`↑ Update${` to v${B}`}`}`}),n&&t.jsx("button",{onClick:()=>u("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>u("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(Fx,{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:[A&&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 ${A.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${A.state==="connecting"||A.state==="new"?"animate-pulse":""}`,style:A.state==="connecting"||A.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",A.state==="connected"?"connected":A.state==="connecting"||A.state==="new"?"connecting...":A.state||"off"]}),A.peers!==void 0&&A.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",A.peers," peer",A.peers!==1?"s":"",")"]})]}),A&&H>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),H>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[I.map(S=>{const C=zx(S.type),W=S.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:C.icon}),t.jsx("span",{children:C.name}),W!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${W?"bg-green-400":"animate-pulse"}`,style:W?void 0:{background:"var(--status-warning)"},title:W?"CDP connected":"CDP connecting..."})]},S.id)}),N.map(S=>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:S.cliName||"CLI"})]},S.id)),j.map(S=>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:S.cliName||"ACP"})]},S.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||k)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||h==="error"?"text-red-400":o==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:k||c})]}),m==="disconnect"&&t.jsx(tl,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
|
|
43
|
-
|
|
44
|
-
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
45
|
-
|
|
46
|
-
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:v,onCancel:()=>u(null)}),m==="revoke"&&t.jsx(tl,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
|
|
47
|
-
|
|
48
|
-
This will:
|
|
49
|
-
• Immediately disconnect the machine
|
|
50
|
-
• Delete the machine registration
|
|
51
|
-
• Require restarting ADHDev on that machine
|
|
52
|
-
|
|
53
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:w,onCancel:()=>u(null)})]})}const Gx=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function qx(){const{preference:e,setPreference:s}=Yo();return t.jsx("div",{className:"flex gap-2",children:Gx.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 Yx(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 Xx(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function pa(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function sl(e){const{r:s,g:r,b:n}=Xx(e);return .2126*pa(s)+.7152*pa(r)+.0722*pa(n)}function rl(e,s){const r=sl(e),n=sl(s),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function fd(e){const s=Yx(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return rl(s,r)>=rl(s,n)?r:n}const co={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},uo={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},Jx=[{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"}}}],hd="adhdev-chat-theme",xd="adhdev-chat-theme-custom";function un(){if(typeof window>"u")return"ember";try{return localStorage.getItem(hd)||"ember"}catch{return"ember"}}function $t(e){try{const s=localStorage.getItem(xd);if(s){const r=JSON.parse(s);return{...e==="dark"?co:uo,...r[e]}}}catch{}return e==="dark"?co:uo}function Gr(e,s){try{localStorage.setItem(xd,JSON.stringify({dark:e,light:s}))}catch{}}function Rt(e,s){const r=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${r}, ${n}, ${a}, ${s})`}function Ln(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 Qx={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function vr(e,s){var a;const r=(a=Qx[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",Ln(r,24)),n.style.setProperty("--accent-on-primary",fd(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Ln(r,18)})`),n.style.setProperty("--border-accent",Rt(r,.35)),n.style.setProperty("--nav-active-bg",Rt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Rt(r,.06)}`)}function 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",Rt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Rt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Rt(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",Rt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Rt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Ln(e.accentColor,30)),s.style.setProperty("--accent-on-primary",fd(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Ln(e.accentColor,40)})`),s.style.setProperty("--border-accent",Rt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Rt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Rt(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${Rt(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function Xo(){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 Zx(e){try{localStorage.setItem(hd,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ys()?"dark":"light";gs($t(s))}else Xo(),vr(e,ys()?"dark":"light")}function eb(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=un();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=ys()?"dark":"light";gs($t(s))}else Xo(),vr(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 St({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 or({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 tb({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=i.useState(()=>$t(r));i.useEffect(()=>{a($t(r))},[r]);const o=i.useCallback((l,c)=>{a(d=>{const m={...d,[l]:c},h=$t(r==="dark"?"light":"dark");return r==="dark"?Gr(m,h):Gr(h,m),gs(m),s(m),m})},[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(or,{title:"App Background",children:[t.jsx(St,{label:"Background",value:n.bgPrimary,onChange:l=>o("bgPrimary",l)}),t.jsx(St,{label:"Surface",value:n.bgSecondary,onChange:l=>o("bgSecondary",l)}),t.jsx(St,{label:"Card",value:n.surfacePrimary,onChange:l=>o("surfacePrimary",l)})]}),t.jsxs(or,{title:"App Text",children:[t.jsx(St,{label:"Primary",value:n.textPrimary,onChange:l=>o("textPrimary",l)}),t.jsx(St,{label:"Secondary",value:n.textSecondary,onChange:l=>o("textSecondary",l)}),t.jsx(St,{label:"Muted",value:n.textMuted,onChange:l=>o("textMuted",l)})]}),t.jsxs(or,{title:"Borders & Accent",children:[t.jsx(St,{label:"Border subtle",value:n.borderSubtle,onChange:l=>o("borderSubtle",l)}),t.jsx(St,{label:"Border default",value:n.borderDefault,onChange:l=>o("borderDefault",l)}),t.jsx(St,{label:"Accent",value:n.accentColor,onChange:l=>o("accentColor",l)})]})]}),t.jsxs("div",{children:[t.jsxs(or,{title:"Chat Bubbles",children:[t.jsx(St,{label:"User bubble",value:n.userBubble,onChange:l=>o("userBubble",l)}),t.jsx(St,{label:"User text",value:n.userText,onChange:l=>o("userText",l)}),t.jsx(St,{label:"Agent bubble",value:n.assistantBubble,onChange:l=>o("assistantBubble",l)}),t.jsx(St,{label:"Agent text",value:n.assistantText,onChange:l=>o("assistantText",l)})]}),t.jsxs(or,{title:"Chat Layout",children:[t.jsx(St,{label:"Chat BG",value:n.containerBg,onChange:l=>o("containerBg",l)}),t.jsx(St,{label:"Send button",value:n.sendButton,onChange:l=>o("sendButton",l)}),t.jsx(St,{label:"Input border",value:n.inputBorder,onChange:l=>o("inputBorder",l)}),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:l=>o("bubbleRadius",Number(l.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 l=e?co:uo,d=$t(e?"light":"dark");e?Gr(l,d):Gr(d,l),a(l),gs(l),s(l)},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 sb(){const[e,s]=i.useState(un),[r,n]=i.useState(!0),[a,o]=i.useState(()=>$t("dark"));i.useEffect(()=>{n(ys());const d=new MutationObserver(()=>{const h=ys();n(h);const g=un();g==="custom"?gs($t(h?"dark":"light")):vr(g,h?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const h=ys();n(h);const g=un();g==="custom"?gs($t(h?"dark":"light")):vr(g,h?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?gs($t(r?"dark":"light")):(Xo(),vr(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o($t(r?"dark":"light"))},[r]);const l=d=>{s(d),Zx(d)},c=[...Jx,{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:c.map(d=>{const m=e===d.id,u=r?d.preview.dark:d.preview.light,h=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>l(d.id),className:"text-left rounded-xl p-3 transition-all",style:{background:m?"var(--bg-glass-hover)":"var(--bg-glass)",border:m?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:m?1:.75},children:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"Hello! How can I help?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:h},children:"Fix the bug please"}),t.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.assistantBubble,border:u.assistantBorder,color:u.textColor},children:"On it! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[m&&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:d.id==="custom"?"🎨 Custom":d.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&t.jsx(tb,{dark:r,onColorsChange:d=>o(d)})]})}const Jo="adhdev_mobileDashboardMode_v1",mo="adhdev:mobile-dashboard-mode-change";function Qo(){try{return localStorage.getItem(Jo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function rb(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??Qo())},r=a=>{const o=a.detail;s(o)},n=a=>{a.key&&a.key!==Jo||s()};return window.addEventListener(mo,r),window.addEventListener("storage",n),()=>{window.removeEventListener(mo,r),window.removeEventListener("storage",n)}}function nb(e){try{localStorage.setItem(Jo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(mo,{detail:e}))}function ab(){const[e,s]=i.useState(!0);return i.useEffect(()=>{s(Qo()==="chat")},[]),t.jsx(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Jt,{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),nb(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const fa=new Map,nl=new Map;function ob(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function ib(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 bd(){const{sendCommand:e}=wt(),{injectEntries:s,getIdes:r}=Nr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??rh,l=nl.get(n)||0;if(!(a!=null&&a.force)&&l>0&&Date.now()-l<o)return;const c=fa.get(n);if(c)return c;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=ob(m);if(!u)return;const h=r().find(k=>k.id===n),g=ib(h,n,u.machine,u.timestamp||Date.now());s([g]),nl.set(n,Date.now())})().finally(()=>{fa.delete(n)});return fa.set(n,d),d},[r,s,e])}function lb(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 cb(e,s){const{sendData:r}=wt(),{injectEntries:n,getIdes:a}=Nr(),o=Array.from(new Set(e.filter(Boolean))).join("|");i.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const l=o?o.split("|"):[];if(l.length===0)return;const c=l.map(d=>Xt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:s==null?void 0:s.intervalMs}},u=>{const h=a().find(k=>k.id===d),g=lb(h,d,u);n([g])}));return()=>{c.forEach(d=>d())}},[o,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function db(e,s){const{sendData:r}=wt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);return i.useEffect(()=>{if(!e){a(null),l(!1);return}if(!(s!=null&&s.enabled)||!r){l(!1);return}a(null),l(!0);let c=null;const d=Xt.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}:{}}},m=>{c&&(clearTimeout(c),c=null),a(m.diagnostics),l(!1)});return d.initialSendAccepted?c=setTimeout(()=>{l(!1)},ih):l(!1),()=>{c&&clearTimeout(c),d()}},[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:o,applyDiagnostics:a}}function ub(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function gd(e){const{sendData:s}=wt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=ub(e);if(!a||!e.sessionId||!s){n({});return}const o=Xt.subscribe({sendData:s},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},l=>{n({status:l.status,modalMessage:l.modalMessage,modalButtons:l.modalButtons}),Fs.record({interactionId:l.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:l.status,modalButtonCount:Array.isArray(l.modalButtons)?l.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const yd="adhdev_hiddenTabs",vd="adhdev_autoHiddenMeshTabs";function mb(){try{const e=localStorage.getItem(yd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ds(e){try{localStorage.setItem(yd,JSON.stringify([...e]))}catch{}}function pb(){try{const e=localStorage.getItem(vd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function al(e){try{localStorage.setItem(vd,JSON.stringify([...e]))}catch{}}function fr(e){return Fo(e)}function Hn(e,s){return Os(s).some(r=>e.has(r))}function fb(e){var s,r,n;return((s=e.settings)==null?void 0:s.launchedByCoordinator)===!0&&typeof((r=e.settings)==null?void 0:r.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0&&((n=e.settings)==null?void 0:n.spawnedSessionVisibility)==="hidden"}function hb(e,s,r=new Set){return e.filter(n=>{if(!fb(n))return!1;const a=fr(n);return r.has(a)?!1:!Hn(s,n)})}function xb(){const[e,s]=i.useState(mb),[r,n]=i.useState(pb),a=i.useCallback(g=>{const k=fr(g);s(f=>{const p=new Set(f);return p.has(k)?p.delete(k):p.add(k),ds(p),p})},[]),o=i.useCallback(g=>{const k=fr(g);s(f=>{if(f.has(k))return f;const p=new Set(f);return p.add(k),ds(p),p})},[]),l=i.useCallback(g=>{const k=fr(g);s(f=>{if(f.has(k))return f;const p=new Set(f);return p.add(k),ds(p),p}),n(f=>{if(f.has(k))return f;const p=new Set(f);return p.add(k),al(p),p})},[]),c=i.useCallback(g=>{const k=fr(g);s(f=>{if(!f.has(k))return f;const p=new Set(f);return p.delete(k),ds(p),p}),n(f=>{if(f.has(k))return f;const p=new Set(f);return p.add(k),al(p),p})},[]),d=i.useCallback(()=>{s(g=>{if(g.size===0)return g;const k=new Set;return ds(k),k})},[]),m=i.useCallback((g,k)=>{s(f=>{const p=new Set(f);for(const b of k)p.add(b);return ds(p),p})},[]),u=i.useCallback((g,k)=>{s(f=>{const p=new Set(f);for(const b of k)p.delete(b);return ds(p),p})},[]),h=i.useCallback(g=>Hn(e,g),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:l,showTarget:c,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:h}}function wd(e){return e instanceof Error?e.message:String(e||"")}function jd(e){const s=wd(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 kd(e){const s=wd(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}async function Nd({conversation:e,mode:s,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!nt(e)||tt(e))return;const o=Xs(e);if(o===s)return;const l=e.sessionId;l&&a(c=>({...c,[l]:s}));try{await n(Ts(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ut(e),mode:s})}catch(c){const d=kd(c);l&&!d&&a(m=>{const u={...m};return o===Sd(r,l)?delete u[l]:u[l]=o,u}),jd(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function ol(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 bb(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 o=ol(a,s),l=Array.isArray(a.childSessions)?a.childSessions.map(d=>ol(d,s)):a.childSessions,c=l!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:l}:{}}):a});return r?n:e}function Sd(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 gb(e,s){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,o]of Object.entries(e))Sd(s,a)===o&&(delete n[a],r=!0);return r?n:e}function yb({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{Cc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:Qc(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return of(a),i.useEffect(()=>{if(Object.keys(s).length===0)return;const l=setTimeout(()=>{r(c=>{const d=Date.now(),m={};for(const[u,h]of Object.entries(c))d-h<5e3&&(m[u]=h);return Object.keys(m).length===Object.keys(c).length?c:m})},5500);return()=>clearTimeout(l)},[s,r]),i.useEffect(()=>{const o=setInterval(()=>{const l=Date.now()-3e5;n(c=>{const d=c.filter(m=>m.timestamp>l).slice(-100);return d.length===c.length?c:d})},6e4);return()=>clearInterval(o)},[n]),null}function il(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 vs(e){const s=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],r=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,n=il(s==null?void 0:s.receivedAt)||il(s==null?void 0:s.timestamp)||0;return Math.max(r,n)}function po(e,s=0){return vs(e)||e.lastUpdated||s||0}function Cd(e){return vs(e)||e.lastUpdated||0}function Id(e,s,r=Cd){const n=r(s)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(s.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(s.displayPrimary);if(o!==0)return o;const l=e.displaySecondary.localeCompare(s.displaySecondary);return l!==0?l:e.tabKey.localeCompare(s.tabKey)}function fo(e){var r;const s=gt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function vb(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!fo(e)&&!e.title.trim()}function wb(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(fo(r))-Number(fo(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Id(s,r)})[0]||null}function Bt(e,s){const r=e.filter(l=>l.routeId===s);if(r.length===0)return null;const n=r.find(l=>l.streamSource==="native")||null,a=r.filter(l=>l.streamSource==="agent-stream"),o=wb(a);return n?o&&vb(n)?o:n:o||r[0]||null}function jb(e){const s=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!s||r.startsWith(`${s}:`)?r:`${s}:${r}`}function kb(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const a=jb(n),o=r.get(a);if(!o){r.set(a,n);continue}const l=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>l||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function ha(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 Nb(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 ll(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?Nb(Ks(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 Sb(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.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),ll(e.activeChat),...s.map(r=>[r.id||"",r.providerSessionId||"",r.transport||"",r.mode||"",r.status||"",r.title||"",r.lastMessageHash||"",String(r.lastMessageAt||""),r.lastMessagePreview||"",r.lastMessageRole||"",String(r.lastUpdated||""),ll(r.activeChat)].join(":"))].join("|")}function Cb(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 Ib(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const o of Os({routeId:n.routeId}))r.set(o,a);for(const o of Os({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Os({tabKey:n.tabKey}))r.set(o,n)}return r}function Tb(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Ab(e){const s=Tb(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=Ks(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Mb({ides:e,connectionStates:s,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>kb(e),[e]),o=i.useMemo(()=>ad(e),[e]),l=i.useRef([]),c=i.useRef([]),d=i.useRef([]),m=i.useRef(new Map),u=i.useRef(new Map),h=i.useMemo(()=>{const N=new Map,j=[];for(const w of a){const{connectionState:B="new",machineName:R}=od(w,{machineNames:o,connectionStates:s,defaultConnectionState:"new"}),T=Sb(w),H=m.current.get(w.id);if(H&&H.ide===w&&H.sourceSignature===T&&H.connectionState===B&&H.machineName===R){N.set(w.id,H),j.push(...H.conversations);continue}const E=qo(w,{machineNames:o,connectionStates:s,defaultConnectionState:"new"}),D={ide:w,sourceSignature:T,connectionState:B,machineName:R,conversations:E};N.set(w.id,D),j.push(...E)}m.current=N;const A=new Map,M=w=>{const B=Ab(w),R=u.current.get(w.tabKey);if(R&&R.signature===B)return A.set(w.tabKey,R),R.timestamp;const T={signature:B,timestamp:Cd(w)||(R==null?void 0:R.timestamp)||0};return A.set(w.tabKey,T),T.timestamp},v=[...j].sort((w,B)=>Id(w,B,M));return u.current=A,v},[a,s,o]),g=i.useMemo(()=>{const N=Cb(h,r);return ha(l.current,N)?l.current:(l.current=N,N)},[h,r]),k=i.useMemo(()=>{const N=new Map,j=Array.from(new Set(g.map(A=>A.routeId)));for(const A of j){const M=Bt(g,A);M&&N.set(A,M)}return N},[g]),f=i.useMemo(()=>{const N=new Map;for(const j of g){const A=k.get(j.routeId),M=j.streamSource==="native"&&A?A:j;for(const v of Os({providerSessionId:j.providerSessionId,sessionId:j.sessionId,tabKey:j.tabKey}))N.set(v,M)}return N},[g,k]),p=i.useMemo(()=>Ib(g,k),[g,k]),b=i.useCallback(N=>{if(N)return f.get(N)},[f]),y=i.useCallback(N=>{if(N)return p.get(N)},[p]),x=i.useMemo(()=>{const N=g.filter(j=>!Hn(n,j));return ha(c.current,N)?c.current:(c.current=N,N)},[g,n]),I=i.useMemo(()=>{const N=x.map(j=>j.tabKey);return ha(d.current,N)?d.current:(d.current=N,N)},[x]);return{chatIdes:a,conversations:g,visibleConversations:x,visibleTabKeys:I,resolveConversationBySessionId:b,resolveConversationByTarget:y}}function Lb({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const a=i.useMemo(()=>{var c;return e||!s?null:((c=r(s))==null?void 0:c.tabKey)??null},[e,r,s]),o=i.useMemo(()=>{var c;return!e||!s?null:((c=r(s))==null?void 0:c.tabKey)??null},[e,r,s]),l=i.useCallback(()=>{s&&n(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:l}}function Rb({ides:e,sendDaemonCommand:s,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{ot.setIdes(e)},[e]),i.useEffect(()=>{ot.setResolveAction((a,o,l)=>{s(a,o,l).catch(()=>{})})},[s]),i.useEffect(()=>{const a=ot.onToast(o=>{r(c=>c.some(m=>m.message===o.message&&o.timestamp-m.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const l=o.duration||5e3;setTimeout(()=>r(c=>c.filter(d=>d.id!==o.id)),l)});return()=>{a()}},[r]),i.useEffect(()=>{const a=Yc.on("status_event",o=>{ot.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=l=>{var p;const c=l.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||c.daemonId;if(!u)return;const h=Number(c.buttonIndex),g=c.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[h])||"Approve",k=String(g).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),f=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(k);s(u,"resolve_action",{action:f?"approve":"reject",button:g,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(b=>console.error("[SW Action] approval failed:",b))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",a)}},[n,s])}const _b="adhdev_dashboardLayout_v1",Pb="adhdev_dashboardDockview_v1",Db="adhdev_dashboardDockviewHiddenRestore_v1",ir={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Zo(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function Eb(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Td(e){return`${_b}:${e}`}function $b(e){const s=Td(e);return Zo(s,null)}function Bb(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=Td(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Ad(e){return`${Pb}:${e}`}function Ob(e){const s=Ad(e);return Zo(s,null)}function Fb(e,s){try{const r=Ad(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Md(e){return`${Db}:${e}`}function Kb(e){const s=Md(e);return Zo(s,{})}function Wb(e,s){try{const r=Md(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Hb(){return{groupAssignments:[...ir.groupAssignments],focusedGroup:ir.focusedGroup,groupActiveTabIds:{...ir.groupActiveTabIds},groupTabOrders:{...ir.groupTabOrders},groupSizes:[...ir.groupSizes]}}function Ub(e,s){return e?e.length===s.length&&e.every((r,n)=>r===s[n]):s.length===0}function zb(){const[e]=i.useState(()=>Eb(typeof window<"u"?window.innerWidth:1280)),[s,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,l]=i.useState({}),[c,d]=i.useState({}),[m,u]=i.useState([]),[h,g]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[k,f]=i.useState(!1),p=i.useCallback(()=>{if(k)return;const w=$b(e)??Hb();r(new Map(w.groupAssignments)),a(w.focusedGroup),l(w.groupActiveTabIds),d(w.groupTabOrders),u(w.groupSizes),f(!0)},[k,e]);i.useEffect(()=>{k&&Bb(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:m})},[k,e,s,n,o,c,m]),i.useEffect(()=>{const w=window.matchMedia("(max-width: 767px)"),B=R=>g(R.matches);return w.addEventListener("change",B),()=>w.removeEventListener("change",B)},[]);const b=i.useCallback(w=>{r(w)},[]),y=i.useCallback(w=>{a(w)},[]),x=i.useCallback(w=>{l(w)},[]),I=i.useCallback(w=>{d(w)},[]),N=i.useCallback(w=>{u(w)},[]),j=i.useCallback(w=>{y(w)},[y]),A=i.useCallback((w,B)=>{l(R=>(R[w]??null)===(B??null)?R:{...R,[w]:B})},[]),M=i.useCallback((w,B)=>{d(R=>{const T=R[w];return Ub(T,B)?R:{...R,[w]:B}})},[]),v=i.useCallback((w,B)=>{const R=B.get(w)??0;return A(R,w),j(R),R},[j,A]);return{layoutProfile:e,groupAssignments:s,updateGroupAssignments:b,focusedGroup:n,updateFocusedGroup:y,focusGroup:j,groupActiveTabIds:o,updateGroupActiveTabIds:x,setGroupActiveTab:A,groupTabOrders:c,updateGroupTabOrders:I,setGroupTabOrder:M,groupSizes:m,updateGroupSizes:N,isMobile:h,hasHydratedStoredLayout:k,hydrateStoredLayout:p,focusConversationTab:v}}function Vb(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Oo(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Gb({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:l,setSearchParams:c,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:h,handleRefreshHistory:g}){const k=i.useRef(!1),f=i.useRef(!1),p=i.useRef(null),b=i.useRef(!1);i.useEffect(()=>{if(!e||k.current||s.length===0)return;if(!a){o();return}const y=r(e);y&&(l(y.tabKey,n),k.current=!0,f.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),c(x=>{const I=new URLSearchParams(x);return I.delete("activeTab"),I},{replace:!0}))},[e,s,r,n,a,o,l,c]),i.useEffect(()=>{if(!(f.current||a)&&s.length!==0){if(!e){o(),f.current=!0;return}if(k.current){f.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(f.current||a)&&(o(),f.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,s.length,a,o]),i.useEffect(()=>{if(!d){b.current=!1;return}if(!m||b.current||u)return;const y=h.find(x=>x.id===m.routeId);y&&(!y.chats||y.chats.length===0||Vb(y.chats,m))&&(b.current=!0,g())},[d,m,u,h,g])}function xa(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=Oo(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Ld({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[l,c]=i.useState(!1),[d,m]=i.useState(!1),u=i.useCallback(async f=>{try{await e("standalone","launch_ide",{ideType:f,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=i.useCallback(async(f,p)=>{try{const b=f||(s==null?void 0:s.daemonId)||"",y=await e(b,"switch_chat",{id:p,sessionId:p,...fs(s)}),x=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||x==="switched"||x==="switched-by-title")return;x===!1||x==="not_found"?rr(a,"⚠️ Session tab not found — try refreshing history"):typeof x=="string"&&x.startsWith("error:")?rr(a,`⚠️ Switch error: ${x}`):rr(a,"⚠️ Session switch failed")}catch(b){console.error("Switch failed",b),rr(a,`❌ Switch failed: ${b.message||"connection error"}`)}},[s,e,a]),g=i.useCallback(async()=>{if(!(!s||l)){c(!0);try{const f=Us(s);await e(f,"new_chat",{...fs(s)}),o(p=>({...p,[s.tabKey]:Date.now()}))}catch(f){console.error("New chat failed",f)}finally{c(!1)}}},[s,l,e,o]),k=i.useCallback(async()=>{var f,p;if(!(!s||d)){m(!0);try{const b=Us(s),y=async()=>e(b,"list_chats",{forceExpand:!0,...fs(s)});let x=await y(),I=(x==null?void 0:x.chats)||((f=x==null?void 0:x.result)==null?void 0:f.chats);xa(I,s)&&(await new Promise(N=>setTimeout(N,450)),x=await y(),I=(x==null?void 0:x.chats)||((p=x==null?void 0:x.result)==null?void 0:p.chats)),x!=null&&x.success&&Array.isArray(I)&&(n(s.routeId,I),xa(I,s)&&!xa(r,s)&&rr(a,"⚠️ History dialog did not fully open — try once more"))}catch(b){console.error("Refresh history failed",b)}finally{m(!1)}}},[s,r,d,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:h,handleNewChat:g,handleRefreshHistory:k}}function qb(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 Yb(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function cl(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 qr(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[l,c]of e)!r.has(l)||c<=0||n.includes(c)||n.push(c);n.sort((l,c)=>l-c);const a={};n.forEach((l,c)=>{a[l]=c}),n.length===0&&(a[0]=0);const o=new Map;for(const[l,c]of e){if(!r.has(l)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(l,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function dl(e,s){const r={};for(const[n,a]of Object.entries(e)){const o=s[Number(n)];typeof o=="number"&&(r[o]=a)}return r}function Xb(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 Jb(e,s,r){if(s.length<=1)return[];const n=s.map(l=>e[l]).filter(l=>Number.isFinite(l)),a=n.length===s.length?n:Array(r).fill(100/r),o=a.reduce((l,c)=>l+c,0);return o>0?a.map(l=>l/o*100):Array(r).fill(100/r)}function ul(e,s){const r={};for(const[n,a]of Object.entries(e)){const o=Number(n);r[o>=s?o+1:o]=a}return r}function ml(e){return Array(e).fill(100/e)}function Qb({groupAssignments:e,updateGroupAssignments:s,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:l,isMobile:c,visibleConversations:d,visibleTabKeys:m}){const u=i.useRef(null),h=i.useMemo(()=>qr(e,m),[e,m]),g=h.assignments,k=i.useMemo(()=>c?1:h.groupCount,[h.groupCount,c]),f=k>1,p=i.useCallback((j,A)=>{s(M=>{const v=new Map(qr(M,m).assignments);return A===0?v.delete(j):v.set(j,A),v}),n(M=>({...M,[A]:j})),r(A)},[s,m,n,r]),b=i.useCallback(j=>{s(A=>{const M=qr(A,m).assignments,v=new Map;for(const[w,B]of M)B!==j&&(B>j?v.set(w,B-1):v.set(w,B));return v}),l(A=>{if(A.length<=1)return[];const M=[...A];M.splice(j,1);const v=M.reduce((w,B)=>w+B,0);return v>0?M.map(w=>w/v*100):[]}),r(0)},[s,m,l,r]),y=i.useCallback((j,A)=>{A.preventDefault();const M=u.current;if(!M)return;const v=A.clientX,w=M.offsetWidth,B=o.length===k?[...o]:ml(k),R=H=>{const D=(H.clientX-v)/w*100,S=[...B];S[j]=Math.max(15,B[j]+D),S[j+1]=Math.max(15,B[j+1]-D),l(S)},T=()=>{document.removeEventListener("mousemove",R),document.removeEventListener("mouseup",T),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",R),document.addEventListener("mouseup",T)},[o,k,l]),x=i.useCallback((j,A,M)=>{if(k>=4)return;const v=M==="left"?A:A+1;s(w=>{const B=qr(w,m).assignments,R=new Map;for(const T of d){const H=B.get(T.tabKey)??0,E=H>=v?H+1:H;E>0&&R.set(T.tabKey,E)}return v>0&&R.set(j,v),R}),l(w=>{const B=w.length===k?[...w]:ml(k),R=B[A]??100/k,T=Math.max(15,R/2),H=Math.max(15,R/2),E=[...B];E[A]=T,E.splice(v,0,H);const D=E.reduce((S,C)=>S+C,0);return E.map(S=>S/D*100)}),n(w=>{const B=ul(w,v);return B[v]=j,B}),a(w=>{const B=ul(w,v);return B[v]=[j],B}),r(v)},[k,s,m,d,l,n,a,r]);i.useEffect(()=>{qb(e,g)||s(g)},[e,g,s]),i.useEffect(()=>{const{mapping:j,usedGroups:A}=h;n(M=>{const v=dl(M,j);return cl(M,v)?M:v}),a(M=>{const v=dl(M,j);return cl(M,v)?M:v}),r(M=>{const v=c?0:Xb(M,A,j);return M===v?M:v}),l(M=>{const v=c?[]:Jb(M,A,h.groupCount);return Yb(M,v)?M:v})},[h,c,n,a,r,l]);const I=i.useMemo(()=>{const j=Array.from({length:k},()=>[]);for(const A of d){const M=g.get(A.tabKey)??0,v=Math.min(M,k-1);j[v].push(A)}return j},[d,g,k]),N=i.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:u,normalizedGroupAssignments:g,numGroups:k,isSplitMode:f,groupedConvs:I,moveTabToGroup:p,closeGroup:b,handleResizeStart:y,splitTabRelative:x,clearAllSplits:N}}function ba(e){if(typeof e!="string")return null;const s=e.trim().toLowerCase();return s==="stable"||s==="latest"?"stable":s==="preview"||s==="next"?"preview":null}function Zb(e){if(typeof e!="string")return null;const s=e.trim().toLowerCase();return s==="latest"||s==="stable"?"latest":s==="next"||s==="preview"?"next":null}function Yr(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}function ei(e){const s=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=ba(s.channel)||ba(e.updateChannel)||ba(e.releaseChannel)||void 0,n=Zb(s.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=Yr(s.targetVersion)||Yr(e.serverVersion)||void 0,o=Yr(s.minVersion)||void 0,l=Yr(s.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...l?{updateCommand:l}:{}}}function Ps(e,s=null){return ei(e).targetVersion||s}function Rd(e){return ei(e).channel||null}function _d(e){const s=ei(e);return{...s.channel?{channel:s.channel}:{},...s.npmTag?{npmTag:s.npmTag}:{},...s.targetVersion?{targetVersion:s.targetVersion}:{},...Object.keys(s).length>0?{updatePolicy:s}:{}}}function eg({ides:e,sendDaemonCommand:s}){const r="0.9.81",n=i.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:pd(h,Ps(h,r))).sort((h,g)=>Number(yr(g,Ps(g,r)))-Number(yr(h,Ps(h,r)))),[r,e]),a=i.useMemo(()=>n.some(h=>yr(h,Ps(h,r))),[r,n]),o=i.useMemo(()=>n.map(h=>Ps(h,r)).find(h=>typeof h=="string"&&h.trim().length>0)||r,[r,n]),[l,c]=i.useState(!1),[d,m]=i.useState({}),u=i.useCallback(async h=>{var k,f;const g=e.find(p=>p.id===h);if(g){m(p=>({...p,[h]:"upgrading"}));try{const p=await s(h,"daemon_upgrade",_d(g));(k=p==null?void 0:p.result)!=null&&k.upgraded||(f=p==null?void 0:p.result)!=null&&f.success?m(b=>({...b,[h]:"done"})):m(b=>({...b,[h]:"error"}))}catch{m(p=>({...p,[h]:"error"}))}}},[e,s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:l,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const Pd=80;function mn(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function tg(e){return{...e,createdAt:mn(e.createdAt),updatedAt:mn(e.updatedAt,e.createdAt),lastEventAt:mn(e.lastEventAt,e.updatedAt||e.createdAt)}}function sg(e){const s=Fo(e);return s==="unknown:"?e.id:s}function rg(e){return[e.type,Wc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function ng(e,s=Pd){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=sg(n),o=r.get(a);if(!o){r.set(a,n);continue}(n.updatedAt>o.updatedAt||n.updatedAt===o.updatedAt&&n.createdAt>o.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const o=a.updatedAt-n.updatedAt;return o!==0?o:a.createdAt-n.createdAt}).slice(0,Math.max(0,s))}function ag(e,s){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?s.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const l=Bn(a,s),c=l.inboxBucket==="needs_attention"?"needs_attention":l.inboxBucket==="task_complete"&&l.unread?"task_complete":null;if(!c)continue;const d=mn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=rg({type:c,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});n.push(tg({id:m,dedupKey:m,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Rc(a),preview:Df(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return ng(n)}function og(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function ig(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=Pd}=e,a=i.useMemo(()=>ag(s,r).slice(0,Math.max(0,n)),[s,r,n]),o=i.useMemo(()=>og(a),[a]);return{notifications:a,unreadCount:o}}function lg({notifications:e,sendDaemonCommand:s}){const r=i.useCallback(o=>{const l=e.find(d=>d.id===o),c=Math.max(Date.now(),(l==null?void 0:l.updatedAt)||0);l!=null&&l.sessionId&&s(l.machineId||l.routeId,"mark_session_seen",{sessionId:l.sessionId,seenAt:c}).catch(()=>{})},[e,s]),n=i.useCallback(o=>{const l=e.find(c=>c.id===o);l!=null&&l.sessionId&&s(l.machineId||l.routeId,"mark_notification_unread",{sessionId:l.sessionId,notificationId:l.id}).catch(()=>{})},[e,s]),a=i.useCallback(o=>{const l=e.find(c=>c.id===o);l!=null&&l.sessionId&&s(l.machineId||l.routeId,"delete_notification",{sessionId:l.sessionId,notificationId:l.id}).catch(()=>{})},[e,s]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const cg=i.createContext(null);function Dd(){return i.useContext(cg)}function Un(...e){const s=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const l=o.toLowerCase();s.has(l)||(s.add(l),r.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)n(o);continue}n(a)}return r}function dg(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 zn(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=dg(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 ug(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 mg(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Vn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=mg(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 o=typeof(a==null?void 0:a.path)=="string"?a.path:r,l=o.includes("\\")?"\\":"/",c=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${l}${u}`:`${m.replace(/[\\/]+$/,"")}${l}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(m=>(m==null?void 0:m.type)==="directory"&&typeof(m==null?void 0:m.name)=="string").map(m=>({name:m.name,path:typeof(m==null?void 0:m.path)=="string"&&m.path.trim()?m.path:c(o,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:o,directories:d}}function pg(e,s){const r={meshId:s.meshId||"",workspace:s.workspace||"",serverName:s.serverName||"adhdev-mesh",adhdevMcpCommand:s.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function Ed(e,s={}){const r=e==null?void 0:e.mcpConfig;return(r==null?void 0:r.mode)!=="manual"?null:{serverName:r.serverName||"adhdev-mesh",configFormat:r.format,configPathCommand:r.configPathCommand,requiresRestart:r.requiresRestart===!0,instructions:r.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:pg(r.template||"",{...s,serverName:r.serverName||"adhdev-mesh"})}}function fg(e){if(!e||typeof e!="object")return null;const s=e,r=typeof s.instructions=="string"?s.instructions:"",n=typeof s.template=="string"?s.template:"";return!r&&!n?null:{serverName:typeof s.serverName=="string"?s.serverName:void 0,configFormat:typeof s.configFormat=="string"?s.configFormat:void 0,configPathCommand:typeof s.configPathCommand=="string"?s.configPathCommand:void 0,requiresRestart:s.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function zt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function $d(e){return Rr(e)||e.tabKey||e.routeId||null}function Bd(e){const s=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(n&&o.routeId!==n)return!1;const l=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(s&&l.includes(s)||r&&l.includes(r)||n&&o.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const o=Bt(e.conversations,n)||e.conversations.find(l=>l.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return s||r||n||null}function ss(e){return String(e||"").trim()}function Od(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Rn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function hg(e,s){return!e||!s?!1:e===s||e.endsWith(`/${s}`)||s.endsWith(`/${e}`)}function xg(e,s){const r=ss(e.providerSessionId),n=ss(e.targetSessionId),a=s.find(o=>{const l=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(ss).filter(Boolean);return!!(r&&l.includes(r)||n&&l.includes(n))});return a?a.tabKey:n||r||null}function bg(e,s,r){if(s.event!=="agent:generating_completed")return null;const n=Od(s.daemonId);if(n&&n!==e.machineId)return null;const a=ss(s.providerType);if(e.providerType&&a!==e.providerType)return null;const o=ss(e.resumeSessionId),l=ss(e.launchedSessionId),c=ss(s.providerSessionId),d=ss(s.targetSessionId);if(o&&o!==c&&o!==d||l&&l!==c&&l!==d)return null;const m=Rn(e.workspacePath);if(m){const u=Rn(s.workspaceName);if(u&&!hg(u,m))return null}return xg(s,r)}function pl(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function gg({ides:e,conversations:s,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useRef(null),l=i.useCallback(()=>{o.current=null,a(null)},[]),c=i.useCallback(d=>{o.current=d,a(d)},[]);return i.useEffect(()=>{if(!n)return;const d=Rn(n.workspacePath),m=e.find(h=>{var b,y,x,I;if(!h||h.type==="adhdev-daemon"||Od(h.daemonId||h.id)!==n.machineId||(Cr(h)?"cli":$s(h)?"acp":"ide")!==n.kind)return!1;const f=String(h.agentType||h.type||"");if(n.providerType&&f!==n.providerType)return!1;if(n.resumeSessionId)return String(h.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const N=String(n.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(A=>String(A||"")).filter(Boolean).includes(N)}if(d){const N=Rn(h.workspace||h.runtimeWorkspaceLabel);return N?N===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((I=(x=(y=(b=h.activeChat)==null?void 0:b.messages)==null?void 0:y.at)==null?void 0:x.call(y,-1))==null?void 0:I.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=Bd({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:s});u&&(l(),r(u))},[l,s,e,r,n]),i.useEffect(()=>ot.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=bg(m,d,s);u&&(l(),r(u))}),[l,s,r]),i.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(m=>!m||m.startedAt!==n.startedAt?m:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:c}}function yg({sendDaemonCommand:e,trackPendingLaunch:s,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const l=Dd(),c=i.useCallback(async(p,b)=>Vn(e,p,b),[e]),d=i.useCallback(async(p,b)=>{if(!b.trim())return{ok:!1,error:"Choose a workspace path first."};try{const y=await e(p,"workspace_add",{path:b.trim()});return y!=null&&y.success?{ok:!0}:{ok:!1,error:(y==null?void 0:y.error)||"Could not save workspace"}}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not save workspace"}}},[e]),m=i.useCallback(async(p,b,y)=>{var x;try{const I={ideType:b,enableCdp:!0};(x=y==null?void 0:y.workspacePath)!=null&&x.trim()&&(I.workspace=y.workspacePath.trim());const N=await e(p,"launch_ide",I);return!(N!=null&&N.success)&&(N==null?void 0:N.success)!==void 0?{ok:!1,error:(N==null?void 0:N.error)||"Could not launch IDE"}:(s({machineId:p,kind:"ide",providerType:b,workspacePath:(y==null?void 0:y.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(I){return{ok:!1,error:I instanceof Error?I.message:"Could not launch IDE"}}},[e,s]),u=i.useCallback(async(p,b,y,x)=>{var N,j,A;const I=Date.now();try{const M={cliType:y};(N=x==null?void 0:x.workspacePath)!=null&&N.trim()?M.dir=x.workspacePath.trim():x!=null&&x.workspaceId&&(M.workspaceId=x.workspaceId),(j=x==null?void 0:x.resumeSessionId)!=null&&j.trim()&&(M.resumeSessionId=x.resumeSessionId.trim()),Array.isArray(x==null?void 0:x.cliArgs)&&x.cliArgs.length>0&&(M.cliArgs=x.cliArgs),(A=x==null?void 0:x.initialModel)!=null&&A.trim()&&(M.initialModel=x.initialModel.trim());const v=await e(p,"launch_cli",M),w=(v==null?void 0:v.result)||v,B=(w==null?void 0:w.sessionId)||(w==null?void 0:w.id);return v!=null&&v.success&&B?(s({machineId:p,kind:b,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,launchedSessionId:B,startedAt:I}),{ok:!0}):v!=null&&v.success?(s({machineId:p,kind:b,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:I}),{ok:!0}):{ok:!1,error:(v==null?void 0:v.error)||(w==null?void 0:w.error)||`Could not launch ${b.toUpperCase()} session`}}catch(M){return pl(M)?(s({machineId:p,kind:b,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:I}),{ok:!0}):{ok:!1,error:M instanceof Error?M.message:`Could not launch ${b.toUpperCase()} session`}}},[r,e,s]),h=i.useCallback(async p=>{var b;if(l!=null&&l.listMeshes)return l.listMeshes(p);if(!p)return[];try{const y=await e(p,"list_meshes",{}),x=(y==null?void 0:y.result)??y;if((x==null?void 0:x.success)===!1)throw new Error((x==null?void 0:x.error)||"Could not load meshes");return(Array.isArray(x==null?void 0:x.meshes)?x.meshes:Array.isArray((b=x==null?void 0:x.result)==null?void 0:b.meshes)?x.result.meshes:[]).map(N=>{var j;return{id:String((N==null?void 0:N.id)||""),name:String((N==null?void 0:N.name)||(N==null?void 0:N.id)||"Untitled mesh"),repoIdentity:(N==null?void 0:N.repoIdentity)||(N==null?void 0:N.repo_identity)||null,workspace:Array.isArray(N==null?void 0:N.nodes)&&N.nodes.length>0?String(((j=N.nodes[0])==null?void 0:j.workspace)||""):null,nodesCount:Array.isArray(N==null?void 0:N.nodes)?N.nodes.length:void 0,status:(N==null?void 0:N.status)||null}}).filter(N=>N.id)}catch(y){throw console.error("List meshes failed",y),y}},[l,e]),g=i.useCallback(async(p,b,y)=>{if(!b.trim())return{ok:!1,error:"Choose a mesh first."};if(l!=null&&l.launchMeshCoordinator)return l.launchMeshCoordinator(p,b,y);const x=Date.now();try{const I={meshId:b.trim()};y.trim()&&(I.cliType=y.trim());const N=await e(p,"launch_mesh_coordinator",I),j=(N==null?void 0:N.result)??N;if((j==null?void 0:j.success)===!1||(N==null?void 0:N.success)===!1){const M=String((j==null?void 0:j.code)||(N==null?void 0:N.code)||""),v=fg((j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup)||(N==null?void 0:N.meshCoordinatorSetup)||(N==null?void 0:N.manualSetup));return{ok:!1,error:(j==null?void 0:j.error)||(N==null?void 0:N.error)||"Could not launch mesh coordinator",code:M||void 0,manualSetup:v}}const A=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return A?r(A):s({machineId:p,kind:"cli",providerType:(j==null?void 0:j.cliType)||y.trim()||void 0,workspacePath:(j==null?void 0:j.workspace)||null,startedAt:x}),{ok:!0}}catch(I){return pl(I)?(s({machineId:p,kind:"cli",providerType:y.trim()||void 0,startedAt:x}),{ok:!0}):{ok:!1,error:I instanceof Error?I.message:"Could not launch mesh coordinator"}}},[l,r,e,s]),k=i.useCallback(async(p,b)=>{if(!p||!b)return[];try{const y=await e(p,"list_saved_sessions",{providerType:b,kind:"cli",limit:30}),x=(y==null?void 0:y.result)??y;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(y){return console.error("List saved sessions failed",y),[]}},[e]),f=i.useCallback(async p=>{await Nd({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:h,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:k,setActiveCliViewMode:f}}function vg(e){switch(e){case"notification-open":case"toast-open":case"conversation-open":case"requested-tab":return!0;case"dockview-shortcut":case"dockview-focus":case"dockview-move":case"dockview-split":case"stored-layout-restore":case"passive-tab-sync":return!1;default:return!1}}function wg(e,s,r=Date.now()){return!e||!vg(s)?null:{tabKey:e,nonce:r}}function jg({isMobile:e,conversations:s,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:l}){const[c,d]=i.useState(null),[m,u]=i.useState(null),h=i.useMemo(()=>{var b,y;if(!e){if(c){const x=s.find(I=>I.tabKey===c);if(x)return x}return r[0]}const p=n[a];if(p){const x=s.find(I=>I.tabKey===p);if(x)return x}return((b=o[a])==null?void 0:b[0])||((y=o[0])==null?void 0:y[0])},[s,c,a,n,o,e,r]),g=i.useCallback(p=>{d(p)},[]),k=i.useCallback(p=>{d(p.tabKey),l(b=>{const y=new URLSearchParams(b),x=$f(p);return x?y.set("activeTab",x):y.delete("activeTab"),y},{replace:!0})},[l]),f=i.useCallback((p,b)=>{const y=wg(p,b);y&&u(y)},[]);return{activeConv:h,openDesktopConversation:k,requestScrollToBottom:f,scrollToBottomRequest:m,setDesktopActiveTab:g}}function kg(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 Ng(e){const s=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",s,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&s&&s!==r),autoReadKey:o,completionMarker:s,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Sg({activeConv:e,isMobile:s,liveSessionInboxState:r,sendDaemonCommand:n}){const a=i.useRef(null),o=i.useRef(null),l=i.useRef(null),c=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{const m=()=>{l.current&&(clearTimeout(l.current),l.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(s){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=jn(e,r),h=Ng({tabKey:e.tabKey,historySessionId:Rr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:vs(e),liveState:u}),g=h.autoReadKey,k=kg({autoReadKey:g,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!h.shouldMarkSeen){k.shouldCancelPending&&m(),a.current=g;return}if(!k.shouldSchedule)return;k.shouldCancelPending&&m();const f=()=>{if(document.visibilityState!=="visible"||a.current===g)return;a.current=g,o.current=null,l.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const b=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:b,completionMarker:h.completionMarker}).catch(()=>{})};if(o.current=k.nextPendingKey,document.visibilityState==="visible"){l.current=setTimeout(f,1500);const b=()=>{document.visibilityState!=="visible"&&l.current&&(clearTimeout(l.current),l.current=null)};d.current=b,document.addEventListener("visibilitychange",b);return}const p=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(f,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,s,r,n]),i.useEffect(()=>()=>{l.current&&clearTimeout(l.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function ga(e){if(!e)return"";const s=String(e.workspacePath||"").trim();if(s)return s;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function Cg({activeConv:e,remoteDialogConv:s,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:l,setClearedTabs:c,setSearchParams:d}){var C;const[m,u]=i.useState(!1),[h,g]=i.useState([]),[k,f]=i.useState(()=>Nt()),[p,b]=i.useState(!1),[y,x]=i.useState(null),I=i.useRef(null),N=i.useMemo(()=>r||s||e,[e,r,s]),j=!!N&&nt(N)&&!tt(N),A=i.useMemo(()=>{if(!N||!j)return null;const W=N.daemonId||N.routeId||"",_=Ut(N),O=ga(N);return`${W}:${_}:${N.providerSessionId||""}:${O}`},[N,j]),M=i.useMemo(()=>!N||!j?"":ga(N),[N,j]),{isCreatingChat:v,isRefreshingHistory:w,handleSwitchSession:B,handleNewChat:R,handleRefreshHistory:T}=Ld({sendDaemonCommand:a,activeConv:N,chats:(C=n.find(W=>W.id===(N==null?void 0:N.routeId)))==null?void 0:C.chats,updateRouteChats:o,setToasts:l,setClearedTabs:c}),H=i.useCallback(()=>{u(!0)},[]),E=i.useCallback(()=>{u(!1)},[]),D=i.useCallback(async()=>{if(!(!N||!j||p)){b(!0);try{const W=N.daemonId||N.routeId,_=Ut(N),O=ga(N),V=await a(W,"list_saved_sessions",{agentType:_,providerType:_,kind:"cli",limit:50,...N.providerSessionId?{providerSessionId:N.providerSessionId}:{},...O?{workspace:O}:{}}),X=(V==null?void 0:V.result)??V;g(Array.isArray(X==null?void 0:X.sessions)?X.sessions:[])}catch(W){console.error("Refresh saved sessions failed",W),g([])}finally{b(!1)}}},[N,p,j,a]);i.useEffect(()=>{if(!m){I.current=null;return}if(!j){I.current=null,g([]),b(!1);return}!A||p||I.current!==A&&(I.current=A,D())},[D,m,p,j,A]);const S=i.useCallback(async W=>{if(!N||!j||!W.providerSessionId||!W.workspace)return;const _=N.daemonId||N.routeId,O=Ut(N);try{x(W.providerSessionId);const V=await a(_,"launch_cli",{cliType:O,dir:W.workspace,resumeSessionId:W.providerSessionId,initialModel:Nc(W.summaryMetadata,"model",{preferShortValue:!0})||void 0}),X=(V==null?void 0:V.result)??V,ye=typeof(X==null?void 0:X.sessionId)=="string"?X.sessionId:typeof(X==null?void 0:X.id)=="string"?X.id:"";ye&&d(he=>{const ne=new URLSearchParams(he);return ne.set("activeTab",ye),ne},{replace:!0}),E()}catch(V){console.error("Resume saved session failed",V)}finally{x(null)}},[E,N,j,a,d]);return{historyModalOpen:m,openHistoryModal:H,closeHistoryModal:E,historyTargetConv:N,isSavedSessionHistoryTarget:j,isHistoryCreatingChat:v,isHistoryRefreshingHistory:w,handleHistorySwitchSession:B,handleHistoryNewChat:R,handleHistoryRefresh:T,savedHistorySessions:h,savedHistoryFilters:k,setSavedHistoryFilters:f,missingWorkspaceResumePath:M,isSavedHistoryLoading:p,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:D,handleResumeSavedHistorySession:S}}function Ig({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}){const[d,m]=i.useState(null),[u,h]=i.useState(null),g=i.useMemo(()=>{if(e||!n)return null;const y=c(n);return y&&!nt(y)&&!tt(y)?y:null},[e,n,c]),k=i.useMemo(()=>{const y=d==null?void 0:d.routeId;if(!y)return null;const x=d!=null&&d.tabKey?o.find(I=>I.tabKey===d.tabKey):a?o.find(I=>I.tabKey===a):null;return(x==null?void 0:x.routeId)===y?x:Bt(o,y)},[o,d,a]),f=i.useMemo(()=>{if(k)return l.find(y=>y.id===k.routeId)},[l,k]);i.useEffect(()=>{g&&(m({routeId:g.routeId,tabKey:Bi(g)}),h(g),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,g]);const p=i.useCallback(y=>{y&&(m({routeId:y.routeId,tabKey:Bi(y)}),h(y))},[]),b=i.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:k,remoteDialogIdeEntry:f,remoteDialogActiveConv:u,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:b}}function Tg({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:g,setRemoteDialogActiveConv:k,openRemoteDialog:f,closeRemoteDialog:p}=Ig({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}),[b,y]=i.useState(!1),[x,I]=i.useState(null),N=i.useCallback(async M=>{const v=M||d;!v||!nt(v)&&!tt(v)||(I(v),y(!0))},[d]),j=i.useCallback(()=>{y(!1),I(null)},[]),A=i.useCallback(async M=>{const v=x||d;if(!v||!nt(v)&&!tt(v)){j();return}y(!1);try{const w=Ut(v),B=v.routeId||v.daemonId||"";await m(B,"stop_cli",{cliType:w,targetSessionId:v.sessionId,mode:M})}catch(w){console.error("Stop CLI failed:",w)}finally{I(null)}},[d,j,x,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:g,setRemoteDialogActiveConv:k,openRemoteDialog:f,closeRemoteDialog:p,cliStopDialogOpen:b,cliStopTargetConv:x,requestCliStop:N,cancelCliStop:j,confirmCliStop:A}}function Fd({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var I,N;const l=ls(),c=Ts(e),d=o?null:Lc(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),g=Hs(e),k=Ef(e),f=(I=e.settings)==null?void 0:I.meshNodeFor,p=e.meshQueueStats,b=(N=e.settings)==null?void 0:N.meshCoordinatorFor;if(!m&&!u&&!h&&!d&&!f&&!p)return null;const y=i.useCallback(()=>{if(n){n();return}c&&l("/dashboard",{state:{openMachineId:c}})},[c,l,n]),x=i.useCallback(()=>{if(r){r();return}const j=$d(e);j&&l(zt(j))},[e,l,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[m&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:x,title:k,children:[t.jsx(Mt,{size:12}),t.jsx("span",{children:k})]}):t.jsxs("span",{className:"conversation-meta-chip",title:k,children:[t.jsx(Mt,{size:12}),t.jsx("span",{children:k})]})),u&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[t.jsx(Ws,{size:12}),t.jsx("span",{children:g})]}),h&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[t.jsx(Ws,{size:12}),t.jsx("span",{children:g})]}),d&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:d,children:[t.jsx(as,{size:12}),t.jsx("span",{children:d})]}):t.jsxs("span",{className:"conversation-meta-chip",title:d,children:[t.jsx(as,{size:12}),t.jsx("span",{children:d})]})),f&&t.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[t.jsx(as,{size:12}),t.jsx("span",{children:"Mesh Node"})]}),b&&p&&t.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[t.jsx(Dm,{size:12}),t.jsxs("span",{children:[p.pending," Pending"]})]})]})}function ya(e,s=!0){return(e??!0)&&s}const ti=i.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:l,handleRelaunch:c,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:p,isInputActive:b=!0,isVisible:y=!0}){const x=n,I=!n,N=ya(y,x),j=ya(y,I),A=ya(y),M=gd(s),v=M.status||M.modalMessage||M.modalButtons?{...s,...M.status?{status:M.status}:{},...M.modalMessage!==void 0?{modalMessage:M.modalMessage}:{},...M.modalButtons!==void 0?{modalButtons:M.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(wc,{activeConv:v,onModalButton:l}),t.jsx(Fd,{conversation:v,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),v.transport!=="pty"&&v.transport!=="acp"&&v.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[t.jsx("span",{className:"text-sm",children:t.jsx(Sr,{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:c,children:"Relaunch with CDP"})]})}):null,v.transport==="pty"?t.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[t.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:x?"visible":"hidden",pointerEvents:x?"auto":"none"},children:t.jsx(Xh,{activeConv:v,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:N,isInputActive:b&&N})}),t.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:I?"visible":"hidden",pointerEvents:I?"auto":"none"},children:t.jsx(oo,{activeConv:v,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:p,isInputActive:b&&j,isVisible:j})})]}):t.jsx(oo,{activeConv:v,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:g,actionLogs:k,userName:f,scrollToBottomRequestNonce:p,isInputActive:b&&A,isVisible:A})]})},(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&&e.isVisible===s.isVisible);function Ag({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:l,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:h,onOpenHistory:g,onOpenRemote:k,onOpenMeshGraph:f,onStopCli:p,cliViewMode:b,onSetCliViewMode:y,handleSendChat:x,handleFocusAgent:I,handleModalButton:N,handleRelaunch:j}){var R;const A=i.useRef(null),M=nt(e)&&!s,v=M&&b==="terminal",w=!!e.daemonId&&typeof((R=e.settings)==null?void 0:R.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,B=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 ${B} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:t.jsx(ko,{size:18})}),t.jsxs("div",{className:"min-w-0 flex-1 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:dt(e)}),t.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:t.jsx(Fd,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>h(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[M&&b&&t.jsx(Wo,{mode:b,onChange:y,compact:!0}),M&&p&&t.jsx("button",{onClick:()=>{p(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(vt,{size:14})}),w&&f&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:t.jsx(rs,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:t.jsx(No,{size:14})}),!s&&!M&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>k(e),type:"button",children:t.jsx(Mt,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(ti,{activeConv:e,clearToken:0,isCliTerminal:v,ideEntry:n,terminalRef:A,handleModalButton:N,handleRelaunch:j,handleSendChat:x,isSendingChat:l,sendFeedbackMessage:c,handleFocusAgent:I,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const va={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 Mg(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Kd(){const[e,s]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),l=e==="unix"?"unix":r;i.useEffect(()=>{s(Mg())},[]);const c=i.useCallback(()=>{navigator.clipboard.writeText(va[l].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[l]);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:c,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:va[l].prompt}),t.jsx("span",{className:"flex-1 break-all",children:va[l].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 Wd({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:Mt},{key:"chats",label:"Chats",icon:Jt}];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:o})=>{const l=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 ${l?"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:l?{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":l,children:[t.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${l?"text-accent-primary":"bg-transparent text-current"}`,style:l?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:t.jsx(o,{size:15})}),t.jsx("span",{children:a})]},n)})})})}function Xr({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function As({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 lr({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 Lg({conversation:e,onCancel:s,onConfirm:r}){const n=dt(e),a=Ss(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",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:s}),t.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"fade-in relative w-full sm:w-[min(92vw,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] border border-border-subtle bg-bg-primary shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),t.jsx("div",{className:"mt-1 text-[13px] leading-relaxed text-text-muted",children:"This only collapses the chat locally. You can restore it from Hidden tabs."})]}),t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary text-text-secondary transition-colors hover:bg-surface-primary hover:text-text-primary",onClick:s,"aria-label":"Cancel hide chat",children:t.jsx(vt,{size:16})})]}),t.jsx("div",{className:"px-4 py-4",children:t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[t.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),t.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),t.jsxs("div",{className:"flex items-center justify-end gap-2 border-t border-border-subtle bg-bg-secondary px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))]",children:[t.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function Jr({item:e,type:s,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:l}){var B;const c=s==="needs_attention"||s==="task_complete",d=s==="working",m=s==="earlier",u=s==="task_complete",{isReconnecting:h,isConnecting:g}=Ys(e.conversation),k=dt(e.conversation),f=Ss(e.conversation),p=Jc(e.conversation,{requiresAction:s==="needs_attention"}),b=c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",y=c?"bg-accent-primary shadow-glow":d?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":m?"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",x=m?"text-text-secondary":"text-text-primary",I=m?"text-text-muted":"text-text-secondary",N=m?"text-text-secondary opacity-80":"text-text-muted",j=m?"text-text-muted opacity-80":"text-text-muted",A=!d&&!u,M=!!e.conversation.daemonId&&typeof((B=e.conversation.settings)==null?void 0:B.meshCoordinatorFor)=="string"&&e.conversation.settings.meshCoordinatorFor.length>0,v="text-[color:var(--status-warning)]",w=R=>{if(!l)return;R.preventDefault(),R.stopPropagation();const T=l==null?void 0:l(e.conversation);Promise.resolve(T).catch(H=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",H)})};return t.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${b}`,children:t.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[c||d?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.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${y}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(k)}),a&&t.jsxs("button",{type:"button",className:"mobile-inbox-hide-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:R=>{R.preventDefault(),R.stopPropagation(),a()},"aria-label":`Hide ${k}`,title:"Hide conversation",children:[t.jsx(So,{size:11}),t.jsx("span",{children:"Hide"})]}),M&&o&&t.jsxs("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex min-h-7 items-center justify-center gap-1 rounded-full border border-border-subtle bg-bg-primary/70 px-2 text-[10px] font-semibold text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:R=>{R.preventDefault(),R.stopPropagation(),o(e.conversation)},"aria-label":`Open mesh graph for ${k}`,title:"Open live repo mesh graph",children:[t.jsx(rs,{size:11}),t.jsx("span",{children:"Graph"})]})]}),t.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:w,type:"button",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${x}`,children:k}),A&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${j}`,children:vc(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${I}`,children:[t.jsx("span",{className:"truncate",children:f}),t.jsx(zs,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${v} animate-pulse`,children:"Reconnecting…"})]}):g?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):p==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:v,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${N}`,children:e.preview})]}),c&&!u&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),u&&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"}),d&&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 fl({size:e=32}){return t.jsx("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}})})}function Rg({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:l,getAvatarText:c,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:h,onHideConversation:g,onOpenMeshGraph:k,onOpenNewSession:f,onOpenMachine:p,onOpenSettings:b,onSectionChange:y,wsStatus:x="connected",isStandalone:I=!1,onCollectChatDebugBundle:N}){const[j,A]=i.useState(null),M=x==="disconnected"||x==="reconnecting"||x==="offline"||x==="auth_failed",v=l.length>0,w=s.length>0||r.length>0||n.length>0||a.length>0,B=e==="machines"?"Machines":"Chats",R=I?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",T=I?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",H=i.useCallback(async S=>{const C=Us(S);if(!C)return;const W=Array.isArray(S.messages)?S.messages:[],_=$c({activeConv:S,visibleMessages:W,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:W.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),O=await m(C,"get_chat_debug_bundle",{...fs(S),delivery:"daemon_file",frontendSnapshot:_}),V=Cn(O),X=Fc(V),ye=await Oc(X);ye==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ot.showToast(Bc(V,{locatorCopyStatus:ye}),ye==="failed"?"warning":"success")},[d,m]),E=N||H,D=i.useCallback(()=>{j&&(g==null||g(j),A(null))},[j,g]);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 ${R}`,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:B}),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(En,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:b,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(Dn,{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] ${T}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?t.jsx(lr,{icon:t.jsx(fl,{}),title:x==="offline"?"Network offline":x==="auth_failed"?"Session expired":"Reconnecting",subtitle:x==="offline"?"Waiting for network…":x==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):l.length===0?t.jsx(lr,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:I?"Waiting for your daemon":"Connect your machines",subtitle:I?"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:!I&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(Kd,{})})}):t.jsx(As,{children:l.map((S,C)=>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] ${C>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(S.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:c(S.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:S.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:S.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[S.unread," new"]}):S.total>0?`${S.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:S.subtitle}),S.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[S.total," chat",S.total!==1?"s":"",S.unread>0?` · ${S.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},S.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Xr,{title:"Needs attention",className:"mb-0"}),t.jsx(As,{children:s.map((S,C)=>t.jsx("div",{className:C>0?"border-t border-border-subtle/70":"",children:t.jsx(Jr,{item:S,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:g?()=>A(S.conversation):void 0,onOpenMeshGraph:k,onCollectChatDebugBundle:E})},S.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Xr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(As,{children:r.map((S,C)=>t.jsx("div",{className:C>0?"border-t border-border-subtle/70":"",children:t.jsx(Jr,{item:S,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:g?()=>A(S.conversation):void 0,onOpenMeshGraph:k,onCollectChatDebugBundle:E})},S.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Xr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(As,{children:n.map((S,C)=>t.jsx("div",{className:C>0?"border-t border-border-subtle/70":"",children:t.jsx(Jr,{item:S,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:g?()=>A(S.conversation):void 0,onOpenMeshGraph:k,onCollectChatDebugBundle:E})},S.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(Xr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(As,{children:a.map((S,C)=>t.jsx("div",{className:C>0?"border-t border-border-subtle/70":"",children:t.jsx(Jr,{item:S,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:g?()=>A(S.conversation):void 0,onOpenMeshGraph:k,onCollectChatDebugBundle:E})},S.conversation.tabKey))}):w?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):M?t.jsx(lr,{icon:t.jsx(fl,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):v?t.jsx(lr,{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(Jt,{size:20})}),title:"No conversations yet",subtitle:ed,children:f&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:f,"aria-label":Wt,title:Wt,children:[t.jsxs("svg",{width:"16",height:"16",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("span",{children:Wt})]})}):t.jsx(lr,{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"&&o.length>0&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:t.jsx(As,{className:"mt-4 border-dashed bg-bg-secondary/20",children:t.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),t.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),t.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:h,children:"Restore all"})]})})})]}),e==="chats"&&f&&w&&t.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:f,"aria-label":Wt,title:Wt,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"})]})}),j&&t.jsx(Lg,{conversation:j,onCancel:()=>A(null),onConfirm:D}),t.jsx(Wd,{section:e,onSectionChange:y})]})}function _g(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 Hd(e){const s=[e.workspace||"Workspace unknown"],r=Ns(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=_g(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Gn({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:l="Use this folder",onClose:c,onNavigate:d,onConfirm:m}){const[u,h]=i.useState(r);i.useEffect(()=>{h(r)},[r]);const g=ug(r),k=u.trim();return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:t.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:t.jsx(vt,{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||d(g)},disabled:!g||a,children:[t.jsx(ko,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:u,onChange:f=>h(f.target.value),onKeyDown:f=>{f.key!=="Enter"||!k||a||(f.preventDefault(),d(k))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!k||a||d(k)},disabled:!k||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):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(f=>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:()=>d(f.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(ks,{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:f.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:f.path})]})]},f.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:c,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(k||r),disabled:!k&&!r||a,children:l})]})]})})}function si({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:l="Launch",busyLabel:c="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:h,showModelInput:g,modelValue:k,onModelChange:f,historyProviderNode:p,onConfirm:b,onCancel:y}){const x=n==null?void 0:n.find(I=>I.key===a);return t.jsx("div",{className:"fixed inset-0 z-[110] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:t.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":"Close launch confirmation",children:t.jsx(vt,{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&&o&&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:I=>o(I.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:d,children:n.map(I=>t.jsx("option",{value:I.key,children:I.label},I.key))}),(x==null?void 0:x.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:x.description})]}),p,r.map(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:I.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:I.value})]},`${I.label}:${I.value}`)),g&&f&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:k||"",onChange:I=>f(I.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:d})]}),m&&h&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:u||"",onChange:I=>h(I.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:d})]})]}),t.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:d,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:d,children:[t.jsx(Io,{size:14}),d?c:l]})]})]})})}function hl(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ws(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of s.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===s.defaultWorkspaceId?"⭐ ":""}${hl(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const l=(r==null?void 0:r.trim())||"",c=l?(s.workspaces||[]).find(d=>d.path===l):null;if(l&&!c&&o.push({key:`custom:${l}`,label:hl(l),description:l,workspaceId:null,workspacePath:l}),n){const d=`saved:${n}`;if(o.some(m=>m.key===d))return{options:o,selectedKey:d}}return c?{options:o,selectedKey:`saved:${c.id}`}:l?{options:o,selectedKey:`custom:${l}`}:{options:o,selectedKey:"__home__"}}function Pg(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Dg(e){return[Pg(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Eg(e){return e.lastLaunchedAt?$n(e.lastLaunchedAt):""}function Ud(e){return{metaText:Dg(e),updatedLabel:Eg(e)}}function wa(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function $g({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var st,mt,ht,yt;const l=Lr(),[c,d]=i.useState(!1),m=(((st=e.detectedIdes)==null?void 0:st.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),h=e.defaultWorkspaceId||null,[g,k]=i.useState(h||((mt=u[0])==null?void 0:mt.id)||""),[f,p]=i.useState(""),[b,y]=i.useState(""),[x,I]=i.useState([]),[N,j]=i.useState(!1),[A,M]=i.useState(""),[v,w]=i.useState(!1),[B,R]=i.useState(wa(m,s.length,r.length)),T=i.useRef(null),[H,E]=i.useState(null),D=i.useRef("__home__"),[S,C]=i.useState("__home__"),[W,_]=i.useState(""),[O,V]=i.useState(""),[X,ye]=i.useState(""),[he,ne]=i.useState([]),[pe,ke]=i.useState(()=>Nt().textQuery),[Se,G]=i.useState(()=>Nt().workspaceQuery),[be,fe]=i.useState(()=>Nt().modelQuery),[ve,P]=i.useState(()=>Nt().resumableOnly),[me,q]=i.useState(()=>Nt().sortMode),[de,ae]=i.useState(!1),[xe,ue]=i.useState(!1),ce=i.useRef(null),te=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&l(e.id,{minFreshMs:3e4}).catch(()=>{})},[l,e]);const $=g==="__custom__"?f.trim():((ht=u.find(Te=>Te.id===g))==null?void 0:ht.path)||"",J=g==="__custom__"&&!!$&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),oe=g!=="__custom__"&&((yt=u.find(Te=>Te.id===g))==null?void 0:yt.path)||"",ee=i.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),Ne=i.useCallback(async Te=>{j(!0),M("");try{const Ue=await a(Te);y(Ue.path),p(Ue.path),I(Ue.directories)}catch(Ue){M(Ue instanceof Error?Ue.message:"Could not load folder")}finally{j(!1)}},[a]),Ce=i.useCallback(()=>{var Ue;k("__custom__"),w(!0);const Te=zn(e.platform,Un(f.trim(),oe,ee,e.defaultWorkspacePath,(Ue=u.find(et=>et.id===h))==null?void 0:Ue.path,u.map(et=>et.path)));Ne(Te)},[f,h,Ne,ee,oe,e.platform,u]),we=i.useCallback(Te=>{if(Te!=null&&Te.workspaceId){k(Te.workspaceId),p("");return}if(Te!=null&&Te.workspacePath){k("__custom__"),p(Te.workspacePath);return}k(""),p("")},[]),K=i.useCallback(Te=>{if(k(Te),Te==="__custom__"){Ce();return}p("")},[Ce]),Ie=i.useCallback(Te=>{k("__custom__"),p(Te)},[]),Re=i.useCallback((Te,Ue)=>{T.current=Ue,D.current=Te.selectedWorkspaceKey||"__home__",C(Te.selectedWorkspaceKey||"__home__"),_(Te.initialArgs||""),V(Te.initialModel||""),ye(""),ne([]);const et=Te.providerType?`${e.id}:${Te.providerType}`:null;if(ix(te.current,et)){const ze=Nt();ke(ze.textQuery),G(ze.workspaceQuery),fe(ze.modelQuery),P(ze.resumableOnly),q(ze.sortMode)}te.current=et,E(Te),Te.providerType&&o&&(ae(!0),o(Te.providerType).then(ze=>ne(ze||[])).catch(ze=>console.warn("Failed to load saved sessions",ze)).finally(()=>ae(!1)))},[o,e.id]),Ke=i.useMemo(()=>td(he,{textQuery:pe,workspaceQuery:Se,modelQuery:be,resumableOnly:ve,sortMode:me}),[be,ve,he,me,pe,Se]);i.useEffect(()=>{X&&(Ke.some(Te=>Te.providerSessionId===X)||ye(""))},[Ke,X]);const He=i.useCallback(()=>{T.current&&(ue(!0),T.current().finally(()=>{T.current=null,ue(!1),E(null)}))},[]),qe=i.useCallback(()=>{T.current=null,E(null)},[]),Ye=i.useCallback(Te=>{D.current=Te,C(Te)},[]);return i.useEffect(()=>{var Te;ce.current!==e.id&&(ce.current=e.id,k(h||((Te=u[0])==null?void 0:Te.id)||"__custom__"),p(""),y(""),I([]),M(""),w(!1),ke(Nt().textQuery),G(Nt().workspaceQuery),fe(Nt().modelQuery),P(Nt().resumableOnly),q(Nt().sortMode),te.current=null,R(wa(m,s.length,r.length)))},[r.length,s.length,h,m,e.id,u]),i.useEffect(()=>{var Te;g!=="__custom__"&&(g&&u.some(Ue=>Ue.id===g)||k(h||((Te=u[0])==null?void 0:Te.id)||"__custom__"))},[h,g,u]),i.useEffect(()=>{B==="ide"&&m||B==="cli"&&s.length>0||B==="acp"&&r.length>0||R(wa(m,s.length,r.length))},[B,r.length,s.length,m]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:h,workspaceChoice:g,customWorkspacePath:f,browseCurrentPath:b,browseDirectories:x,browseBusy:N,browseError:A,browseDialogOpen:v,activeLauncherKind:B,launchConfirm:H,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:S,launchConfirmArgs:W,launchConfirmModel:O,launchConfirmResumeId:X,launchConfirmSavedSessions:he,launchConfirmTextFilter:pe,launchConfirmWorkspaceFilter:Se,launchConfirmModelFilter:be,launchConfirmResumableOnly:ve,launchConfirmSortMode:me,filteredLaunchConfirmSavedSessions:Ke,launchConfirmSessionsLoading:de,launchConfirmBusy:xe,resolvedWorkspacePath:$,canCreateMissingWorkspace:J,openBrowseDialog:Ce,loadBrowsePath:Ne,handleWorkspaceChoiceChange:K,chooseCustomWorkspacePath:Ie,setCustomWorkspacePath:p,setBrowseDialogOpen:w,setActiveLauncherKind:R,openLaunchConfirm:Re,handleConfirmLaunch:He,closeLaunchConfirm:qe,setWorkspaceSelectionFromOption:we,setLaunchConfirmWorkspaceKeyAndSync:Ye,setLaunchConfirmArgs:_,setLaunchConfirmModel:V,setLaunchConfirmResumeId:ye,setLaunchConfirmTextFilter:ke,setLaunchConfirmWorkspaceFilter:G,setLaunchConfirmModelFilter:fe,setLaunchConfirmResumableOnly:P,setLaunchConfirmSortMode:q}}function Bg({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:l,machineAction:c,isStandalone:d,section:m,showBottomNav:u,onBack:h,onSectionChange:g,onOpenConversation:k,onOpenRecent:f,onOpenMachineDetails:p,onMachineUpgrade:b,onLaunchDetectedIde:y,onAddWorkspace:x,onBrowseDirectory:I,onLaunchWorkspaceProvider:N,onListSavedSessions:j}){const A=S=>S==="ide"?"IDE":S==="cli"?"CLI":"ACP",M=r.slice(0,4),v=s.slice(0,3),w=$g({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:I,onListSavedSessions:j}),B=i.useMemo(()=>M.map(S=>{const{metaText:C,updatedLabel:W}=Ud(S);return{key:`recent-launch:${S.id}`,primary:S.label,secondary:C,updatedLabel:W,onClick:()=>{const{options:_,selectedKey:O}=ws({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspacePath:S.workspace});w.openLaunchConfirm({title:S.kind==="ide"?xs("restart-ide",S.label):S.providerSessionId?zo(S.label):xs("start-fresh",S.label),description:S.kind==="ide"?bs("restart-ide"):S.providerSessionId?Vo():bs("start-fresh"),confirmLabel:S.kind==="ide"?Vs("restart-ide"):S.providerSessionId?Tn(!0):Vs("start-fresh"),busyLabel:S.kind==="ide"?Gs("restart-ide"):S.providerSessionId?Ho(!0):Gs("start-fresh"),workspaceOptions:_,selectedWorkspaceKey:O,details:[{label:"Mode",value:A(S.kind)},...S.providerType?[{label:"Provider",value:S.providerType}]:[]]},async()=>{const V=_.find(X=>X.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(V),await f({...S,workspace:(V==null?void 0:V.workspacePath)??null})})}}}),[w,f,M]),R=i.useMemo(()=>v.map(S=>({key:`recent-chat:${S.conversation.tabKey}`,primary:dt(S.conversation),secondary:Vh(S.conversation,{timestampLabel:S.timestamp?vc(S.timestamp):null}),unread:S.unread,onClick:()=>k(S.conversation)})),[k,v]),T=w.showAllRecent?B:B.slice(0,4),H=B.length>0,E=R.length>0,D=d?"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 ${D} 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:h,type:"button","aria-label":"Back",children:t.jsx(ko,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:At(e,{fallbackId:e.id})}),t.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[E&&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:R.map(S=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${S.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:S.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:S.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:S.secondary})]},S.key))})]}),H&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:T.map(S=>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:S.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:S.primary}),S.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:S.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:S.secondary})]},S.key))}),B.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>w.setShowAllRecent(S=>!S),children:w.showAllRecent?"Show fewer":`Show ${B.length-4} more`})})]}),(w.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:w.workspaceChoice,onChange:S=>w.handleWorkspaceChoiceChange(S.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:w.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[w.workspaceRows.map(S=>t.jsxs("option",{value:S.id,children:[S.id===w.defaultWorkspaceId?"⭐ ":"",On(S.path,S.label)||S.path]},S.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),w.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(ks,{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:w.resolvedWorkspacePath||w.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:w.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:()=>{w.resolvedWorkspacePath&&x(w.resolvedWorkspacePath)},disabled:!w.resolvedWorkspacePath||w.browseBusy,children:"Save as workspace"})]})]}),w.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[w.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.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:()=>w.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.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:()=>w.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${w.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:()=>w.setActiveLauncherKind("acp"),children:"ACP"})]}),w.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:w.activeLauncherKind==="ide"?"Choose an IDE":w.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:w.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(S=>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:C,selectedKey:W}=ws({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${S.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:C,selectedWorkspaceKey:W,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:S.name}]},async()=>{const _=C.find(O=>O.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(_),y(S.type,{workspacePath:(_==null?void 0:_.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:S.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},S.type)):(w.activeLauncherKind==="cli"?n:a).map(S=>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 C=w.activeLauncherKind==="cli"?"cli":"acp",{options:W,selectedKey:_}=ws({machine:{workspaces:w.workspaceRows,defaultWorkspaceId:w.defaultWorkspaceId},currentWorkspaceId:w.workspaceChoice!=="__custom__"?w.workspaceChoice:null,currentWorkspacePath:w.resolvedWorkspacePath});w.openLaunchConfirm({title:`Launch ${S.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${C.toUpperCase()}`,workspaceOptions:W,selectedWorkspaceKey:_,details:[{label:"Mode",value:C.toUpperCase()},{label:"Provider",value:S.displayName}],showArgsInput:!0,showModelInput:C==="acp",initialArgs:"",initialModel:"",providerType:S.type},async()=>{const O=W.find(V=>V.key===w.launchConfirmWorkspaceKeyRef.current);w.setWorkspaceSelectionFromOption(O),N(C,S.type,{workspaceId:(O==null?void 0:O.workspaceId)??null,workspacePath:(O==null?void 0:O.workspacePath)??null,args:w.launchConfirmArgs,model:w.launchConfirmModel,resumeSessionId:w.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[S.icon?`${S.icon} `:"",S.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:w.resolvedWorkspacePath||"Use selected workspace"})]},S.type))})]}),c.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${c.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[c.message,w.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:()=>x(w.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:[o&&t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:b,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",l]}),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:p,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"})]})]})]})]}),w.browseDialogOpen&&t.jsx(Gn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:w.browseCurrentPath,directories:w.browseDirectories,busy:w.browseBusy,error:w.browseError,confirmLabel:"Use this folder",onClose:()=>w.setBrowseDialogOpen(!1),onNavigate:S=>{w.loadBrowsePath(S)},onConfirm:S=>{w.chooseCustomWorkspacePath(S),w.setBrowseDialogOpen(!1)}}),w.launchConfirm&&t.jsx(si,{title:w.launchConfirm.title,description:w.launchConfirm.description,details:w.launchConfirm.details,workspaceOptions:w.launchConfirm.workspaceOptions,selectedWorkspaceKey:w.launchConfirmWorkspaceKey,onWorkspaceChange:w.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:w.launchConfirm.providerType?Tn(!!w.launchConfirmResumeId):w.launchConfirm.confirmLabel,busyLabel:w.launchConfirm.providerType?void 0:w.launchConfirm.busyLabel,busy:w.launchConfirmBusy,showArgsInput:w.launchConfirm.showArgsInput,argsValue:w.launchConfirmArgs,onArgsChange:w.setLaunchConfirmArgs,showModelInput:w.launchConfirm.showModelInput,modelValue:w.launchConfirmModel,onModelChange:w.setLaunchConfirmModel,historyProviderNode:w.launchConfirm.providerType&&(w.launchConfirmSessionsLoading||w.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"}),w.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:Uo()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:w.launchConfirmTextFilter,onChange:S=>w.setLaunchConfirmTextFilter(S.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:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:w.launchConfirmWorkspaceFilter,onChange:S=>w.setLaunchConfirmWorkspaceFilter(S.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:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:w.launchConfirmModelFilter,onChange:S=>w.setLaunchConfirmModelFilter(S.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:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),t.jsxs("select",{value:w.launchConfirmSortMode,onChange:S=>w.setLaunchConfirmSortMode(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.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:w.launchConfirmResumableOnly,onChange:S=>w.setLaunchConfirmResumableOnly(S.target.checked),disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:w.launchConfirmResumeId,onChange:S=>w.setLaunchConfirmResumeId(S.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:w.launchConfirmBusy||w.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:dx()}),w.filteredLaunchConfirmSavedSessions.map(S=>t.jsxs("option",{value:S.providerSessionId,disabled:!S.canResume,children:[S.title||S.providerSessionId," ",S.canResume?"":"(workspace missing)"]},S.providerSessionId))]}),!w.launchConfirmSessionsLoading&&w.launchConfirmSavedSessions.length>0&&w.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),w.launchConfirmResumeId&&(()=>{const S=w.filteredLaunchConfirmSavedSessions.find(W=>W.providerSessionId===w.launchConfirmResumeId);if(!S)return null;const C=Hd(S);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:C.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:C.providerSessionId}),t.jsx("div",{className:"mt-1",children:C.metaLine}),C.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:C.updatedLabel}),C.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:C.preview})]})})()]}),onConfirm:w.handleConfirmLaunch,onCancel:w.closeLaunchConfirm}),u&&t.jsx(Wd,{section:m,onSectionChange:g})]})}function pn(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Og(e,s=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=s.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:pn(e)}function Fg(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 Kg(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:Ns(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 l;const a=Cr(n)?"cli":$s(n)?"acp":"ide",o=Ns(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((l=n.activeChat)==null?void 0:l.title)||(Cr(n)?n.cliName||n.type:$s(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:$s(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:n.lastMessageAt||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Wg(e,s){const r=new Map;for(const n of s){const a=Ts(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((h,g)=>g.timestamp-h.timestamp)[0]||null,l=(o==null?void 0:o.conversation)||null,c=to(n),d=a.filter(h=>h.unread||h.requiresAction).length,m=Fg(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:At(n,{fallbackId:n.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:l,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:l?Gh(l):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const o=n.latestTimestamp||n.fallbackActivityAt||0,l=a.latestTimestamp||a.fallbackActivityAt||0;return l!==o?l-o:n.label.localeCompare(a.label)})}function Hg(e){return e==="chat"}function Qr(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 Ug({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:l,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:g,onRequestedMobileSectionConsumed:k,setSelectedTabKey:f,setScreen:p,setSelectedMachineId:b,setSection:y,setMachineBackTarget:x,resetMachineAction:I}){const N=i.useRef(null),j=i.useCallback(A=>{if(!(A!=null&&A.sessionId))return;const M=jn(A,l),v=Math.max(Date.now(),vs(A),M.lastUpdated||0);Qr("mark_read:start",{tabKey:A.tabKey,sessionId:A.sessionId,displayPrimary:dt(A),inboxBucket:M.inboxBucket,unread:M.unread,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,activityAt:vs(A),readAt:v}),c(Ts(A)||A.routeId,"mark_session_seen",{sessionId:A.sessionId,providerSessionId:A.providerSessionId,seenAt:v,completionMarker:M.completionMarker}).then(w=>{Qr("mark_read:result",{tabKey:A.tabKey,sessionId:A.sessionId,result:w})}).catch(w=>{Qr("mark_read:error",{tabKey:A.tabKey,sessionId:A.sessionId,error:w instanceof Error?w.message:String(w)})})},[l,c]);return i.useEffect(()=>{var M;if(!n){Hg(o)&&p("inbox"),f(((M=e[0])==null?void 0:M.tabKey)||null),N.current=null;return}if(o!=="chat"){N.current=null;return}const A=`${n.tabKey}:${n.sessionId||""}`;N.current!==A&&(N.current=A,j(n))},[e,j,o,n,p,f]),i.useEffect(()=>{if(!d)return;const A=e.find(M=>M.tabKey===d);A&&(f(A.tabKey),p("chat"),m==null||m())},[e,m,d,p,f]),i.useEffect(()=>{if(!u)return;const A=s.find(M=>M.id===u);A&&(b(A.id),I(),y("machines"),x("inbox"),p("machine"),h==null||h())},[s,h,u,I,x,p,y,b]),i.useEffect(()=>{g&&(y(g),p("inbox"),k==null||k())},[k,g,p,y]),i.useEffect(()=>{const A=r.filter(M=>M.inboxBucket==="task_complete"||M.unread);A.length!==0&&Qr("inbox_state",{screen:o,selectedTabKey:a,items:A.map(M=>{const v=jn(M.conversation,l);return{liveState:v,tabKey:M.conversation.tabKey,sessionId:M.conversation.sessionId,displayPrimary:dt(M.conversation),serverBucket:v.inboxBucket,computedBucket:M.inboxBucket,serverUnread:v.unread,computedUnread:M.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,activityAt:vs(M.conversation)}})})},[r,l,o,a]),{markConversationRead:j}}function zg(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function xl(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Vg(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Gg({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[l,c]=i.useState(""),[d,m]=i.useState(null),u=i.useCallback(()=>{o("idle"),c(""),m(null)},[]),h=i.useCallback(async(x,I,N)=>{var j;try{o("loading"),c(`Launching ${I}…`);const A={ideType:I,enableCdp:!0};(j=N==null?void 0:N.workspacePath)!=null&&j.trim()&&(A.workspace=N.workspacePath.trim()),await e(x,"launch_ide",A),o("done"),c(`${I} launch requested`)}catch(A){o("error"),c(A instanceof Error?A.message:"Launch IDE failed"),console.error("Launch IDE failed",A)}},[e]),g=i.useCallback(async(x,I,N)=>{if(I.trim())try{o("loading"),c(N!=null&&N.createIfMissing?"Creating folder…":"Saving workspace…");const j=await e(x,"workspace_add",{path:I.trim(),createIfMissing:(N==null?void 0:N.createIfMissing)===!0});if(j!=null&&j.success){o("done"),c(N!=null&&N.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),c((j==null?void 0:j.error)||"Could not save workspace")}catch(j){o("error"),c(j instanceof Error?j.message:"Could not save workspace")}},[e]),k=i.useCallback(async x=>{var I,N,j,A,M,v;try{o("loading"),c("Starting daemon upgrade…");const w=await e(x,"daemon_upgrade",{});if((I=w==null?void 0:w.result)!=null&&I.alreadyLatest){o("done"),c(`Already on v${((N=w==null?void 0:w.result)==null?void 0:N.version)||"latest"}.`);return}if((j=w==null?void 0:w.result)!=null&&j.upgraded||(A=w==null?void 0:w.result)!=null&&A.success){o("done"),c(`Upgrade to v${((M=w==null?void 0:w.result)==null?void 0:M.version)||"latest"} started. Daemon is restarting…`);return}o("error"),c(((v=w==null?void 0:w.result)==null?void 0:v.error)||"Upgrade failed")}catch(w){o("error"),c(w instanceof Error?w.message:"Upgrade failed")}},[e]),f=i.useCallback(async(x,I,N,j)=>{var v,w,B;const A=Date.now(),M={machineId:x,kind:I,providerType:N,workspaceId:(j==null?void 0:j.workspaceId)||null,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:A};try{o("loading"),c(`Launching ${N}…`),m(M);const R={cliType:N};(v=j==null?void 0:j.workspacePath)!=null&&v.trim()?R.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(R.workspaceId=j.workspaceId),j!=null&&j.resumeSessionId&&(R.resumeSessionId=j.resumeSessionId),(w=j==null?void 0:j.args)!=null&&w.trim()&&(R.cliArgs=j.args.trim().split(/\s+/).filter(Boolean)),(B=j==null?void 0:j.model)!=null&&B.trim()&&(R.initialModel=j.model.trim());const T=await e(x,"launch_cli",R),H=(T==null?void 0:T.result)||T,E=(H==null?void 0:H.sessionId)||(H==null?void 0:H.id);if(T!=null&&T.success&&E){m(null),o("done"),c(`${N} launched`),s(zt(E));return}if(T!=null&&T.success){o("loading"),c(`${N} launch requested — waiting for session…`);return}m(null),o("error"),c((T==null?void 0:T.error)||(H==null?void 0:H.error)||`Could not launch ${I.toUpperCase()} workspace`)}catch(R){if(Vg(R)){o("loading"),c(`${N} launch requested — waiting for session…`);return}m(null),o("error"),c(R instanceof Error?R.message:`Could not launch ${I.toUpperCase()} workspace`)}},[s,e]),p=i.useCallback(async(x,I)=>{try{const N=await e(x,"list_saved_sessions",{providerType:I,kind:"cli",limit:30}),j=(N==null?void 0:N.result)??N;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(N){return console.error("Failed to list saved sessions on mobile:",N),[]}},[e]),b=i.useCallback(async(x,I)=>Vn(e,x,I),[e]);i.useEffect(()=>{if(!d)return;const x=xl(d.workspacePath),I=r.find(j=>{var R,T,H,E;if(!j||j.type==="adhdev-daemon"||zg(j.daemonId||j.id)!==d.machineId||(j.transport==="acp"?"acp":j.transport==="pty"?"cli":null)!==d.kind||String(j.agentType||j.type||"")!==d.providerType)return!1;const w=String(j.providerSessionId||"");if(d.resumeSessionId&&w)return w===d.resumeSessionId;if(x){const D=xl(j.workspace||j.runtimeWorkspaceLabel);return D?D===x:!1}return Number(j.lastUpdated||j._lastUpdate||j.timestamp||((E=(H=(T=(R=j.activeChat)==null?void 0:R.messages)==null?void 0:T.at)==null?void 0:H.call(T,-1))==null?void 0:E.timestamp)||0)>=d.startedAt-5e3});if(!I)return;const N=Bd({entrySessionId:I.sessionId,entryInstanceId:I.instanceId,entryRouteId:I.id,conversations:n});N&&(m(null),o("done"),c(`${d.providerType} launched`),s(zt(N)))},[n,r,s,d]),i.useEffect(()=>{if(!d)return;const x=window.setTimeout(()=>{m(I=>!I||I.startedAt!==d.startedAt?I:(o("error"),c("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(x)},[d]);const y=i.useCallback(async(x,I)=>{if(I.kind==="ide"&&I.providerType){await h(x,I.providerType,{workspacePath:I.workspace||null});return}(I.kind==="cli"||I.kind==="acp")&&I.providerType&&await f(x,I.kind,I.providerType,{workspacePath:I.workspace||null,resumeSessionId:I.providerSessionId||null})},[h,f]);return{machineAction:{state:a,message:l},resetMachineAction:u,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:k,handleLaunchWorkspaceProvider:f,handleListSavedSessions:p,handleBrowseDirectory:b,handleOpenRecent:y}}function qg({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:l,setSelectedMachineId:c,setSection:d,setMachineBackTarget:m}){const u=i.useCallback(y=>{o(y.tabKey),l("chat"),n(y)},[n,l,o]),h=i.useCallback(y=>{const x=e.find(I=>I.routeId===y.routeId&&I.streamSource==="native");x&&(o(x.tabKey),l("chat"),n(x))},[e,n,l,o]),g=i.useCallback(()=>{n(s),l("inbox")},[n,s,l]),k=i.useCallback((y,x="inbox")=>{c(y),a(),d("machines"),m(x),l("machine")},[a,m,l,d,c]),f=i.useCallback(y=>{const x=Ts(y);x&&k(x,"chat")},[k]),p=i.useCallback(()=>{a(),l(r)},[r,a,l]),b=i.useCallback(y=>{d(y),l("inbox")},[l,d]);return{openConversation:u,openNativeConversation:h,backFromConversation:g,openMachine:k,openConversationMachine:f,backFromMachine:p,changeMachineSection:b}}function Cs(e,s){return e.category!==s?!1:s==="ide"?!0:e.enabled===!0}function Yg(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Xg({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:g,onRequestedMobileSectionConsumed:k,onOpenHistory:f,onOpenRemote:p,onStopCli:b,wsStatus:y,isConnected:x,onShowAllHiddenConversations:I,onHideConversation:N,onOpenMeshGraph:j,onOpenNewSession:A,liveSessionInboxState:M,setCliViewModeOverrides:v}){const[w,B]=i.useState(()=>{var ee;return((ee=e[0])==null?void 0:ee.tabKey)||null}),[R,T]=i.useState(()=>e[0]?"chat":"inbox"),[H,E]=i.useState("chats"),[D,S]=i.useState(null),[C,W]=i.useState("inbox"),_=i.useRef([]),O=ls(),V="0.9.81",X=i.useMemo(()=>e.find(ee=>ee.tabKey===w)||e[0]||null,[e,w]),ye=i.useMemo(()=>X?r.find(ee=>ee.id===X.routeId):void 0,[r,X]),he=i.useMemo(()=>!X||tt(X)||!nt(X)?null:Xs(X),[X]),ne=i.useMemo(()=>r.filter(ee=>ee.type==="adhdev-daemon").sort(_o),[r]),pe=i.useMemo(()=>ne.find(ee=>ee.id===D)||null,[ne,D]),ke=Kn({sendDaemonCommand:a,activeConv:X||void 0,setActionLogs:o,isStandalone:l}),Se=Gg({sendDaemonCommand:a,navigate:O,ides:r,conversations:e}),G=i.useMemo(()=>e.map(ee=>{const Ne=R==="chat"&&(X==null?void 0:X.tabKey)===ee.tabKey,Ce=Bn(ee,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ne}),we=vs(ee),K=Xc(ee);return{conversation:ee,timestamp:we,preview:K,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[e,M,R,X]),{markConversationRead:be}=Ug({conversations:e,machineEntries:ne,items:G,selectedConversation:X,selectedTabKey:w,screen:R,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:g,onRequestedMobileSectionConsumed:k,setSelectedTabKey:B,setScreen:T,setSelectedMachineId:S,setSection:E,setMachineBackTarget:W,resetMachineAction:Se.resetMachineAction}),fe=qg({conversations:e,selectedConversation:X,machineBackTarget:C,markConversationRead:be,resetMachineAction:Se.resetMachineAction,setSelectedTabKey:B,setScreen:T,setSelectedMachineId:S,setSection:E,setMachineBackTarget:W}),ve=i.useMemo(()=>pn(G.filter(ee=>ee.requiresAction)),[G]),P=i.useMemo(()=>pn(G.filter(ee=>ee.unread&&!ee.requiresAction)),[G]),me=i.useMemo(()=>Og(G.filter(ee=>!ee.unread&&!ee.requiresAction&&ee.isWorking),_.current),[G]);i.useEffect(()=>{_.current=me.map(ee=>ee.conversation.tabKey)},[me]);const q=i.useMemo(()=>pn(G.filter(ee=>!ee.unread&&!ee.requiresAction&&!ee.isWorking)),[G]),de=i.useMemo(()=>pe?G.filter(ee=>Ts(ee.conversation)===pe.id):[],[G,pe]),ae=i.useMemo(()=>Kg(pe,r),[r,pe]),xe=(pe==null?void 0:pe.version)||null,ue=!!pe&&!!xe&&!0&&xe!==V,ce=i.useMemo(()=>(pe==null?void 0:pe.availableProviders)||[],[pe]),te=i.useMemo(()=>ce.filter(ee=>Cs(ee,"cli")).map(ee=>({type:ee.type,displayName:ee.displayName||ee.type,icon:ee.icon})),[ce]),$=i.useMemo(()=>ce.filter(ee=>Cs(ee,"acp")).map(ee=>({type:ee.type,displayName:ee.displayName||ee.type,icon:ee.icon})),[ce]),J=i.useMemo(()=>Wg(ne,G),[G,ne]),oe=i.useCallback(async ee=>{pe&&await Se.handleOpenRecent(pe.id,ee)},[Se,pe]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:R==="chat"&&X?t.jsx(Ag,{selectedConversation:X,isAcp:tt(X),isStandalone:l,selectedIdeEntry:ye,actionLogs:n,userName:c,isSendingChat:ke.isSendingChat,sendFeedbackMessage:ke.sendFeedbackMessage,isFocusingAgent:ke.isFocusingAgent,handleModalButton:ke.handleModalButton,handleRelaunch:ke.handleRelaunch,onBack:fe.backFromConversation,onOpenNativeConversation:fe.openNativeConversation,onOpenMachine:fe.openConversationMachine,onOpenHistory:f,onOpenRemote:p,onOpenMeshGraph:j,onStopCli:b,cliViewMode:he,onSetCliViewMode:async ee=>{await Nd({conversation:X,mode:ee,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:v})},handleSendChat:ke.handleSendChat,handleFocusAgent:ke.handleFocusAgent}):R==="machine"&&pe?t.jsx(Bg,{selectedMachineEntry:pe,selectedMachineConversations:de,selectedMachineRecentLaunches:ae,cliProviders:te,acpProviders:$,selectedMachineNeedsUpgrade:ue,appVersion:V,machineAction:Se.machineAction,isStandalone:l,section:H,showBottomNav:C==="inbox",onBack:fe.backFromMachine,onSectionChange:fe.changeMachineSection,onOpenConversation:fe.openConversation,onOpenRecent:oe,onOpenMachineDetails:()=>O(`/machines/${pe.id}`),onMachineUpgrade:()=>Se.handleMachineUpgrade(pe.id),onLaunchDetectedIde:(ee,Ne)=>Se.handleLaunchDetectedIde(pe.id,ee,Ne),onAddWorkspace:(ee,Ne)=>Se.handleAddWorkspace(pe.id,ee,Ne),onBrowseDirectory:ee=>Se.handleBrowseDirectory(pe.id,ee),onLaunchWorkspaceProvider:(ee,Ne,Ce)=>Se.handleLaunchWorkspaceProvider(pe.id,ee,Ne,Ce),onListSavedSessions:ee=>Se.handleListSavedSessions(pe.id,ee)}):t.jsx(Rg,{section:H,attentionItems:ve,unreadItems:P,workingItems:me,completedItems:q,hiddenConversations:s,machineCards:J,getAvatarText:Yg,actionLogs:n,sendDaemonCommand:a,onOpenConversation:fe.openConversation,onShowAllHidden:I,onHideConversation:N,onOpenMeshGraph:j,onOpenNewSession:A,onOpenMachine:fe.openMachine,onOpenSettings:()=>O("/settings"),onSectionChange:E,wsStatus:y,isConnected:x,isStandalone:l})})}function ja(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Jg({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const l=i.useRef(0),[c,d]=i.useState(!1),[m,u]=i.useState(null),h=i.useCallback(()=>{l.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const g=i.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(l.current+=1,d(!0))},[]),k=i.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!ja(s,r)){u("merge");return}const y=b.currentTarget.getBoundingClientRect(),x=b.clientX-y.left,I=y.width/3;x<I?u("split-left"):x>I*2?u("split-right"):u("merge")},[s,r]),f=i.useCallback(()=>{l.current-=1,!(l.current>0)&&(l.current=0,d(!1),u(null))},[]),p=i.useCallback(b=>{l.current=0,d(!1);const y=b.dataTransfer.getData("text/tab-key"),x=y?e.some(N=>N.tabKey===y):!1,I=m;if(u(null),o(),!!y){if(b.preventDefault(),I==="split-left"&&ja(s,r)){r==null||r(y,"split-left");return}if(I==="split-right"&&ja(s,r)){r==null||r(y,"split-right");return}if(x){a(y);return}n==null||n(y)}},[e,m,s,r,n,a,o]);return{dragOver:c,dropAction:m,resetDragState:h,handleDragEnter:g,handleDragOver:k,handleDragLeave:f,handleDrop:p}}function Qg(e,s){const r=new Set(s.map(o=>o.tabKey)),n=e.filter(o=>r.has(o)),a=s.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...a]}function Zg({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,l]=i.useState(s??null),[c,d]=i.useState(r??[]),[m,u]=i.useState(null),h=i.useRef(null),g=i.useRef(null),k=i.useRef(n),f=i.useRef(a);i.useEffect(()=>{k.current=n},[n]),i.useEffect(()=>{f.current=a},[a]),i.useEffect(()=>{s&&s!==o&&l(s)},[s,o]),i.useEffect(()=>{d(M=>{const v=Qg(M,e);return v.length===M.length&&v.every((w,B)=>w===M[B])?M:v})},[e]);const p=i.useMemo(()=>{const M=m??c;if(M.length===0)return e;const v=new Map(M.map((w,B)=>[w,B]));return[...e].sort((w,B)=>{const R=v.get(w.tabKey)??999,T=v.get(B.tabKey)??999;return R-T})},[e,m,c]);i.useEffect(()=>{var v,w;if(p.length===0){o!==null&&(l(null),(v=k.current)==null||v.call(k,null));return}if(o&&p.some(B=>B.tabKey===o))return;const M=p[0].tabKey;M!==o&&(l(M),(w=k.current)==null||w.call(k,M))},[p,o]);const b=i.useMemo(()=>p.find(M=>M.tabKey===o),[p,o]),y=i.useCallback(M=>{var v;l(M),(v=k.current)==null||v.call(k,M)},[]),x=i.useCallback((M,v,w)=>{d(B=>{var E;const R=B.filter(D=>D!==M),T=R.indexOf(v);if(T<0)return B;const H=w==="left"?T:T+1;return R.splice(H,0,M),(E=f.current)==null||E.call(f,R),R}),u(null)},[]),I=i.useCallback((M,v,w)=>{const R=(c.length>0?c:e.map(E=>E.tabKey)).filter(E=>E!==M),T=R.indexOf(v);if(T<0)return;const H=w==="left"?T:T+1;R.splice(H,0,M),h.current=R,u(R)},[c,e]),N=i.useCallback(()=>{var v;const M=h.current;M&&(d(M),(v=f.current)==null||v.call(f,M))},[]),j=i.useCallback(()=>{h.current=null,u(null)},[]),A=i.useCallback(M=>{d(v=>{var B;const w=v.filter(R=>R!==M);return w.push(M),(B=f.current)==null||B.call(f,w),w})},[]);return{activeTabId:o,activeConv:b,sortedConversations:p,previewOrderRef:h,draggingTabRef:g,selectTab:y,handleTabReorder:x,updatePreviewOrder:I,commitPreviewOrder:N,clearPreviewOrder:j,moveTabToEnd:A,setDraggingTabKey:M=>{g.current=M}}}function ey({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 ri({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){if(a)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const l=!r&&!n,c=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?ed:r?"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.";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:d}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),c&&t.jsx("div",{className:"flex items-center justify-center mb-4",children:t.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Wt,"aria-label":Wt,children:[t.jsx(uc,{size:14}),t.jsx("span",{children:Wt})]})}),l&&t.jsx(Kd,{}),l&&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 zd="adhdev-tab-shortcuts";function Vd(){try{return JSON.parse(localStorage.getItem(zd)||"{}")}catch{return{}}}function Gd({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,l]=i.useState(()=>Vd()),[c,d]=i.useState(null),m=i.useCallback(h=>{const g=[];return h.metaKey&&g.push(a?"⌘":"Meta"),h.ctrlKey&&g.push("Ctrl"),h.altKey&&g.push(a?"⌥":"Alt"),h.shiftKey&&g.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(g.push(h.key.length===1?h.key.toUpperCase():h.key),g.join("+"))},[a]),u=i.useCallback(h=>{l(h);try{localStorage.setItem(zd,JSON.stringify(h))}catch{}},[]);return i.useEffect(()=>{if(!e||!c)return;const h=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){d(null);return}const k=m(g);if(!k)return;const f={...o};for(const[p,b]of Object.entries(f))b===k&&delete f[p];f[c]=k,u(f),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,c,o,u,m]),i.useEffect(()=>{if(!e)return;const h=g=>{if(!(!g.ctrlKey&&!g.metaKey&&!g.altKey)){for(const[k,f]of Object.entries(o))if(s.includes(k)&&m(g)===f){g.preventDefault(),r(),n(k);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,o,s,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const ka=e=>{e.preventDefault()},ty=i.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:l,draggingTabRef:c,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:h,onReorderTab:g,onCommitPreviewOrder:k,onClearPreviewOrder:f,onDragStateReset:p,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:x,longPressTimer:I,isGroupActive:N}){const j=Ys(s),A=j.isGenerating?"agent-tab-generating":j.isWaiting?"agent-tab-waiting":"",M=j.isReconnecting,v=i.useCallback(C=>{c.current=s.tabKey,b(s.tabKey),C.dataTransfer.setData("text/tab-key",s.tabKey),C.dataTransfer.effectAllowed="move"},[s.tabKey,c,b]),w=i.useCallback(()=>{c.current=null,b(null),k(),f(),p()},[c,b,k,f,p]),B=i.useCallback(C=>{const W=c.current;if(!(!W||W===s.tabKey)&&C.dataTransfer.types.includes("text/tab-key")){C.preventDefault(),C.stopPropagation();const _=C.currentTarget.getBoundingClientRect(),O=C.clientX<_.left+_.width/2?"left":"right";h(W,s.tabKey,O)}},[s.tabKey,c,h]),R=i.useCallback(C=>{C.preventDefault(),C.stopPropagation();const W=C.dataTransfer.getData("text/tab-key");if(W&&W!==s.tabKey){const _=C.currentTarget.getBoundingClientRect(),O=C.clientX<_.left+_.width/2?"left":"right";l.includes(W)?g(W,s.tabKey,O):y&&y(W)}f()},[s.tabKey,l,g,y,f]),T=i.useCallback(C=>{C.stopPropagation(),d(),m(s.tabKey),u(s)},[s,u,d,m]),H=i.useCallback(C=>{C.preventDefault(),x(C.clientX,C.clientY,s.tabKey)},[s.tabKey,x]),E=i.useCallback(C=>{const W=C.touches[0];I.current=setTimeout(()=>{x(W.clientX,W.clientY,s.tabKey)},600)},[s.tabKey,I,x]),D=i.useCallback(()=>{I.current&&clearTimeout(I.current)},[I]),S=["adhdev-dockview-tab",A,r&&"is-active",N&&"is-group-active",M&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:S,draggable:!0,onDragStart:v,onDragEnd:w,onDragOver:B,onDrop:R,onClick:T,onContextMenu:H,onTouchStart:E,onTouchEnd:D,onTouchMove:D,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:j.isGenerating?t.jsx("div",{className:"tab-spinner"}):j.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):M?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):j.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:dt(s),children:dt(s)}),t.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[M?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:hs(s)}):j.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[hs(s),t.jsx("span",{className:"connecting-dots"})]}):t.jsx("span",{className:"truncate",children:hs(s)}),t.jsx(zs,{git:s.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(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 sy({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:g,onDragTabKeyChange:k,onReceiveTab:f,onHideTab:p,isGroupActive:b,allowTabShortcuts:y=!0}){const[x,I]=i.useState(null),N=i.useRef(null),j=i.useRef(null),A=i.useMemo(()=>e.map(H=>H.tabKey),[e]);Ar("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(x==null?void 0:x.tabKey)||null});const{isMac:M,tabShortcuts:v,shortcutListening:w,setShortcutListening:B,saveShortcuts:R}=Gd({enabled:y,sortedTabKeys:e.map(H=>H.tabKey),onFocus:o,onSelectTab:l});i.useEffect(()=>{if(!x)return;const H=E=>{const D=document.querySelector("[data-pane-context-menu]");D&&D.contains(E.target)||I(null)};return window.addEventListener("mousedown",H,!0),()=>window.removeEventListener("mousedown",H,!0)},[x]),i.useEffect(()=>{const H=j.current;if(!H)return;const E=D=>{Math.abs(D.deltaY)<=Math.abs(D.deltaX)||(D.preventDefault(),H.scrollLeft+=D.deltaY)};return H.addEventListener("wheel",E,{passive:!1}),()=>H.removeEventListener("wheel",E)},[]);const T=i.useCallback((H,E,D)=>{I({x:H,y:E,tabKey:D})},[]);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:j,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(H=>t.jsx(ty,{conv:H,isActive:s===H.tabKey,isDraggedTab:a.current===H.tabKey,isTaskCompleteUnread:n.has(H.tabKey),shortcut:y?v[H.tabKey]:void 0,conversationKeys:A,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:g,onDragTabKeyChange:k,onReceiveTab:f,onOpenContextMenu:T,longPressTimer:N,isGroupActive:b},H.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),x&&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:x.x,top:x.y},children:[y&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:ka,onClick:H=>{H.stopPropagation(),B(x.tabKey),I(null)},children:["⌨ ",v[x.tabKey]?`Change shortcut (${v[x.tabKey]})`:"Set shortcut"]}),v[x.tabKey]&&t.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:ka,onClick:()=>{const H={...v};delete H[x.tabKey],R(H),I(null)},children:"✕ Remove shortcut"})]}),p&&t.jsxs(t.Fragment,{children:[y&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:ka,onClick:()=>{p(x.tabKey),I(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&w&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:()=>B(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:H=>H.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. ",M?"⌘+1":"Ctrl+1",", ",M?"⌥+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 ry({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,userName:d,groupIndex:m,onFocus:u,isSplitMode:h,numGroups:g,onMoveTab:k,onReceiveTab:f,style:p,onActiveTabChange:b,initialActiveTabId:y,initialTabOrder:x,onTabOrderChange:I,onHideTab:N,isFocused:j,allowTabShortcuts:A=!0,onOpenNewSession:M,liveSessionInboxState:v}){const{sendCommand:w}=wt(),B=i.useRef(null),{activeTabId:R,activeConv:T,sortedConversations:H,draggingTabRef:E,selectTab:D,handleTabReorder:S,updatePreviewOrder:C,commitPreviewOrder:W,clearPreviewOrder:_,moveTabToEnd:O,setDraggingTabKey:V}=Zg({conversations:e,initialActiveTabId:y,initialTabOrder:x,onActiveTabChange:b,onTabOrderChange:I}),X=Kn({sendDaemonCommand:a,activeConv:T,setActionLogs:o,isStandalone:l}),{dragOver:ye,dropAction:he,resetDragState:ne,handleDragEnter:pe,handleDragOver:ke,handleDragLeave:Se,handleDrop:G}=Jg({conversations:e,numGroups:g,onMoveTab:k,onReceiveTab:f,onOwnTabDrop:O,onClearPreviewOrder:_}),be=T&&!tt(T)&&Xs(T)==="terminal",fe=i.useMemo(()=>T?s.find(q=>q.id===T.routeId):void 0,[s,T]),ve=i.useMemo(()=>T?n.filter(q=>q.routeId===T.tabKey):[],[n,T]),P=i.useMemo(()=>new Set(H.filter(q=>Pp(q,v,{isOpenConversation:q.tabKey===R})).map(q=>q.tabKey)),[R,v,H]);Ar("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:R,dragOver:ye});const me=i.useCallback(q=>{q.streamSource==="agent-stream"&&q.agentType&&w(q.routeId,Ec(),{agentType:q.agentType,...q.sessionId&&{targetSessionId:q.sessionId}}).catch(()=>{})},[w]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:ye?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(sy,{conversations:H,activeTabId:R,groupIndex:m,numGroups:g,unreadTabKeys:P,draggingTabRef:E,onFocus:u,onSelectTab:D,onConversationActivated:me,onPreviewReorder:C,onReorderTab:S,onCommitPreviewOrder:W,onClearPreviewOrder:_,onDragStateReset:ne,onDragTabKeyChange:V,onMoveTab:k,onReceiveTab:f,onHideTab:N,isGroupActive:j??!1,allowTabShortcuts:A}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:pe,onDragOver:ke,onDragLeave:Se,onDrop:G,children:[ye&&t.jsx(ey,{dropAction:he,canSplit:!!(g<4&&k)}),T?t.jsx(ti,{activeConv:T,clearToken:r[T.tabKey]||0,isCliTerminal:!!be,ideEntry:fe,terminalRef:B,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,handleSendChat:X.handleSendChat,isSendingChat:X.isSendingChat,sendFeedbackMessage:X.sendFeedbackMessage,handleFocusAgent:X.handleFocusAgent,isFocusingAgent:X.isFocusingAgent,actionLogs:ve,userName:d,isInputActive:!h||!!j}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(ri,{conversationsCount:e.length,isSplitMode:h,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:M})})]})]})}function ny({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:g,focusedGroup:k,focusGroup:f,moveTabToGroup:p,splitTabRelative:b,closeGroup:y,handleResizeStart:x,groupActiveTabIds:I,setGroupActiveTab:N,groupTabOrders:j,setGroupTabOrder:A,toggleHiddenTab:M,onOpenNewSession:v,allowTabShortcuts:w=!0,liveSessionInboxState:B}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((R,T)=>{const H=s&&n.length===r?`${n[T]}%`:void 0;return t.jsxs(kt.Fragment,{children:[s&&T>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:E=>x(T-1,E),onDoubleClick:()=>y(T),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(ry,{style:s?{flexBasis:H??`${100/r}%`,flexGrow:H?0:1,flexShrink:H?0:1}:void 0,conversations:R,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:g,groupIndex:T,isFocused:s&&k===T,onFocus:()=>f(T),isSplitMode:s,numGroups:r,onMoveTab:(E,D)=>{D==="left"&&T>0?p(E,T-1):D==="right"&&T<r-1?p(E,T+1):D==="split-left"&&r<4?b(E,T,"left"):D==="split-right"&&r<4&&b(E,T,"right")},onReceiveTab:E=>p(E,T),onActiveTabChange:E=>N(T,E),initialActiveTabId:I[T],initialTabOrder:j[T],onTabOrderChange:E=>A(T,E),onHideTab:M,onOpenNewSession:v,allowTabShortcuts:w,liveSessionInboxState:B})]},T)})})}function qd({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,o]=i.useState(null),[l,c]=i.useState(null);i.useEffect(()=>e?ut.onScreenshot("ide-page",(u,h)=>{if(u!==e)return;const g=new FileReader;g.onload=()=>o(g.result),g.readAsDataURL(h)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=ut.onStatus)==null?void 0:u.call(ut,(h,g)=>{h===e&&g!=null&&g.screenshotUsage&&c(g.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,s]),i.useEffect(()=>{const m=e?ut.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&s?m.startScreenshots(s):m.stopScreenshots(s),()=>{m.stopScreenshots(s)}},[n,r,s,e]);const d=i.useCallback(async(m,u)=>{const h=e?ut.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,u,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:l,handleRemoteAction:d}}const Yd="adhdev-dashboard-action-shortcuts",ay=1200,oy=[["toggleHiddenTabs","G H"],["openNewSession","N"],["setActiveTabShortcut","G S"],["selectPreviousGroupTab","G K"],["selectPreviousGroupTab","T ←"],["selectPreviousGroupTab","⌥+["],["selectPreviousGroupTab","Ctrl+Alt+["],["selectNextGroupTab","G J"],["selectNextGroupTab","T →"],["selectNextGroupTab","⌥+]"],["selectNextGroupTab","Ctrl+Alt+]"],["splitActiveTabDown","S ↓"],["splitActiveTabDown","⌘+⌥+-"],["splitActiveTabDown","Ctrl+Alt+-"],["splitActiveTabRight","S →"],["splitActiveTabRight","⌘+⌥+\\"],["splitActiveTabRight","⌘+⌥+="],["splitActiveTabRight","Ctrl+Alt+\\"],["focusLeftPane","F ←"],["focusLeftPane","⌘+⌥+←"],["focusLeftPane","⌘+⌥+["],["focusLeftPane","Ctrl+Alt+←"],["focusRightPane","F →"],["focusRightPane","⌘+⌥+→"],["focusRightPane","⌘+⌥+]"],["focusRightPane","Ctrl+Alt+→"],["focusUpPane","F ↑"],["focusUpPane","⌘+⌥+U"],["focusUpPane","Ctrl+Alt+↑"],["focusDownPane","F ↓"],["focusDownPane","⌘+⌥+J"],["focusDownPane","Ctrl+Alt+↓"],["moveActiveTabToLeftPane","M ←"],["moveActiveTabToLeftPane","⌘+⌥+⇧+←"],["moveActiveTabToLeftPane","⌘+⌥+,"],["moveActiveTabToLeftPane","Ctrl+Alt+Shift+←"],["moveActiveTabToRightPane","M →"],["moveActiveTabToRightPane","⌘+⌥+⇧+→"],["moveActiveTabToRightPane","⌘+⌥+."],["moveActiveTabToRightPane","Ctrl+Alt+Shift+→"],["moveActiveTabToUpPane","M ↑"],["moveActiveTabToUpPane","⌘+⌥+I"],["moveActiveTabToUpPane","Ctrl+Alt+Shift+↑"],["moveActiveTabToDownPane","M ↓"],["moveActiveTabToDownPane","⌘+⌥+K"],["moveActiveTabToDownPane","Ctrl+Alt+Shift+↓"],["triggerPrimaryApprovalAction","⌥+A"],["triggerSecondaryApprovalAction","⌥+D"],["toggleCliView","T"]];function iy(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function it(e,s){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return s?"⌘+⇧+Enter":"Ctrl+Shift+Enter";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+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return s?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";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+Shift+←";case"selectNextGroupTab":return s?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function Xd(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:it("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:it("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:it("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:it("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:it("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:it("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:it("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:it("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:it("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:it("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:it("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:it("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:it("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:it("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:it("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:it("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:it("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:it("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:it("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:it("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:it("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:it("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:it("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:it("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:it("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:it("toggleCliView",e)}]}function ho(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function _n(e){const s=Object.fromEntries(Xd(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Yd)||"{}"),n={...s,...r};for(const[a,o]of oy)n[a]===o&&(n[a]=s[a]);return n}catch{return s}}function Jd(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function ly({enabled:e=!0,onTrigger:s}){const r=iy(),[n,a]=i.useState(()=>_n(r)),[o,l]=i.useState(null),[c,d]=i.useState([]),m=i.useRef({parts:[],timer:null}),u=i.useCallback(p=>{const b=[];return p.metaKey&&b.push(r?"⌘":"Meta"),p.ctrlKey&&b.push("Ctrl"),p.altKey&&b.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(b.push(Jd(p.key)),b.join("+"))},[r]),h=i.useCallback(p=>{a(p);try{localStorage.setItem(Yd,JSON.stringify(p))}catch{}},[]);i.useEffect(()=>{const p=_n(r),b=Object.entries(n),y=Object.entries(p);b.length===y.length&&b.every(([x,I])=>p[x]===I)||h(p)},[n,r,h]);const g=i.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),k=i.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},ay))},[]);i.useEffect(()=>{if(!o)return;const p=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){l(null),d([]);return}const y=u(b);if(!y)return;const I=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(c.length===0&&I){d([y]);return}const j=[...c,y].slice(0,2).join(" "),A={...n};for(const[M,v]of Object.entries(A))v===j&&delete A[M];A[o]=j,h(A),l(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,h,o,c]),i.useEffect(()=>{if(!e||o)return;const p=b=>{if(b.defaultPrevented)return;const y=u(b);if(!y)return;const x=b.metaKey||b.ctrlKey||b.altKey;if(ho(b.target))return;const I=m.current.parts,N=x?[y]:[...I.slice(-1),y].slice(-2),j=N.join(" "),A=N[N.length-1],M=Object.entries(n).filter(([,T])=>!!T),v=M.find(([,T])=>T===j);if(v){b.preventDefault(),g(),s(v[0]);return}if(M.some(([,T])=>T.startsWith(`${j} `))){b.preventDefault(),m.current.parts=N,k();return}const B=M.find(([,T])=>T===A);if(B){b.preventDefault(),g(),s(B[0]);return}if(M.some(([,T])=>T.startsWith(`${A} `))){b.preventDefault(),m.current.parts=[A],k();return}g()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,k,e,u,s,g,o]),i.useEffect(()=>()=>g(),[g]);const f=i.useMemo(()=>Xd(r),[r]);return{isMac:r,actionDefinitions:f,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:l,setShortcutListeningDraft:d,saveShortcuts:h}}function cy({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 Qd(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function bl({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Qd(n):!0}function dy({previousVisibleConversationCount:e,visibleConversationCount:s,ides:r}){return s>0||e<=0?!1:Qd(r)}const Zd=1e3,uy=4;function gl(e,s){return s?e.clientX>=s.left&&e.clientX<=s.right&&e.clientY>=s.top&&e.clientY<=s.bottom:!1}function yl(e,s,r){return Math.abs(s.clientX-e.clientX)>r||Math.abs(s.clientY-e.clientY)>r}function my({detachDelayMs:e=Zd,stillnessThresholdPx:s=uy,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,l=null,c=null,d=null,m=null,u=!1;const h=()=>{m!=null&&(a(m),m=null)},g=()=>{h(),c=null},k=()=>{h(),o=null,l=null,c=null,d=null,u=!1},f=()=>{!o||!c||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!c||!d||u)&&gl(d,l)&&(yl(c,d,s)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},p=y=>{if(!(!o||u)){if(!gl(y,l)){d={clientX:y.clientX,clientY:y.clientY},g();return}(!c||yl(c,y,s))&&(h(),c={clientX:y.clientX,clientY:y.clientY}),d={clientX:y.clientX,clientY:y.clientY},f()}},b=y=>{!o||u||(y&&(d={clientX:y.clientX,clientY:y.clientY}),g())};return{startDrag:y=>{h(),o=y.panelId,l=y.selfPanelBounds??null,c=null,d={clientX:y.clientX,clientY:y.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:b,markNoDropTarget:b,markDockTarget:b,endDrag:k,isDragging:()=>o!=null,hasDetached:()=>u,dispose:k}}function py(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Zr(e){return e.isActive}function vl(e){return e.isVisible}const eu=i.createContext(null);function qn(){const e=i.useContext(eu);if(!e)throw new Error("DashboardDockviewContext missing");return e}function fn(e){return dt(e)||e.tabKey}function fy(e){return`remote:${e}`}function Dt(e){return e.startsWith("remote:")}function wl(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function hy(e){e.preventDefault()}function Na(e){var n;const s=e==null?void 0:e.defaultView;if(!s)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{s.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=s.requestAnimationFrame)==null||n.call(s,()=>{try{s.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function Sa(e,s){e.classList.remove(qa.className,Ya.className),e.classList.add(s==="light"?qa.className:Ya.className)}function jl(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 xy(e){const[,s]=i.useState(0);i.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 by(e,s,r){var l;const n=[s];let a;for(const c of n){let d;for(const m of c){const u=e.addPanel({id:m.tabKey,component:"conversation",title:fn(m),params:{kind:"conversation",tabKey:m.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((l=s[0])==null?void 0:l.tabKey)??null}function kl(e,s){const r=new Set(s.map(a=>a.tabKey)),n=new Map;for(const a of s)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])Dt(a.id)||r.has(a.id)||e.removePanel(a);for(const a of s){const o=e.getPanel(a.tabKey);if(o){(n.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==fn(a)&&o.api.setTitle(fn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:fn(a),params:{kind:"conversation",tabKey:a.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 Nl(e,s,r){var d,m;const n=r?fy(r):null;for(const u of[...e.panels])Dt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Bt(s,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),l=Zc(a);if(o){o.title!==l&&o.api.setTitle(l);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!Dt(u.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:l,params:{kind:"remote",routeId:r},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function gy({params:e,api:s}){var k;const r=qn(),n=i.useRef(null),[a,o]=i.useState(()=>Zr(s)),[l,c]=i.useState(()=>vl(s)),d=r.conversationsByTabKey.get(e.tabKey),m=Kn({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(Zr(s)),c(vl(s));const f=[s.onDidActiveChange(p=>o(p.isActive)),s.onDidActiveGroupChange(p=>{if(!Zr(s)&&!p.isActive){o(!1);return}o(Zr(s))}),s.onDidVisibilityChange(p=>c(p.isVisible))];return()=>{for(const p of f)p.dispose()}},[s]);const u=i.useMemo(()=>d?r.ides.find(f=>f.id===d.routeId):void 0,[r.ides,d]),h=i.useMemo(()=>d?r.actionLogs.filter(f=>f.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(ri,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const g=!tt(d)&&Xs(d)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(ti,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:g,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:h,userName:r.userName,scrollToBottomRequestNonce:((k=r.scrollToBottomRequest)==null?void 0:k.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:l})})}function yy({params:e}){var d;const s=qn(),r=i.useMemo(()=>Bt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>s.ides.find(m=>m.id===e.routeId),[s.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:l,handleRemoteAction:c}=qd({doId:a,targetSessionId:r?Dc(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(yc,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:l,transportType:r.transport,onAction:c})}):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 vy(){const e=qn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(ri,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function wy(e){var k,f;xy(e);const s=qn(),r=i.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Bt([...s.conversationsByTabKey.values()],e.params.routeId),b=((k=e.api.group.activePanel)==null?void 0:k.id)===e.api.id,y=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.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:p!=null&&p.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:p.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=((f=e.api.group.activePanel)==null?void 0:f.id)===e.api.id,o=e.api.isGroupActive,l=Bn(n,s.liveSessionInboxState,{isOpenConversation:a}),c=l.isReconnecting,d=l.isConnecting,m=l.isGenerating,u=l.isWaiting,h=l.unread,g=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${c?" is-reconnecting":""}`,title:dt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var b;p.preventDefault(),r(p),s.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((b=p.target)==null?void 0:b.ownerDocument)??document})},children:[h&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?t.jsx("div",{className:"tab-spinner"}):u?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):c?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?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:dt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:c?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:hs(n)}):d?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 jy({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:h,registerActionHandlers:g,onActiveTabChange:k,onOpenNewSession:f,onRequestScrollToBottom:p,requestedActiveTabKey:b,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:x,scrollToBottomRequest:I,liveSessionInboxState:N,layoutProfile:j}){var et,ze,at;const{theme:A}=Yo(),{sendCommand:M}=wt(),v=i.useRef(null),w=i.useRef(null),B=i.useRef(null),R=i.useRef(!1),T=i.useRef(!1),H=i.useRef(!1),E=i.useRef(null),D=i.useRef([]),[S,C]=i.useState(null),[W,_]=i.useState(0),O=i.useRef(typeof window>"u"?{}:Kb(j)),V=i.useMemo(()=>new Map(e.map(U=>[U.tabKey,U])),[e]),X=i.useMemo(()=>{const U=v.current;return U?U.groups.some(z=>{try{const Z=z.model.location.type;return Z!=="floating"&&Z!=="popout"?!1:z.panels.some(ie=>V.has(ie.id))}catch{return!1}}):!1},[V,W,e]),ye=i.useCallback(()=>{var U;(U=v.current)==null||U.focus()},[]),he=i.useCallback((U,z)=>{p==null||p(U,z)},[p]),ne=i.useCallback(U=>{const z=document,Z=U.document;for(const le of z.querySelectorAll('link[rel="stylesheet"]')){const je=Z.createElement("link");je.rel="stylesheet",je.href=le.href,le.crossOrigin&&(je.crossOrigin=le.crossOrigin),Z.head.appendChild(je)}for(const le of z.querySelectorAll("style")){const je=Z.createElement("style");je.textContent=le.textContent,Z.head.appendChild(je)}const ie=[];for(const le of z.styleSheets)try{for(const je of le.cssRules)je instanceof CSSStyleRule&&(je.selectorText===":root"||je.selectorText==="html")&&ie.push(je.cssText)}catch{}if(ie.length>0){const le=Z.createElement("style");le.textContent=ie.join(`
|
|
54
|
-
`),Z.head.appendChild(le)}const F=z.documentElement.getAttribute("data-theme");F&&Z.documentElement.setAttribute("data-theme",F),Z.documentElement.style.colorScheme=F==="light"?"light":"dark",Z.body.className=z.body.className;const Y=z.documentElement.getAttribute("style");Y&&Z.documentElement.setAttribute("style",Y);const re=Z.getElementById("dv-popout-window");re instanceof HTMLElement&&(re.classList.add("adhdev-dockview"),Sa(re,A))},[A]),pe=i.useCallback(()=>{var z;const U=v.current;if(U)for(const Z of U.groups)try{const ie=(z=Z.element)==null?void 0:z.ownerDocument;if(!ie||ie===document)continue;const F=ie.getElementById("dv-popout-window");F instanceof HTMLElement&&(F.classList.add("adhdev-dockview"),Sa(F,A));const Y=document.documentElement.getAttribute("data-theme");Y&&ie.documentElement.setAttribute("data-theme",Y),ie.documentElement.style.colorScheme=Y==="light"?"light":"dark",ie.body.className=document.body.className;const re=document.documentElement.getAttribute("style");re?ie.documentElement.setAttribute("style",re):ie.documentElement.removeAttribute("style")}catch{}},[A]),ke=i.useCallback(U=>{const z=v.current;if(!z)return;const Z=z.getPanel(U);Z&&z.addPopoutGroup(Z,{popoutUrl:"/popout.html",onDidOpen:({window:ie})=>{ne(ie),de();const F=V.get(U);ie.document.title=F?`${dt(F)} — ADHDev`:"ADHDev — Popout"}})},[V,ne]),Se=i.useCallback(U=>{const z=v.current,Z=z==null?void 0:z.getPanel(U);if(!z||!Z)return;const ie=z.groups.filter(F=>{var Y;try{return((Y=F.element)==null?void 0:Y.ownerDocument)===document}catch{return!0}});ie.length>0?Z.api.moveTo({group:ie[0],position:"center"}):Z.api.moveTo({position:"center"}),Z.api.setActive()},[]),G=i.useCallback(U=>{var ie;const z=v.current;if(!z)return!1;const Z=z.getPanel(U);if(!Z)return!1;try{return((ie=Z.group.element)==null?void 0:ie.ownerDocument)!==document}catch{return!1}},[]),be=i.useCallback(U=>{G(U)&&Se(U),u(U)},[G,Se,u]),fe=i.useCallback(U=>{const z=v.current,Z=z==null?void 0:z.getPanel(U);!z||!Z||z.addFloatingGroup(Z,{width:600,height:500})},[]),ve=i.useCallback(U=>{var Z;const z=(Z=v.current)==null?void 0:Z.getPanel(U);if(!z)return!1;try{return z.group.model.location.type==="floating"}catch{return!1}},[]),P=i.useCallback(()=>{var z,Z;const U=(Z=(z=v.current)==null?void 0:z.activePanel)==null?void 0:Z.id;return!U||Dt(U)?null:V.has(U)?U:null},[V]),me=i.useCallback(U=>{const z=v.current,Z=z==null?void 0:z.getPanel(U);if(!z||!Z)return;const ie=z.groups.filter(F=>{try{return F.model.location.type==="grid"}catch{return!0}});ie.length>0?Z.api.moveTo({group:ie[0],position:"center"}):Z.api.moveTo({position:"center"}),Z.api.setActive()},[]),q=i.useCallback(()=>{var Y;const U=v.current;if(!U)return;const Z=U.groups.filter(re=>{var le;try{return((le=re.element)==null?void 0:le.ownerDocument)===document&&re.model.location.type==="grid"}catch{return!1}})[0]||null,ie=[...U.panels];for(const re of ie){const le=(Y=re.group.element)==null?void 0:Y.ownerDocument,je=re.group.model.location.type;le===document&&je==="grid"||(Z&&Z.id!==re.group.id?re.api.moveTo({group:Z,position:"center"}):re.api.moveTo({position:"center"}))}const F=U.activePanel;F&&(F.group.model.openPanel(F),F.api.setActive()),Na(document)},[]),de=i.useCallback(()=>{var z,Z;const U=v.current;if(U)for(const ie of U.groups){const F=(z=ie.element)==null?void 0:z.ownerDocument;if(!F||F===document)continue;const Y=F.getElementById("dv-popout-window");if(!(Y instanceof HTMLElement))continue;let re=null,le=F.title||"ADHDev",je="Popout workspace";const _e=ie.activePanel;if(_e)if(re=_e.id,Dt(_e.id)){const Ae=((Z=_e.params)==null?void 0:Z.routeId)||_e.id.slice(7),Xe=Bt([...V.values()],Ae);le=Zc(Xe),je=Xe!=null&&Xe.machineName?`Remote view · ${Xe.machineName}`:"Remote view"}else{const Ae=V.get(_e.id);le=Ae?dt(Ae):_e.title||_e.id,je=Ae?hs(Ae):"Dockview panel"}F.title=`${le} — ADHDev`;const De=Array.from(F.querySelectorAll("#adhdev-popout-header"));for(const Ae of De)Ae.remove();const Me=F.createElement("div");Me.id="adhdev-popout-header",F.body.appendChild(Me),Me.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(";")),Me.innerHTML=`
|
|
55
|
-
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
56
|
-
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
57
|
-
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${wl(le)}</div>
|
|
58
|
-
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${wl(je)}</div>
|
|
59
|
-
</div>
|
|
60
|
-
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
61
|
-
<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>
|
|
62
|
-
<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>
|
|
63
|
-
</div>
|
|
64
|
-
`,Y.style.top="52px",Y.style.height="calc(100% - 52px)";const Ee=Me.querySelector("[data-adhdev-popout-focus]");Ee&&(Ee.onclick=()=>{window.focus()});const Oe=Me.querySelector("[data-adhdev-popout-dock]");Oe&&(Oe.disabled=!re,Oe.style.opacity=re?"1":"0.5",Oe.style.cursor=re?"pointer":"default",Oe.onclick=()=>{var Ae;re&&Se(re),(Ae=F.defaultView)==null||Ae.focus()})}},[V,Se]),ae=i.useCallback(U=>{var ie;const z=v.current,Z=z==null?void 0:z.getPanel(U);if(!(!z||!Z)){Z.group.model.openPanel(Z),Z.api.setActive(),he(U,"dockview-shortcut");try{const F=Z.group.model.location;F.type==="popout"?F.getWindow().focus():Na((ie=Z.group.element)==null?void 0:ie.ownerDocument)}catch{}}},[he]),xe=i.useCallback(U=>{const z=v.current,Z=z==null?void 0:z.activePanel,ie=(z==null?void 0:z.activeGroup)||(Z==null?void 0:Z.group);if(!z||!Z||!ie)return;const F=ie.panels||[];if(F.length<=1)return;const Y=F.findIndex(je=>je.id===Z.id);if(Y<0)return;const re=(Y+U+F.length)%F.length,le=F[re];le&&(le.group.model.openPanel(le),le.api.setActive(),Dt(le.id)||he(le.id,"dockview-shortcut"))},[he]),ue=i.useCallback(U=>{var Ee;const z=v.current,Z=(z==null?void 0:z.activeGroup)||((Ee=z==null?void 0:z.activePanel)==null?void 0:Ee.group);if(!z||!Z)return;const ie=z.groups||[],F=ie.find(Oe=>Oe.id===Z.id);if(!F)return;const Y=F.element.getBoundingClientRect(),re=Y.left+Y.width/2,le=Y.top+Y.height/2,je=(Oe,Ae,Xe,Qe)=>Math.max(0,Math.min(Ae,Qe)-Math.max(Oe,Xe)),_e=Oe=>{const Ae=Oe.element.getBoundingClientRect(),Xe=Ae.left+Ae.width/2,Qe=Ae.top+Ae.height/2;let xt=0,bt=0,ct=0,pt=!1;if(U==="left"?(pt=Xe<re,xt=Math.max(0,Y.left-Ae.right),bt=Math.abs(Qe-le),ct=je(Y.top,Y.bottom,Ae.top,Ae.bottom)):U==="right"?(pt=Xe>re,xt=Math.max(0,Ae.left-Y.right),bt=Math.abs(Qe-le),ct=je(Y.top,Y.bottom,Ae.top,Ae.bottom)):U==="above"?(pt=Qe<le,xt=Math.max(0,Y.top-Ae.bottom),bt=Math.abs(Xe-re),ct=je(Y.left,Y.right,Ae.left,Ae.right)):(pt=Qe>le,xt=Math.max(0,Ae.top-Y.bottom),bt=Math.abs(Xe-re),ct=je(Y.left,Y.right,Ae.left,Ae.right)),!pt)return Number.POSITIVE_INFINITY;const We=ct>0?0:120;return xt*3+bt+We};let De=null,Me=Number.POSITIVE_INFINITY;for(const Oe of ie){if(Oe.id===F.id)continue;const Ae=_e(Oe);Number.isFinite(Ae)&&(Ae>=Me||(Me=Ae,De=Oe))}return De||void 0},[]),ce=i.useCallback(U=>{var ie;const z=ue(U);if(!z)return;const Z=z.activePanel||z.panels[0];Z&&(z.model.openPanel(Z),Z.api.setActive(),Dt(Z.id)||he(Z.id,"dockview-focus"),Na((ie=z.element)==null?void 0:ie.ownerDocument))},[ue,he]),te=i.useCallback((U,z)=>{const Z=v.current,ie=Z==null?void 0:Z.activePanel,F=(Z==null?void 0:Z.activeGroup)||(ie==null?void 0:ie.group);if(!Z||!ie||!F)return;let Y=ue(U);!Y&&(z!=null&&z.createGroupIfMissing)&&(Y=Z.addGroup({referenceGroup:F,direction:U})),Y&&(ie.api.moveTo({group:Y,position:"center"}),ie.group.model.openPanel(ie),ie.api.setActive(),Dt(ie.id)||he(ie.id,z!=null&&z.createGroupIfMissing?"dockview-split":"dockview-move"))},[ue,he]),{isMac:$,tabShortcuts:J,shortcutListening:oe,setShortcutListening:ee,saveShortcuts:Ne}=Gd({sortedTabKeys:e.map(U=>U.tabKey),onFocus:ye,onSelectTab:ae}),Ce=i.useCallback(()=>{var Z;const U=v.current;if(!U)return;const z=U.activePanel;if(z){if(Dt(z.id)){const ie=((Z=z.params)==null?void 0:Z.routeId)||z.id.slice(7),F=Bt(e,ie);F!=null&&F.tabKey&&ee(F.tabKey);return}V.has(z.id)&&ee(z.id)}},[V,ae,ee,e]),we=i.useCallback(U=>{const z=[];return U.metaKey&&z.push($?"⌘":"Meta"),U.ctrlKey&&z.push("Ctrl"),U.altKey&&z.push($?"⌥":"Alt"),U.shiftKey&&U.key.length!==1&&z.push($?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(U.key)?null:(z.push(Jd(U.key)),z.join("+"))},[$]),K=i.useCallback(U=>{var z,Z;switch(U){case"splitActiveTabRight":te("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":te("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ie=P();ie&&fe(ie);return}case"popoutActiveTab":{const ie=P();ie&&ke(ie);return}case"dockActiveTab":{const ie=P();if(!ie)return;G(ie)?Se(ie):ve(ie)&&me(ie);return}case"focusLeftPane":ce("left");return;case"focusRightPane":ce("right");return;case"focusUpPane":ce("above");return;case"focusDownPane":ce("below");return;case"moveActiveTabToLeftPane":te("left");return;case"moveActiveTabToRightPane":te("right");return;case"moveActiveTabToUpPane":te("above");return;case"moveActiveTabToDownPane":te("below");return;case"selectPreviousGroupTab":xe(-1);return;case"selectNextGroupTab":xe(1);return;case"setActiveTabShortcut":Ce();return;case"hideCurrentTab":{const ie=(Z=(z=v.current)==null?void 0:z.activePanel)==null?void 0:Z.id;ie&&!Dt(ie)&&be(ie);return}default:return}},[xe,me,ce,fe,P,be,ve,G,Se,te,ke,Ce]);i.useEffect(()=>{if(!S)return;const U=S.sourceDocument,z=U.defaultView??window,Z=ie=>{const F=U.querySelector("[data-dockview-tab-context-menu]");F&&F.contains(ie.target)||C(null)};return z.addEventListener("mousedown",Z,!0),z!==window&&window.addEventListener("mousedown",()=>C(null),!0),()=>{z.removeEventListener("mousedown",Z,!0),z!==window&&window.removeEventListener("mousedown",()=>C(null),!0)}},[S]);const Ie=i.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:V,hasDetachedConversationPanels:X,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:f,liveSessionInboxState:N,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:be,userName:m,scrollToBottomRequest:I,tabShortcuts:J,openTabContextMenu:({x:U,y:z,tabKey:Z,sourceDocument:ie})=>C({x:U,y:z,tabKey:Z,sourceDocument:ie??document}),popoutTab:ke,moveTabBackToMain:Se,isTabInPopout:G,floatTab:fe,isTabFloating:ve}),[n,s,V,X,r,l,c,f,N,a,o,be,m,I,J,ke,Se,G,fe,ve]),Re=S?cy({isTabInPopout:G(S.tabKey),isTabFloating:ve(S.tabKey),tabShortcut:J[S.tabKey],actionShortcuts:h}):[],Ke=i.useCallback(U=>{var ie;const z=v.current;if((((ie=z==null?void 0:z.activePanel)==null?void 0:ie.id)??null)===U.id){U.group.model.openPanel(U);return}U.group.model.openPanel(U),U.api.setActive()},[]),He=i.useCallback((U,z="requested-tab")=>{if(!U)return!1;const Z=v.current;if(!Z)return!1;const ie=Z.getPanel(U);return ie?(Ke(ie),he(U,z),x==null||x(),!0):!1},[Ke,x,he]),qe=i.useCallback(()=>{if(H.current)return!1;const U=He(E.current,"stored-layout-restore");return U&&(H.current=!0),U},[He]),Ye=i.useCallback(()=>{var z;const U=v.current;U&&Fb(j,{activeTabId:((z=U.activePanel)==null?void 0:z.id)??null,layout:U.toJSON()})},[j]),st=i.useCallback(()=>{Wb(j,O.current)},[j]),mt=i.useCallback(U=>{var ie,F,Y,re;const z=v.current;if(!z)return{kind:"grid"};const Z=z.toJSON();for(const le of Z.floatingGroups||[])if((F=(ie=le.data)==null?void 0:ie.views)!=null&&F.includes(U)&&le.position)return{kind:"floating",position:le.position};for(const le of Z.popoutGroups||[])if((re=(Y=le.data)==null?void 0:Y.views)!=null&&re.includes(U))return{kind:"popout",position:le.position,popoutUrl:le.url};return{kind:"grid"}},[]),ht=i.useCallback(U=>{const z=v.current;if(!z)return;const Z=z.getPanel(U),ie=O.current[U];if(!Z||!ie||ie.kind==="grid")return;if(Z.group.model.location.type===ie.kind){delete O.current[U],st();return}if(ie.kind==="floating"){z.addFloatingGroup(Z,{x:ie.position.left??24,y:ie.position.top??24,width:ie.position.width,height:ie.position.height}),delete O.current[U],st();return}delete O.current[U],st()},[st]);i.useEffect(()=>(g==null||g({setShortcutForActiveTab:Ce,restoreHiddenTabToSavedLocation:ht,activateConversationTab:ae,resetAllPanelsToMain:q,activatePreviousTabInGroup:()=>xe(-1),activateNextTabInGroup:()=>xe(1),floatActiveTab:()=>{const U=P();U&&fe(U)},popoutActiveTab:()=>{const U=P();U&&ke(U)},dockActiveTab:()=>{const U=P();U&&(G(U)?Se(U):ve(U)&&me(U))},splitActiveTabRight:()=>te("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>te("below",{createGroupIfMissing:!0}),focusLeftPane:()=>ce("left"),focusRightPane:()=>ce("right"),focusUpPane:()=>ce("above"),focusDownPane:()=>ce("below"),moveActiveTabToLeftPane:()=>te("left"),moveActiveTabToRightPane:()=>te("right"),moveActiveTabToUpPane:()=>te("above"),moveActiveTabToDownPane:()=>te("below")}),()=>g==null?void 0:g(null)),[xe,me,fe,ce,P,ve,G,te,Se,ke,g,q,ht,ae,Ce]),i.useEffect(()=>()=>{var U;(U=B.current)==null||U.call(B),B.current=null},[]);const yt=i.useCallback(U=>{var Z,ie;v.current=U.api,(Z=B.current)==null||Z.call(B),B.current=null;const z=Ob(j);if(E.current=(z==null?void 0:z.activeTabId)??null,z!=null&&z.layout&&U.api.fromJSON(z.layout,{reuseExistingPanels:!1}),T.current=bl({hasStoredLayout:!!(z!=null&&z.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),T.current||(kl(U.api,e),Nl(U.api,e,y)),U.api.totalPanels===0&&e.length>0){const F=by(U.api,e,b);if(F){const Y=U.api.getPanel(F);Y&&Ke(Y)}}else!T.current&&!He(b)&&qe();if(R.current=!0,U.api.onDidActivePanelChange(F=>{var re;if(E.current=(F==null?void 0:F.id)??null,H.current=!0,de(),F&&Dt(F.id)){const le=((re=F.params)==null?void 0:re.routeId)||F.id.slice(7),je=Bt(e,le);k((je==null?void 0:je.tabKey)??null),Ye();return}if(k((F==null?void 0:F.id)??null),Ye(),!F)return;const Y=V.get(F.id);(Y==null?void 0:Y.streamSource)==="agent-stream"&&Y.agentType&&M(Y.routeId,Ec(),{agentType:Y.agentType,...Y.sessionId&&{targetSessionId:Y.sessionId}}).catch(()=>{})}),U.api.onDidLayoutChange(()=>{Ye(),de(),_(F=>F+1)}),py()){const F=Me=>({clientX:Me.clientX,clientY:Me.clientY}),Y=Me=>{const Ee=Me==null?void 0:Me.getBoundingClientRect();return Ee?{left:Ee.left,right:Ee.right,top:Ee.top,bottom:Ee.bottom}:null},re=Me=>{var Oe;const Ee=(Oe=w.current)==null?void 0:Oe.getBoundingClientRect();return Ee?Me.clientX<Ee.left||Me.clientX>Ee.right||Me.clientY<Ee.top||Me.clientY>Ee.bottom:!1},le=my({detachDelayMs:Zd,onDetach:({panelId:Me,clientX:Ee,clientY:Oe})=>{var ct,pt;const Ae=U.api.getPanel(Me);if(!Ae)return;try{if(Ae.group.model.location.type!=="grid")return}catch{return}const Xe=(ct=w.current)==null?void 0:ct.getBoundingClientRect(),Qe=(pt=Ae.group.element)==null?void 0:pt.getBoundingClientRect(),xt=Math.round(Math.min(Math.max((Qe==null?void 0:Qe.width)??600,360),720)),bt=Math.round(Math.min(Math.max((Qe==null?void 0:Qe.height)??500,260),640));U.api.addFloatingGroup(Ae,{x:Xe?Math.max(0,Ee-Xe.left-32):void 0,y:Xe?Math.max(0,Oe-Xe.top-18):void 0,width:xt,height:bt}),Ae.api.setActive(),Ye(),de(),_(We=>We+1)}}),je=[U.api.onWillDragPanel(Me=>{if(!(Me.nativeEvent.defaultPrevented||Me.nativeEvent.shiftKey)){try{if(Me.panel.group.model.location.type!=="grid")return}catch{return}le.startDrag({panelId:Me.panel.id,selfPanelBounds:Y(Me.panel.group.element),...F(Me.nativeEvent)})}}),U.api.onWillShowOverlay(Me=>{if(le.hasDetached()){Me.preventDefault();return}le.markDockTarget(F(Me.nativeEvent))}),U.api.onWillDrop(Me=>{if(le.hasDetached()){Me.preventDefault(),le.endDrag();return}le.markDockTarget(F(Me.nativeEvent))}),U.api.onDidDrop(()=>le.endDrag()),U.api.onUnhandledDragOverEvent(Me=>{le.isDragging()&&le.markSelfPanel(F(Me.nativeEvent))})],_e=Me=>{if(!le.isDragging())return;const Ee=F(Me);re(Ee)&&le.markNonSelfPanel(Ee)},De=()=>le.endDrag();window.addEventListener("dragover",_e,!0),window.addEventListener("drop",De,!0),window.addEventListener("dragend",De,!0),B.current=()=>{le.dispose();for(const Me of je)Me.dispose();window.removeEventListener("dragover",_e,!0),window.removeEventListener("drop",De,!0),window.removeEventListener("dragend",De,!0)}}U.api.onDidAddGroup(F=>{requestAnimationFrame(()=>{var Y,re;try{const le=(Y=F.element)==null?void 0:Y.ownerDocument;if(!le||le===document)return;(re=le.getElementById("dv-popout-window"))==null||re.classList.add("adhdev-dockview");const je=document.documentElement.getAttribute("data-theme");je&&le.documentElement.setAttribute("data-theme",je),le.body.className=document.body.className;const _e=document.documentElement.getAttribute("style");_e&&le.documentElement.setAttribute("style",_e)}catch{}de(),_(le=>le+1)})}),k(((ie=U.api.activePanel)==null?void 0:ie.id)??null)},[Ke,He,V,r,d,j,k,Ye,b,y,M,de,e]);i.useLayoutEffect(()=>{const U=v.current;if(!U||!R.current||T.current&&bl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;T.current&&(T.current=!1);const z=D.current,Z=new Set(z),ie=e.map(De=>De.tabKey),F=new Set(ie),Y=dy({previousVisibleConversationCount:z.length,visibleConversationCount:e.length,ides:r});let re=!1;for(const De of z)F.has(De)||Y||(O.current[De]=mt(De),re=!0);re&&st(),Y||(kl(U,e),Nl(U,e,y));const le=ie.filter(De=>!Z.has(De));let je=!1;for(const De of le){const Me=U.getPanel(De),Ee=O.current[De];if(!Me||!Ee||Ee.kind==="grid")continue;if(Me.group.model.location.type===Ee.kind){delete O.current[De],je=!0;continue}if(Ee.kind==="floating"){U.addFloatingGroup(Me,{x:Ee.position.left??24,y:Ee.position.top??24,width:Ee.position.width,height:Ee.position.height}),delete O.current[De],je=!0;continue}}if(je&&st(),D.current=ie,b&&He(b))return;!U.activePanel&&U.panels[0]&&Ke(U.panels[0]),!!(U.activePanel&&U.getPanel(U.activePanel.id))||qe()},[Ke,He,qe,r,d,st,mt,b,y,e]),i.useEffect(()=>{R.current&&He(b)},[He,b]),i.useEffect(()=>{const U=Z=>{const ie=Z.target;if(!ie)return;const F=ie.querySelector("[data-tab-key]")||ie.closest("[data-tab-key]");if(F){const Y=F.getAttribute("data-tab-key");if(Y&&Z.dataTransfer){const re=ie.closest(".dv-tab")||F.closest(".dv-tab")||F;Z.dataTransfer.effectAllowed="move",Z.dataTransfer.setData("text/tab-key",Y),re instanceof HTMLElement&&Z.dataTransfer.setDragImage(re,Math.max(12,Math.round(re.clientWidth/2)),Math.max(10,Math.round(re.clientHeight/2)))}}};window.addEventListener("dragstart",U);const z=jl(v.current);for(const Z of z)Z.addEventListener("dragstart",U);return()=>{window.removeEventListener("dragstart",U);for(const Z of z)Z.removeEventListener("dragstart",U)}},[W]),i.useEffect(()=>{var z;const U=(z=w.current)==null?void 0:z.querySelector(".adhdev-dockview");U instanceof HTMLElement&&Sa(U,A),pe(),de()},[de,pe,A]),i.useEffect(()=>{de()},[de]),i.useEffect(()=>{const U=z=>{if(z.defaultPrevented||oe)return;const Z=we(z);if(!Z)return;const ie=z.metaKey||z.ctrlKey||z.altKey;ho(z.target)&&!ie||_n($).setActiveTabShortcut!==Z||(z.preventDefault(),z.stopPropagation(),Ce())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[we,$,oe,Ce]),i.useEffect(()=>{const U=w.current;if(!U)return;const z=Z=>{var le,je;if(!Z.isTrusted)return;const ie=(je=(le=Z.target)==null?void 0:le.closest)==null?void 0:je.call(le,".dv-scrollable");if(!ie)return;Z.preventDefault(),Z.stopPropagation();const F=Math.abs(Z.deltaX),Y=Math.abs(Z.deltaY),re=F>Y?Z.deltaX:Z.deltaY;ie.dispatchEvent(new WheelEvent("wheel",{deltaY:re,deltaMode:Z.deltaMode,bubbles:!1,cancelable:!0}))};return U.addEventListener("wheel",z,{passive:!1,capture:!0}),()=>U.removeEventListener("wheel",z,{capture:!0})},[]),i.useEffect(()=>{const U=jl(v.current);if(U.length===0)return;const z=U.map(Z=>{let ie=[],F=null;const Y=()=>{F!=null&&Z.clearTimeout(F),F=null,ie=[]},re=()=>{F!=null&&Z.clearTimeout(F),F=Z.setTimeout(()=>{F=null,ie=[]},1200)},le=_e=>{if(!_e.ctrlKey&&!_e.metaKey&&!_e.altKey)return;const De=we(_e);if(!De)return;const Me=Vd();for(const[Ee,Oe]of Object.entries(Me))if(e.some(Ae=>Ae.tabKey===Ee)&&Oe===De){_e.preventDefault(),ae(Ee);return}},je=_e=>{if(_e.defaultPrevented||oe)return;const De=we(_e);if(!De)return;const Me=_e.metaKey||_e.ctrlKey||_e.altKey;if(ho(_e.target))return;const Ee=_n($),Oe=Object.entries(Ee).filter(([We,Ot])=>!!Ot&&(We==="splitActiveTabRight"||We==="splitActiveTabDown"||We==="floatActiveTab"||We==="popoutActiveTab"||We==="dockActiveTab"||We==="focusLeftPane"||We==="focusRightPane"||We==="focusUpPane"||We==="focusDownPane"||We==="moveActiveTabToLeftPane"||We==="moveActiveTabToRightPane"||We==="moveActiveTabToUpPane"||We==="moveActiveTabToDownPane"||We==="selectPreviousGroupTab"||We==="selectNextGroupTab"||We==="setActiveTabShortcut"||We==="hideCurrentTab")),Ae=Me?[De]:[...ie.slice(-1),De].slice(-2),Xe=Ae.join(" "),Qe=Ae[Ae.length-1],xt=Oe.find(([,We])=>We===Xe);if(xt){_e.preventDefault(),Y(),K(xt[0]);return}if(Oe.some(([,We])=>We.startsWith(`${Xe} `))){_e.preventDefault(),ie=Ae,re();return}const ct=Oe.find(([,We])=>We===Qe);if(ct){_e.preventDefault(),Y(),K(ct[0]);return}if(Oe.some(([,We])=>We.startsWith(`${Qe} `))){_e.preventDefault(),ie=[Qe],re();return}Y()};return Z.addEventListener("keydown",le),Z.addEventListener("keydown",je),()=>{Y(),Z.removeEventListener("keydown",le),Z.removeEventListener("keydown",je)}});return()=>{for(const Z of z)Z()}},[we,$,W,ae,oe,K,e]);const Te=A==="light"?qa:Ya,Ue=((at=(ze=(et=v.current)==null?void 0:et.activePanel)==null?void 0:ze.group.element)==null?void 0:at.ownerDocument)??document;return t.jsxs(eu.Provider,{value:Ie,children:[t.jsx("div",{ref:w,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(qu,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:gy,remote:yy},defaultTabComponent:wy,watermarkComponent:vy,onReady:yt,singleTabMode:"default",tabAnimation:"smooth",theme:Te,popoutUrl:"/popout.html"})}),S&&kr.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:S.x,top:S.y},children:Re.map(U=>{if(U.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},U.id);let z=t.jsx(Jm,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{};switch(U.id){case"dockInWindow":case"dockBackToGrid":z=t.jsx(Zm,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{me(S.tabKey),C(null)};break;case"moveBackToMain":z=t.jsx(Xm,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{Se(S.tabKey),C(null)};break;case"floatAsPanel":z=t.jsx(Qm,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{fe(S.tabKey),C(null)};break;case"openInNewWindow":z=t.jsx(Ym,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{ke(S.tabKey),C(null)};break;case"setShortcut":Z=ie=>{ie.stopPropagation(),ee(S.tabKey),C(null)};break;case"removeShortcut":z=t.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{const ie={...J};delete ie[S.tabKey],Ne(ie),C(null)};break;case"hideTab":z=t.jsx(So,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{be(S.tabKey),C(null)};break}return t.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${U.tone==="muted"?"text-text-muted":""}`,onMouseDown:hy,onClick:Z,children:[z,t.jsx("span",{className:"flex-1 min-w-0",children:U.label}),U.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:U.shortcut}):null]},U.id)})}),S.sourceDocument.body),oe&&kr.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:()=>ee(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:U=>U.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. ",$?"⌘+1":"Ctrl+1",", ",$?"⌥+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"})]})}),Ue.body)]})}const tu="adhdev-recent-launch-args-v1",ky=8;function su(e){return String(e||"").trim().replace(/\s+/g," ")}function ni(e,s){return`${e.trim()}::${s.trim()}`}function ai(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(tu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function ru(e){if(!(typeof window>"u"))try{window.localStorage.setItem(tu,JSON.stringify(e))}catch{}}function xo(e,s){var o;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((o=ai().byKey[ni(r,n)])==null?void 0:o.items)||[]}function nu(e,s,r){var u;const n=String(e||"").trim(),a=String(s||"").trim(),o=su(r);if(!n||!a||!o)return;const l=ai(),c=ni(n,a),d=((u=l.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(h=>h!==o)].slice(0,ky);l.byKey[c]={items:m},ru(l)}function Ny(e,s,r){var u;const n=String(e||"").trim(),a=String(s||"").trim(),o=su(r);if(!n||!a||!o)return;const l=ai(),c=ni(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(h=>h!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],ru(l)}function au(e){return!e.hasLoadedInitialResults&&!e.isLoading}function hn({title:e,description:s,action:r,children:n,className:a="",contentClassName:o=""}){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 ${o}`.trim():o,children:n}):null]})}function Sy({savedSessionsLoading:e,savedSessionsLoaded:s,savedSessionsCount:r=0}){return e?"Refreshing saved history…":s?r>0?`${r} saved ${r===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function ou({busy:e,savedSessionsLoading:s,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?Hd(o):null,u=Sy({savedSessionsLoading:s,savedSessionsLoaded:n,savedSessionsCount:a});return t.jsxs(hn,{title:"Saved history",description:Uo(),action:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||s,onClick:l,children:s?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:mx()})]}),children:[m?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:m.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),t.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:"Clear"})]})}):t.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&t.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function iu({setup:e,providerName:s,className:r=""}){return e?t.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[t.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",s?` for ${s}`:""]}),e.instructions&&t.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&t.jsxs("span",{children:["Server: ",t.jsx("code",{children:e.serverName})]}),e.configFormat&&t.jsxs("span",{children:["Format: ",t.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&t.jsxs("span",{children:["Config path: ",t.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&t.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&t.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}function Cy({workspaceMode:e,activeKind:s,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:l}){return e==="mesh"?null: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:r},{id:"ide",label:"IDE",enabled:n},{id:"acp",label:"ACP",enabled:a}].map(c=>t.jsx("button",{type:"button",className:`btn btn-sm ${s===c.id?"btn-primary":"btn-secondary"}`,onClick:()=>l(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function Ca(e){var n;if(!e)return null;const s=e.availableProviders||[];return s.some(a=>Cs(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(a=>Cs(a,"acp"))?"acp":null}function en(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Iy({machines:e,ides:s,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var We,Ot;const u=Lr(),h=i.useMemo(()=>[...e].sort(_o),[e]),[g,k]=i.useState(((We=h[0])==null?void 0:We.id)||""),f=i.useMemo(()=>h.find(se=>se.id===g)||h[0],[g,h]),p=i.useMemo(()=>((f==null?void 0:f.workspaces)||[]).map(se=>({id:se.id,path:se.path,label:se.label})),[f]),b=(f==null?void 0:f.defaultWorkspaceId)||null,[y,x]=i.useState("workspace"),[I,N]=i.useState(""),[j,A]=i.useState(""),[M,v]=i.useState([]),[w,B]=i.useState(""),[R,T]=i.useState(!1),[H,E]=i.useState(null),[D,S]=i.useState(""),[C,W]=i.useState(Ca(h[0])),[_,O]=i.useState(""),[V,X]=i.useState(""),[ye,he]=i.useState([]),[ne,pe]=i.useState(""),[ke,Se]=i.useState([]),[G,be]=i.useState(!1),[fe,ve]=i.useState(!1),[P,me]=i.useState(""),[q,de]=i.useState(!1),[ae,xe]=i.useState(()=>Nt()),[ue,ce]=i.useState(null),[te,$]=i.useState(!1),[J,oe]=i.useState(""),[ee,Ne]=i.useState(null),[Ce,we]=i.useState(!1),[K,Ie]=i.useState(""),[Re,Ke]=i.useState([]),[He,qe]=i.useState(!1),[Ye,st]=i.useState(""),[mt,ht]=i.useState(!1),yt=i.useRef(null),Te=i.useRef(0);i.useEffect(()=>{var se;!g&&((se=h[0])!=null&&se.id)&&k(h[0].id)},[g,h]),i.useEffect(()=>{!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||u(f.id,{minFreshMs:3e4}).catch(()=>{})},[u,f]);const Ue=i.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(se=>Cs(se,"cli")),[f]),et=i.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(se=>Cs(se,"acp")),[f]),ze=i.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(se=>({id:se.type,label:se.name||se.type,meta:se.running?"Detected locally":"Available to open"})),[f]),at=i.useMemo(()=>C==="cli"?Ue.map(se=>({id:se.type,label:se.displayName||se.type,meta:"CLI provider"})):C==="acp"?et.map(se=>({id:se.type,label:se.displayName||se.type,meta:"ACP provider"})):ze,[et,C,Ue,ze]),U=i.useMemo(()=>M.find(se=>se.id===w)||null,[M,w]),z=i.useMemo(()=>Ue.find(se=>se.type===_)||null,[Ue,_]),Z=i.useMemo(()=>Ed(z==null?void 0:z.meshCoordinator,{meshId:(U==null?void 0:U.id)||"",workspace:(U==null?void 0:U.workspace)||""}),[z,U]),ie=ee||Z,F=i.useCallback(async se=>{T(!0),S("");try{const Pe=await c(se);v(Pe),B(L=>{var Q;return Pe.some(ge=>ge.id===L)?L:((Q=Pe[0])==null?void 0:Q.id)||""}),E(se)}catch(Pe){v([]),B(""),E(se),S(Pe instanceof Error?Pe.message:"Could not load meshes")}finally{T(!1)}},[c]);i.useEffect(()=>{var Pe;if(!f)return;if(yt.current!==f.id){yt.current=f.id,x("workspace"),N(b||((Pe=p[0])==null?void 0:Pe.id)||"__home__"),A(""),v([]),B(""),E(null),S(""),W(Ca(f)),O(""),X(""),pe(""),Se([]),ve(!1),me(""),xe(Nt()),oe(""),Ne(null);return}N(L=>{var Q;return L==="__custom__"||L==="__home__"||p.some(ge=>ge.id===L)?L:b||((Q=p[0])==null?void 0:Q.id)||"__home__"}),W(L=>L==="ide"&&ze.length>0||L==="cli"&&Ue.length>0||L==="acp"&&et.length>0?L:Ca(f))},[et.length,Ue.length,b,ze.length,f,p]),i.useEffect(()=>{!f||y!=="mesh"||H===f.id||R||F(f.id)},[F,H,R,f,y]),i.useEffect(()=>{y==="mesh"&&C!=="cli"&&Ue.length>0&&W("cli")},[C,Ue.length,y]),i.useEffect(()=>{var se;C&&(at.some(Pe=>Pe.id===_)||O(((se=at[0])==null?void 0:se.id)||""))},[C,at,_]),i.useEffect(()=>{Ne(null)},[f==null?void 0:f.id,w,_,y]);const Y=i.useCallback(async(se,Pe)=>{const L=Te.current+1;return Te.current=L,be(!0),me(""),m(se,Pe).then(Q=>{Te.current===L&&Se(Q)}).catch(Q=>{Te.current===L&&(Se([]),me(Q instanceof Error?Q.message:"Could not load saved sessions"))}).finally(()=>{Te.current===L&&(be(!1),ve(!0))})},[m]),re=i.useCallback((se,Pe)=>{he(xo(se,Pe))},[]);i.useEffect(()=>{Te.current+=1,pe(""),xe(Nt()),!f||!_||C==="ide"?he([]):re(f.id,_),ve(!1),Se([]),me(""),be(!1)},[C,re,Y,f,_]),i.useEffect(()=>{if(!ne)return;const se=ke.find(Pe=>Pe.providerSessionId===ne);se!=null&&se.canResume||pe("")},[ke,ne]);const le=I==="__custom__"?j.trim():I==="__home__"?"":((Ot=p.find(se=>se.id===I))==null?void 0:Ot.path)||"",je=i.useMemo(()=>f?s.filter(se=>se.id!==f.id&&se.daemonId===f.id).map(se=>se.workspace):[],[s,f]),_e=i.useMemo(()=>((f==null?void 0:f.recentLaunches)||[]).map(se=>se.workspace),[f]),De=i.useCallback(se=>{const Pe=String(se.workspace||"").trim();if(!Pe)return;const L=p.find(Q=>en(Q.path)===en(Pe));if(L){N(L.id),A("");return}N("__custom__"),A(Pe)},[p]),Me=i.useCallback(se=>{const Pe=String(se.workspace||"").trim();if(!Pe)return{workspaceId:null,workspacePath:null};const L=p.find(Q=>en(Q.path)===en(Pe));return L?{workspaceId:L.id,workspacePath:null}:{workspaceId:null,workspacePath:Pe}},[p]),Ee=i.useMemo(()=>ke.find(se=>se.providerSessionId===ne)||null,[ke,ne]),Oe=i.useMemo(()=>{var Pe;if(C!=="cli"||!f||!_)return null;const se=((Pe=Ue.find(L=>L.type===_))==null?void 0:Pe.displayName)||_;return{routeId:f.id,daemonId:f.id,providerSessionId:ne||void 0,transport:"pty",mode:"chat",agentName:se,agentType:_,status:"idle",title:se,messages:[],ideType:_,workspaceName:le,workspacePath:le,displayPrimary:se,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${f.id}:${_}`,machineName:At(f,{fallbackId:f.id})}},[C,Ue,le,f,ne,_]),Ae=i.useCallback(()=>{var Pe;if(!f)return;N("__custom__"),we(!0),st("");const se=zn(f.platform,Un(j.trim(),le,je,_e,f.defaultWorkspacePath,(Pe=p.find(L=>L.id===b))==null?void 0:Pe.path,p.map(L=>L.path)));qe(!0),n(f.id,se).then(L=>{Ie(L.path),A(L.path),Ke(L.directories)}).catch(L=>{st(L instanceof Error?L.message:"Could not load folder")}).finally(()=>qe(!1))},[j,b,_e,je,n,le,f,p]),Xe=i.useCallback(se=>{f&&(qe(!0),st(""),n(f.id,se).then(Pe=>{Ie(Pe.path),A(Pe.path),Ke(Pe.directories)}).catch(Pe=>{st(Pe instanceof Error?Pe.message:"Could not load folder")}).finally(()=>qe(!1)))},[n,f]),Qe=i.useCallback(async()=>{if(!f||!le)return;ht(!0),oe("");const se=await a(f.id,le);if(ht(!1),!se.ok){oe(se.error||"Could not save workspace");return}oe("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,le,f]),xt=i.useCallback(async()=>{if(!f)return;if(y==="mesh"){if(!w||!_)return;$(!0),oe(""),Ne(null);const L=await d(f.id,w,_);if($(!1),!L.ok){if(L.code==="mesh_coordinator_manual_mcp_setup_required"&&L.manualSetup){Ne(L.manualSetup),oe("Manual MCP setup required before this provider can act as mesh coordinator.");return}oe(L.error||"Could not start mesh coordinator");return}r();return}if(!C||!_)return;$(!0),oe("");const se=V.trim()?V.trim().split(/\s+/).filter(Boolean):[],Pe=C==="ide"?await o(f.id,_,{workspacePath:le||null}):await l(f.id,C,_,{workspaceId:I!=="__home__"&&I!=="__custom__"?I:null,workspacePath:I==="__custom__"&&le||null,resumeSessionId:C==="cli"&&ne?ne:null,cliArgs:se});if($(!1),!Pe.ok){oe(Pe.error||"Could not start session");return}C!=="ide"&&V.trim()&&(nu(f.id,_,V),re(f.id,_)),r()},[C,V,re,r,o,d,l,le,f,w,ne,_,I,y]),bt=y==="mesh"?"Start mesh coordinator":C?sd(C,C==="cli"&&!!ne):"Start",ct=y==="mesh"?"Starting coordinator…":C?rd(C,C==="cli"&&!!ne):"Starting…",pt=h.length>5;return f?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 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 or resume saved history."})]}),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:r,"aria-label":"Close new session dialog",children:t.jsx(vt,{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(hn,{title:"Machine",children:pt?t.jsx("select",{"aria-label":"Machine",value:f.id,onChange:se=>k(se.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:te,children:h.map(se=>t.jsx("option",{value:se.id,children:At(se,{fallbackId:se.id})},se.id))}):t.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(se=>{const Pe=At(se,{fallbackId:se.id}),L=f.id===se.id;return t.jsxs("button",{type:"button","aria-label":`Select machine ${Pe}`,"aria-pressed":L,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${L?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>k(se.id),disabled:te,title:Pe,children:[t.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${se.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),t.jsx("span",{className:"truncate",children:Pe})]},se.id)})})}),t.jsxs(hn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:y==="workspace"?t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,disabled:te,children:"Browse…"}):void 0,children:[t.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":"Launch target type",children:[{id:"workspace",label:"Workspace",desc:"Normal session"},{id:"mesh",label:"Mesh",desc:"Coordinator session"}].map(se=>t.jsxs("button",{type:"button",role:"radio","aria-checked":y===se.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${y===se.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{x(se.id),oe(""),se.id==="mesh"&&f&&H!==f.id&&!R&&F(f.id)},disabled:te,children:[t.jsx("div",{className:"text-sm font-semibold",children:se.label}),t.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:se.desc})]},se.id))}),y==="workspace"?t.jsxs(t.Fragment,{children:[t.jsxs("select",{value:I,onChange:se=>{const Pe=se.target.value;N(Pe),Pe==="__custom__"?Ae():oe("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:te,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),p.map(se=>t.jsxs("option",{value:se.id,children:[se.id===b?"⭐ ":"",On(se.path,se.label)||se.path]},se.id)),t.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:I==="__home__"?"Launch without a workspace.":le||"Select a workspace folder."}),I==="__custom__"&&le&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,disabled:te,children:[t.jsx(ks,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Qe,disabled:te||mt,children:mt?"Saving…":"Save workspace"})]})]}):t.jsxs("div",{className:"space-y-3",children:[R&&t.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!R&&D&&t.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:D}),!R&&!D&&M.length===0&&t.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker."}),M.length>0&&t.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:M.map(se=>t.jsxs("button",{type:"button",role:"radio","aria-checked":w===se.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${w===se.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>B(se.id),disabled:te,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:se.name}),t.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[se.repoIdentity||"Repo mesh",typeof se.nodesCount=="number"?` · ${se.nodesCount} node${se.nodesCount===1?"":"s"}`:""]}),se.workspace&&t.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",se.workspace]})]},se.id))}),U&&t.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),t.jsx(Cy,{workspaceMode:y,activeKind:C,cliEnabled:Ue.length>0,ideEnabled:ze.length>0,acpEnabled:et.length>0,busy:te,onSelect:W}),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:C==="ide"?"Choose IDE":C==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[at.map(se=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${_===se.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>O(se.id),disabled:te,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.meta})]},se.id)),at.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."})]})]}),y==="mesh"&&ie&&t.jsx(iu,{setup:ie,providerName:(z==null?void 0:z.displayName)||(z==null?void 0:z.name)||_}),y!=="mesh"&&C!=="ide"&&t.jsxs(hn,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:V,onChange:se=>X(se.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:te}),ye.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ye.map(se=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>X(se),disabled:te,title:se,children:se},se))})]}),y!=="mesh"&&C==="cli"&&t.jsx(ou,{busy:te,savedSessionsLoading:G,savedSessionsError:P,selectedSession:Ee,onRefresh:()=>{!f||!_||Y(f.id,_)},onOpenHistory:()=>{!f||!_||(de(!0),au({hasLoadedInitialResults:fe,isLoading:G})&&Y(f.id,_))},onClearSelection:()=>pe("")}),J&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${J.includes("saved")||J.includes("requested")||J.includes("Manual MCP setup")?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:J})]}),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:r,disabled:te,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:xt,disabled:te||(y==="mesh"?!w||!_||C!=="cli"||R:!C||!_||I==="__custom__"&&!le),children:[t.jsx(Io,{size:14}),te?ct:bt]})]})]})}),Ce&&t.jsx(Gn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:K,directories:Re,busy:He,error:Ye,onClose:()=>we(!1),onNavigate:Xe,onConfirm:se=>{A(se),Ie(se),N("__custom__"),we(!1)}}),q&&Oe&&t.jsx(Go,{activeConv:Oe,ides:[],isCreatingChat:!1,isRefreshingHistory:G,savedSessions:ke,isSavedSessionsLoading:G,isResumingSavedSessionId:ue,savedHistoryFilters:ae,missingWorkspaceResumePath:le||null,onSavedHistoryFiltersChange:xe,onClose:()=>de(!1),onNewChat:()=>{pe(""),de(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!f||!_||Y(f.id,_)},onResumeSavedSession:se=>{if(!f||!_||ue||!se.canResume)return;const Pe=Me(se);pe(se.providerSessionId),De(se),ce(se.providerSessionId),de(!1),$(!0),oe(""),l(f.id,"cli",_,{workspaceId:Pe.workspaceId,workspacePath:Pe.workspacePath,resumeSessionId:se.providerSessionId}).then(L=>{if(!L.ok){oe(L.error||"Could not resume session");return}r()}).finally(()=>{$(!1),ce(L=>L===se.providerSessionId?null:L)})}})]}):null}function Ty(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function Ay(e){return((e==null?void 0:e.submodules)??[]).some(s=>s.dirty)}function lu(e){return((e==null?void 0:e.submodules)??[]).some(s=>s.outOfSync||!!s.error)}function My(e){return lu(e)?"degraded":Ay(e)?"dirty":"online"}function Ly(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Sl(e){switch(e){case"online":return 0;case"dirty":return 1;case"degraded":return 2;case"wrong_branch":return 3;case"offline":return 4;case"unknown":default:return 5}}function Ia(e){return e.length===0?"unknown":e.reduce((s,r)=>Sl(r)>Sl(s)?r:s)}function Ry(e){var o,l,c,d,m;const s=new Map,r=new Map;for(const u of e){const h=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=u.git)!=null&&c.upstream&&s.set(h,(s.get(h)??0)+1))}const n=[...s.entries()].sort((u,h)=>{if(h[1]!==u[1])return h[1]-u[1];const g=["main","master","develop","dev"],k=g.indexOf(u[0]),f=g.indexOf(h[0]);return k!==-1||f!==-1?k===-1?1:f===-1?-1:k-f:u[0].localeCompare(h[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,h)=>h[1]-u[1])[0])==null?void 0:m[0])??null}function _y(e,s){const r=[],n=e.git;return n?n.isGitRepo?(!n.branch&&n.headCommit&&r.push("Detached HEAD"),n.hasConflicts&&r.push("Merge conflicts need resolution"),n.branch&&s&&n.branch!==s&&!n.upstream&&r.push(`No upstream tracking for ${n.branch}`),n.upstream&&n.upstreamStatus&&n.upstreamStatus!=="fresh"&&r.push(`Upstream freshness unverified for ${n.branch??"workspace"}`),e.error&&r.push(e.error),r):(r.push("Not a git repository"),r):(r.push("No git status available"),r)}function Py(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function cu(e){var g;const s=Ry(e.nodes),r=[],n=[],a=[],o=new Map;for(const k of e.nodes){const f=k.git,p=(f==null?void 0:f.branch)??null,b=My(f),y=Ty(f)||b==="dirty",x=_y(k,s),I={id:k.nodeId,type:x.length>0?"orphanNode":"worktreeNode",label:k.machineLabel||k.nodeId.slice(0,8),workspace:k.workspace,branch:p,upstream:(f==null?void 0:f.upstream)??null,upstreamStatus:(f==null?void 0:f.upstreamStatus)??null,machineLabel:k.machineLabel||null,health:Ia([k.health,b]),ahead:(f==null?void 0:f.ahead)??0,behind:(f==null?void 0:f.behind)??0,dirty:y,dirtyFiles:Ly(f),hasConflicts:(f==null?void 0:f.hasConflicts)??!1,activeSessionCount:((g=k.activeSessions)==null?void 0:g.length)??0,activeSessions:k.activeSessions??[],providers:k.providers??[],isOrphan:x.length>0,orphanReasons:x,error:k.error,nextStepHint:x[0],parentNodeId:null,submodulePath:null,submoduleCommit:(f==null?void 0:f.headCommit)??null,outOfSync:lu(f),source:k};if(r.push(I),p){const N=o.get(p)??[];N.push(I.id),o.set(p,N)}for(const N of(f==null?void 0:f.submodules)??[]){const j=`${I.id}::submodule::${N.path}`,A=N.path.split("/").filter(Boolean).pop()||N.path;r.push({id:j,type:"submoduleNode",label:A,workspace:N.repoPath,branch:null,upstream:null,upstreamStatus:null,machineLabel:I.machineLabel,health:Py(N),ahead:0,behind:0,dirty:N.dirty,dirtyFiles:N.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:N.error,nextStepHint:N.error||(N.outOfSync?`${N.path} is out of sync with the parent checkout`:N.dirty?`${N.path} has local changes`:`${N.path} is in sync with the parent checkout`),parentNodeId:I.id,submodulePath:N.path,submoduleCommit:N.commit,outOfSync:N.outOfSync,source:{kind:"synthetic-submodule",parentNodeId:I.id,parentWorkspace:k.workspace,submodule:N}}),n.push({id:`${I.id}--${j}`,source:I.id,target:j,type:"submoduleLink",label:N.outOfSync?"submodule out of sync":"submodule"})}}const l=s?`__branch_${s}`:null;if(l&&s){const f=(o.get(s)??[]).map(b=>r.find(y=>y.id===b)).filter(Boolean),p={id:l,type:"defaultBranchNode",label:s,workspace:e.repoIdentity,branch:s,upstream:null,upstreamStatus:null,machineLabel:"default branch",health:Ia(f.map(b=>b.health)),ahead:0,behind:0,dirty:f.some(b=>b.dirty),dirtyFiles:f.reduce((b,y)=>b+y.dirtyFiles,0),hasConflicts:f.some(b=>b.hasConflicts),activeSessionCount:f.reduce((b,y)=>b+y.activeSessionCount,0),activeSessions:f.flatMap(b=>b.activeSessions),providers:[...new Set(f.flatMap(b=>b.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:f.length>0?`${f.length} workspace(s) currently on ${s}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,source:{nodeId:l,machineLabel:s,workspace:e.repoIdentity,health:Ia(f.map(b=>b.health)),providers:[],activeSessions:[]}};r.push(p);for(const b of r)if(!(b.id===l||b.type==="submoduleNode")){if(b.branch===s){n.push({id:`${l}--${b.id}`,source:l,target:b.id,type:"parentBranch",label:"checked out"});continue}if(b.branch){n.push({id:`${l}--${b.id}`,source:l,target:b.id,type:b.isOrphan?"orphanLink":"parentBranch",label:b.branch});continue}b.isOrphan&&n.push({id:`${l}--${b.id}`,source:l,target:b.id,type:"orphanLink",label:"detached"})}}for(const[k,f]of o){if(f.length<2)continue;const p=f.map(b=>r.find(y=>y.id===b)).filter(Boolean);p.sort((b,y)=>b.label.localeCompare(y.label));for(let b=1;b<p.length;b+=1)n.push({id:`wt_${p[b-1].id}--${p[b].id}`,source:p[b-1].id,target:p[b].id,type:"worktreeLink",label:b===1?`${k} peers`:void 0})}const c=r.filter(k=>k.type!=="defaultBranchNode"),d=c.filter(k=>k.isOrphan).length,m=c.filter(k=>k.hasConflicts).length,u=c.filter(k=>k.health==="offline").length,h=c.filter(k=>k.type==="submoduleNode"&&k.outOfSync).length;return d>0&&a.push(`${d} workspace(s) need attention before safe coordination`),m>0&&a.push(`${m} workspace(s) report merge conflicts`),u>0&&a.push(`${u} node(s) are currently offline`),h>0&&a.push(`${h} submodule(s) are out of sync with their parent checkout`),s||a.push("Could not infer a default branch from live mesh status"),{meshId:e.meshId,meshName:e.meshName,repoIdentity:e.repoIdentity,refreshedAt:e.refreshedAt,nodes:r,edges:n,stats:{totalNodes:c.length,onlineNodes:c.filter(k=>k.health==="online").length,dirtyNodes:c.filter(k=>k.dirty).length,orphanNodes:d,errorNodes:c.filter(k=>!!k.error||k.outOfSync).length,offlineNodes:u,totalActiveSessions:c.reduce((k,f)=>k+f.activeSessionCount,0)},warnings:a}}function Dy(e){return!e.nextStepHint||e.type==="defaultBranchNode"?!1:!!(e.isOrphan||e.hasConflicts||e.outOfSync||e.error||e.health==="offline"||e.health==="degraded"||e.health==="wrong_branch"||e.dirty)}function tn(e){return[...new Set(e.filter(s=>!!s))]}function du(e){return e.nodes.filter(s=>s.type!=="submoduleNode")}function Ey(e){const s=e.nodes.find(l=>l.type==="defaultBranchNode")??null,r=(s==null?void 0:s.branch)??null,n=e.nodes.filter(l=>l.type!=="defaultBranchNode"&&l.type!=="submoduleNode"&&!l.isOrphan&&!!r&&l.branch===r),a=e.nodes.filter(l=>l.type!=="submoduleNode"&&!l.isOrphan),o=du(e);return s||n.length>0?tn([s==null?void 0:s.id,...n.map(l=>l.id)]):a.length>0?tn(a.map(l=>l.id)):o.length>0?tn(o.map(l=>l.id)):tn(e.nodes.map(l=>l.id))}function $y(e){const s=du(e),r=new Set(s.map(o=>o.branch).filter(o=>!!o)).size,n=e.nodes.filter(o=>o.type==="submoduleNode").length,a=s.filter(o=>o.isOrphan).length;return s.length>=6||r>=3||n>=3||a>0}function By(e){const s=[...e.nodes].sort((n,a)=>n.id.localeCompare(a.id)).map(n=>[n.id,n.type,n.branch??"",n.parentNodeId??"",n.submodulePath??""].join(":")).join("|"),r=[...e.edges].sort((n,a)=>n.id.localeCompare(a.id)).map(n=>[n.id,n.source,n.target,n.type].join(":")).join("|");return`${e.meshId}::${s}::${r}`}const Cl=430,Il=208,Tl=136,Oy=42,Al=164,Fy=30;function Ky(e,s){const r=s?"border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":"border-white/10 shadow-[0_18px_48px_rgba(3,7,18,0.22)]";switch(e){case"online":return`${r} bg-emerald-500/8`;case"dirty":return`${r} bg-amber-500/8`;case"degraded":return`${r} bg-rose-500/10`;case"wrong_branch":return`${r} bg-violet-500/10`;case"offline":return`${r} bg-slate-500/12`;default:return`${r} bg-slate-950/78`}}function Vt(e){switch(e){case"health":return"border-white/10 bg-slate-950/60 text-slate-200";case"dirty":return"border-amber-400/25 bg-amber-500/10 text-amber-200";case"conflict":return"border-rose-400/25 bg-rose-500/10 text-rose-200";case"orphan":return"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200";case"submodule":return"border-violet-400/25 bg-violet-500/10 text-violet-200";case"meta":default:return"border-cyan-400/20 bg-cyan-500/8 text-cyan-100"}}function uu(e){switch(e){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":return"#fb7185";case"wrong_branch":return"#a78bfa";case"offline":return"#94a3b8";default:return"#64748b"}}function Wy(e){return e.replace(/_/g," ")}function Hy(e){return!e.upstream||e.upstreamStatus==="fresh"}function Uy(e){return Hy(e)?`+${e.ahead} / -${e.behind}`:"upstream unverified"}function zy({data:e,selected:s}){const r=e.graphNode,n=r.type==="defaultBranchNode",a=r.type==="submoduleNode",o=Dy(r),l=n?"default branch anchor":a?r.submodulePath||"submodule checkout":r.machineLabel||r.workspace,c=r.submoduleCommit?r.submoduleCommit.slice(0,7):null;return t.jsxs("div",{className:`${a?"w-[216px]":"w-[232px]"} rounded-2xl border px-3.5 py-3 backdrop-blur-sm transition-all ${Ky(r.health,s)}`,children:[t.jsx(bi,{type:"target",position:gi.Top,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),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:"truncate text-sm font-semibold text-slate-100",children:r.label}),t.jsx("div",{className:"truncate text-[11px] text-slate-400",children:l})]}),t.jsx("span",{className:"mt-0.5 h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:uu(r.health)},"aria-hidden":!0})]}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-1.5 text-[10px]",children:[t.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Vt("health")}`,children:Wy(r.health)}),a&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("submodule")}`,children:"submodule"}),r.branch&&!a&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("meta")}`,children:r.branch}),c&&a&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("meta")}`,children:c}),r.dirty&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("dirty")}`,children:a?"local changes":`${r.dirtyFiles} dirty`}),r.outOfSync&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("conflict")}`,children:"out of sync"}),r.hasConflicts&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("conflict")}`,children:"conflicts"}),!a&&r.upstream&&r.upstreamStatus!=="fresh"&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("orphan")}`,children:"upstream unverified"}),r.isOrphan&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("orphan")}`,children:"needs attention"})]}),t.jsx("div",{className:"mt-3 space-y-1.5 text-[11px] text-slate-300",children:a?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("span",{className:"text-slate-500",children:"Parent"}),t.jsx("span",{className:"truncate text-right font-medium text-slate-100",children:r.machineLabel||"mesh node"})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("span",{className:"text-slate-500",children:"State"}),t.jsx("span",{className:"font-medium text-slate-100",children:r.outOfSync?"Out of sync":r.dirty?"Dirty":"Synced"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("span",{className:"text-slate-500",children:"Sessions"}),t.jsx("span",{className:"font-medium text-slate-100",children:r.activeSessionCount})]}),t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("span",{className:"text-slate-500",children:"Git drift"}),t.jsx("span",{className:"font-medium text-slate-100",children:Uy(r)})]})]})}),o&&t.jsx("div",{className:"mt-3 rounded-xl border border-cyan-400/15 bg-cyan-500/8 px-3 py-2 text-[10px] leading-4 text-cyan-50/90",children:r.nextStepHint}),t.jsx(bi,{type:"source",position:gi.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Vy={meshNode:zy};function Ta(e,s){return e.type==="defaultBranchNode"&&s.type!=="defaultBranchNode"?-1:s.type==="defaultBranchNode"&&e.type!=="defaultBranchNode"||e.type==="submoduleNode"&&s.type!=="submoduleNode"?1:s.type==="submoduleNode"&&e.type!=="submoduleNode"?-1:e.branch&&s.branch&&e.branch!==s.branch?e.branch.localeCompare(s.branch):e.branch&&!s.branch?-1:!e.branch&&s.branch?1:e.label.localeCompare(s.label)}function Gy(e){const s=[...e.nodes].sort(Ta),r=s.find(f=>f.type==="defaultBranchNode")??null,n=new Map;for(const f of s){if(f.type!=="submoduleNode"||!f.parentNodeId)continue;const p=n.get(f.parentNodeId)??[];p.push(f),n.set(f.parentNodeId,p)}const a=s.filter(f=>f.id!==(r==null?void 0:r.id)&&f.type!=="submoduleNode"),o=new Map,l=[];for(const f of a){if(f.isOrphan||!f.branch){l.push(f);continue}const p=f.branch,b=o.get(p)??[];b.push(f),o.set(p,b)}const c=[...o.entries()].sort(([f],[p])=>r!=null&&r.branch&&f===r.branch&&p!==r.branch?-1:r!=null&&r.branch&&p===r.branch&&f!==r.branch?1:f.localeCompare(p));l.length>0&&c.push(["__orphans__",[...l].sort(Ta)]),c.length===0&&c.push(["__nodes__",[]]);const d=[],m=c.length,u=Math.max(1,m-1)*Cl,h=r?0:80,g=r?Il:0;r&&d.push({id:r.id,type:"meshNode",position:{x:u/2,y:h},data:{graphNode:r},selected:!1,draggable:!1,selectable:!0}),c.forEach(([f,p],b)=>{const y=b*Cl,x=p.length>0?p:a.length>0?a:[];let I=g;x.forEach(N=>{d.push({id:N.id,type:"meshNode",position:{x:y,y:I},data:{graphNode:N},selected:!1,draggable:!1,selectable:!0});const j=[...n.get(N.id)??[]].sort(Ta);if(j.length>0){j.forEach((A,M)=>{d.push({id:A.id,type:"meshNode",position:{x:y+Oy,y:I+Al+M*Tl},data:{graphNode:A},selected:!1,draggable:!1,selectable:!0})}),I+=Al+j.length*Tl+Fy;return}I+=Il}),f==="__nodes__"&&a.length===0&&r&&d.push({id:`${r.id}__placeholder`,type:"meshNode",position:{x:y,y:g},data:{graphNode:{id:`${r.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:e.repoIdentity,branch:r.branch,upstream:null,upstreamStatus:null,machineLabel:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,source:{nodeId:`${r.id}__placeholder`,machineLabel:null,workspace:e.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}},selected:!1,draggable:!1,selectable:!1})});const k=e.edges.map(f=>({id:f.id,source:f.source,target:f.target,label:f.label,type:f.type==="worktreeLink"||f.type==="submoduleLink"?"smoothstep":"bezier",animated:f.type==="orphanLink",markerEnd:{type:em.ArrowClosed,width:f.type==="submoduleLink"?16:18,height:f.type==="submoduleLink"?16:18,color:Ml(f)},style:{stroke:Ml(f),strokeWidth:f.type==="orphanLink"?2.25:f.type==="submoduleLink"?1.7:f.type==="worktreeLink"?1.8:2,strokeDasharray:f.type==="orphanLink"?"5 4":f.type==="submoduleLink"?"4 3":void 0},labelStyle:{fill:"var(--text-secondary, #cbd5e1)",fontSize:10,fontWeight:600},labelBgStyle:{fill:"rgba(2, 6, 23, 0.86)",fillOpacity:1,stroke:"rgba(148, 163, 184, 0.2)"},labelBgPadding:[5,3],labelBgBorderRadius:6}));return{nodes:d,edges:k}}function Ml(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";default:return"#64748b"}}function qy({data:e}){const s=tm(),r=sm(),n=i.useRef(null),a=i.useMemo(()=>By(e),[e]),o=i.useMemo(()=>Ey(e),[e]);return i.useEffect(()=>{if(!s||e.nodes.length===0||n.current===a)return;let l=!1;const c=requestAnimationFrame(()=>{if(l)return;const d=o.length>0&&o.length<e.nodes.length;r.fitView({nodes:d?o.map(m=>({id:m})):void 0,padding:d?.2:.16,maxZoom:d?1.04:.96,duration:260}),n.current=a});return()=>{l=!0,cancelAnimationFrame(c)}},[e.nodes.length,o,a,s,r]),null}function mu({data:e,selectedNodeId:s=null,onNodeClick:r}){const n=i.useMemo(()=>Gy(e),[e]),a=i.useMemo(()=>$y(e),[e]),o=i.useMemo(()=>n.nodes.map(l=>({...l,selected:l.id===s})),[n.nodes,s]);return t.jsxs("div",{className:"relative h-full min-h-[520px] overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",children:[t.jsxs("div",{className:"absolute inset-x-3 top-3 z-10 flex flex-wrap items-center justify-between gap-2 text-[11px] text-slate-200",children:[t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsxs("span",{className:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1",children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),t.jsxs("span",{className:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1",children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&t.jsxs("span",{className:"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100",children:[e.stats.orphanNodes," need attention"]})]}),t.jsx("div",{className:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",children:"Focused on the main path first · drag or scroll to pan"})]}),t.jsxs(Yu,{nodes:o,edges:n.edges,nodeTypes:Vy,minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!1,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(l,c)=>r==null?void 0:r(c.data.graphNode),className:"h-full w-full",colorMode:"dark",proOptions:{hideAttribution:!0},children:[t.jsx(qy,{data:e}),a&&t.jsx(Xu,{className:"!bottom-4 !right-4 !bg-slate-950/85 !border !border-white/10 !rounded-xl",nodeColor:l=>uu(l.data.graphNode.health)}),t.jsx(Ju,{className:"!bottom-4 !left-4 !shadow-lg",showInteractive:!1}),t.jsx(Qu,{variant:Zu.Dots,gap:18,size:1.2,color:"rgba(148, 163, 184, 0.22)"})]})]})}function Tt({label:e,value:s}){return s==null||s===""?null:t.jsxs("div",{className:"flex justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",children:[t.jsx("span",{className:"text-slate-400",children:e}),t.jsx("span",{className:"break-all text-right font-medium text-slate-200",children:String(s)})]})}function Yy({health:e}){const s={online:"bg-green-500/10 text-green-400 border-green-500/20",dirty:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",degraded:"bg-red-500/10 text-red-400 border-red-500/20",wrong_branch:"bg-purple-500/10 text-purple-400 border-purple-500/20",offline:"bg-gray-500/10 text-gray-400 border-gray-500/20",unknown:"bg-gray-500/10 text-gray-400 border-gray-500/20"};return t.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] border ${s[e]||s.unknown}`,children:e})}function Xy(e){var a,o,l;if(e.type==="submoduleNode")return e.submoduleCommit?e.submoduleCommit.slice(0,7):null;const s=e.source;if("kind"in s)return null;const r=(a=s.git)!=null&&a.headCommit?s.git.headCommit.slice(0,7):null,n=((l=(o=s.git)==null?void 0:o.headMessage)==null?void 0:l.trim())||null;return!r&&!n?null:[r,n].filter(Boolean).join(" · ")}function Jy(e){if(!e.upstream)return null;switch(e.upstreamStatus){case"fresh":return"verified";case"stale":return"unverified (fetch failed)";case"unchecked":return"unverified";case"unavailable":return"unavailable";case"no_upstream":default:return null}}function pu({node:e,onClose:s}){if(!e)return t.jsx("div",{className:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",children:"Select a node to view details."});const r=e.type==="submoduleNode",n=Xy(e);return t.jsxs("div",{className:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"truncate text-xs font-semibold text-slate-100",children:e.label}),s&&t.jsx("button",{onClick:s,className:"text-xs text-slate-400 hover:text-slate-100",children:"✕"})]}),t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx(Yy,{health:e.health}),r&&t.jsx("span",{className:"rounded border border-violet-500/20 bg-violet-500/10 px-1.5 py-0.5 text-[10px] text-violet-200",children:"Submodule"}),e.dirty&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-yellow-500/10 text-yellow-400 border border-yellow-500/20",children:"Dirty"}),e.outOfSync&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Out of sync"}),e.hasConflicts&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Conflict"}),e.isOrphan&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Orphan"})]}),t.jsxs("div",{className:"flex flex-col gap-0.5 mt-1",children:[t.jsx(Tt,{label:"Workspace",value:e.workspace}),t.jsx(Tt,{label:"Branch",value:e.branch}),t.jsx(Tt,{label:"Upstream",value:r?null:e.upstream??null}),t.jsx(Tt,{label:"Upstream state",value:r?null:Jy(e)}),t.jsx(Tt,{label:"HEAD",value:n}),t.jsx(Tt,{label:"Submodule path",value:e.submodulePath??null}),t.jsx(Tt,{label:"Submodule commit",value:e.submoduleCommit??null}),t.jsx(Tt,{label:"Parent node",value:r&&(e.machineLabel||e.parentNodeId)||null}),t.jsx(Tt,{label:"Ahead",value:!r&&(!e.upstream||e.upstreamStatus==="fresh")&&e.ahead>0?`+${e.ahead}`:null}),t.jsx(Tt,{label:"Behind",value:!r&&(!e.upstream||e.upstreamStatus==="fresh")&&e.behind>0?`-${e.behind}`:null}),t.jsx(Tt,{label:"Dirty files",value:e.dirtyFiles>0?e.dirtyFiles:null}),t.jsx(Tt,{label:"Active sessions",value:e.activeSessionCount>0?e.activeSessionCount:null}),t.jsx(Tt,{label:"Providers",value:r?null:e.providers.join(", ")||null}),t.jsx(Tt,{label:"Error",value:e.error??null})]}),e.orphanReasons.length>0&&t.jsxs("div",{className:"mt-1",children:[t.jsx("div",{className:"text-[10px] font-semibold text-red-400 mb-1",children:"Orphan reasons"}),t.jsx("ul",{className:"list-disc list-inside text-[10px] text-red-300 space-y-0.5",children:e.orphanReasons.map((a,o)=>t.jsx("li",{children:a},o))})]}),e.nextStepHint&&t.jsxs("div",{className:"mt-1 px-2 py-1.5 rounded bg-blue-500/10 border border-blue-500/20 text-[10px] text-blue-300",children:["💡 ",e.nextStepHint]})]})}const Ll=new Set(["pending","assigned"]),Qy={pending:0,assigned:0},Zy={recentFailures:0};function Ze({label:e,tone:s="default"}){const r={default:"border-white/10 bg-white/[0.04] text-slate-200",good:"border-emerald-400/20 bg-emerald-500/10 text-emerald-200",warn:"border-amber-400/20 bg-amber-500/10 text-amber-100",danger:"border-rose-400/20 bg-rose-500/10 text-rose-100",info:"border-sky-400/20 bg-sky-500/10 text-sky-100"};return t.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${r[s]||r.default}`,children:e})}function cr({title:e,subtitle:s,children:r,className:n=""}){return t.jsxs("section",{className:`rounded-2xl border border-white/10 bg-white/[0.04] ${n}`,children:[t.jsxs("div",{className:"border-b border-white/10 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-white",children:e}),s&&t.jsx("div",{className:"mt-1 text-xs text-slate-400",children:s})]}),t.jsx("div",{className:"px-4 py-3",children:r})]})}function Ge({label:e,value:s}){return t.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",children:[t.jsx("span",{className:"text-slate-400",children:e}),t.jsx("span",{className:"max-w-[65%] break-all text-right text-slate-100",children:s})]})}function Ft({label:e,onClick:s,tone:r="default"}){const n={default:"border-white/10 bg-white/[0.04] text-slate-200 hover:bg-white/[0.08]",info:"border-sky-400/25 bg-sky-500/10 text-sky-100 hover:bg-sky-500/16",success:"border-emerald-400/25 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/16"};return t.jsx("button",{type:"button",onClick:s,className:`rounded-full border px-2.5 py-1 text-[11px] transition ${n[r]||n.default}`,children:e})}function ts(e){if(!e)return null;const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()}function Ms(e){if(!e)return null;const s=new Date(e);return Number.isNaN(s.getTime())?null:s.toLocaleString()}function Aa(e){switch(e){case"completed":return"good";case"failed":case"cancelled":return"danger";case"assigned":return"info";case"pending":return"warn";default:return"default"}}function Rl(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}function sn(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function _l(e){if(!e)return"default";if(e.state==="self")return"info";if(e.transport==="direct"&&e.state==="connected")return"good";if(e.transport==="relay"&&e.state==="connected")return"info";switch(e.state){case"connected":return"good";case"connecting":return"warn";case"disconnected":case"failed":case"closed":return"danger";default:return"default"}}function Ma(e){return e?e.state==="self"?"mesh self":e.transport==="direct"&&e.state==="connected"?"mesh direct":e.transport==="relay"&&e.state==="connected"?"mesh relay":!e.reported&&e.source==="not_reported"?"mesh unknown / not reported":`mesh ${e.state}`:"mesh unknown"}function La(e){return e===!0?"yes":e===!1?"no":"unknown"}function Pl(e,s){if(!s)return null;const r=new URLSearchParams;return e&&r.set("daemonId",e),r.set("targetSessionId",s),`/dashboard?${r.toString()}`}function Dl(e){const s=e.git;if(!s)return"No git probe";const r=(s.staged??0)+(s.modified??0)+(s.untracked??0)+(s.deleted??0)+(s.renamed??0),n=[];s.branch&&n.push(s.branch),s.upstream&&s.upstreamStatus!=="fresh"&&n.push("upstream unverified"),s.upstreamStatus==="fresh"&&((s.ahead??0)>0||(s.behind??0)>0)&&n.push(`↑${s.ahead??0}/↓${s.behind??0}`),r>0&&n.push(`${r} dirty`);const a=(s.submodules??[]).filter(l=>l.dirty),o=(s.submodules??[]).filter(l=>l.outOfSync||l.error);return a.length>0&&n.push(`${a.length} submodule dirty`),o.length>0&&n.push(`${o.length} submodule drift`),s.hasConflicts&&n.push("conflicts"),n.join(" · ")||"Clean"}function e0(e){var r;const s=[];for(const n of e.nodes){const a=n.activeSessionDetails&&n.activeSessionDetails.length>0?n.activeSessionDetails:(n.activeSessions??[]).map(o=>({sessionId:o,workspace:n.workspace,isCached:!0}));for(const o of a)s.push({nodeId:n.nodeId,machineLabel:n.machineLabel,workspace:n.workspace,branch:((r=n.git)==null?void 0:r.branch)??null,nodeHealth:n.health,session:o})}return s}function Ra(e){const s=e.assignedNodeId||e.targetNodeId||"unbound",r=e.assignedSessionId||e.targetSessionId||"no session";return`${s} · ${r}`}function rn(e){return e.assignedNodeId||e.targetNodeId||null}function _a(e){var s;return e.assignedSessionId||e.targetSessionId||((s=e.autoLaunch)==null?void 0:s.sessionId)||null}function Pa(e){var s,r;return((s=e.nodes.find(n=>n.type!=="submoduleNode"))==null?void 0:s.id)??((r=e.nodes[0])==null?void 0:r.id)??null}function wr(e){return e?e.slice(0,7):null}function t0(e,s){var o,l,c;const r=wr((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(l=e==null?void 0:e.git)==null?void 0:l.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=s[0];return a?[wr(a.commit),a.message].filter(Boolean).join(" · "):null}function s0(e){const s=(e==null?void 0:e.result)??e,r=(s==null?void 0:s.log)??(e==null?void 0:e.log)??s;return Array.isArray(r==null?void 0:r.entries)?r.entries:[]}function r0({graph:e,status:s,emptyMessage:r="No live mesh graph is available for this coordinator yet.",daemonId:n=null,sendDaemonCommand:a=null}){var O,V,X,ye,he,ne,pe,ke,Se,G,be,fe,ve;const o=ls(),[l,c]=i.useState(()=>Pa(e)),[d,m]=i.useState(()=>{const P=Pa(e);return P?{kind:"node",nodeId:P}:null}),[u,h]=i.useState("active"),[g,k]=i.useState({}),f=i.useMemo(()=>new Map(s.nodes.map(P=>[P.nodeId,P])),[s.nodes]),p=i.useMemo(()=>new Map(e.nodes.map(P=>[P.id,P])),[e.nodes]),b=((O=s.queue)==null?void 0:O.tasks)??[],y=((V=s.queue)==null?void 0:V.summary)??null,x=(y==null?void 0:y.activeCounts)??Qy,I=((X=s.ledger)==null?void 0:X.summary)??Zy,N=i.useMemo(()=>e0(s),[s]),j=i.useMemo(()=>{const P=new Map;for(const me of N){const q=me.session.state||me.session.lifecycle||"unknown";P.set(q,(P.get(q)??0)+1)}return[...P.entries()].sort((me,q)=>q[1]-me[1])},[N]),A=i.useMemo(()=>u==="all"?b:u==="active"?b.filter(P=>Ll.has(P.status)):b.filter(P=>!Ll.has(P.status)),[u,b]);i.useEffect(()=>{if(!l||!p.has(l)){const P=Pa(e);c(P),m(P?{kind:"node",nodeId:P}:null)}},[e,p,l]);const M=l?p.get(l)??null:null,v=l?f.get(l)??null:null,w=(d==null?void 0:d.kind)==="queue"?b.find(P=>P.id===d.taskId)??null:null,B=(d==null?void 0:d.kind)==="session"?N.find(P=>P.nodeId===d.nodeId&&P.session.sessionId===d.sessionId)??null:null,R=i.useMemo(()=>N.filter(P=>P.nodeId===l),[l,N]),T=i.useMemo(()=>b.filter(P=>rn(P)===l),[b,l]),H=(B==null?void 0:B.session.workspace)||(B==null?void 0:B.workspace)||(M==null?void 0:M.workspace)||null,E=H?g[H]??null:null,D=t0(v,(E==null?void 0:E.entries)??[]),S=i.useCallback(P=>{P&&o(zt(P),{state:{openRemoteForTabKey:P}})},[o]),C=i.useCallback((P,me)=>{c(P),m({kind:"session",nodeId:P,sessionId:me})},[]),W=i.useCallback(P=>{c(P),m({kind:"node",nodeId:P})},[]);i.useEffect(()=>{if(!H||!n||!a)return;const P=g[H];if(P!=null&&P.loading||P&&(P.entries.length>0||P.error))return;let me=!1;return k(q=>{var de;return{...q,[H]:{loading:!0,error:null,entries:((de=q[H])==null?void 0:de.entries)??[]}}}),a(n,"git_log",{workspace:H,limit:5}).then(q=>{me||k(de=>({...de,[H]:{loading:!1,error:null,entries:s0(q)}}))}).catch(q=>{me||k(de=>({...de,[H]:{loading:!1,error:q instanceof Error?q.message:"git_log failed",entries:[]}}))}),()=>{me=!0}},[n,g,H,a]);const _=[...e.warnings??[],...s.nodes.filter(P=>P.machineStatus&&P.machineStatus!=="online").map(P=>`${P.machineLabel}: ${P.machineStatus}`)];return t.jsxs("div",{className:"flex min-h-0 flex-col gap-4 xl:flex-row",children:[t.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:t.jsxs("div",{className:"min-h-0 flex-1 rounded-[28px] border border-white/10 bg-white/[0.03] p-3 sm:p-4",style:{minHeight:420},children:[t.jsxs("div",{className:"mb-3 rounded-2xl border border-white/10 bg-slate-950/45 px-3.5 py-3",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 text-xs text-slate-200",children:[t.jsx(Ze,{label:`${e.stats.totalNodes} nodes`,tone:"default"}),t.jsx(Ze,{label:`${e.stats.totalActiveSessions} active sessions`,tone:e.stats.totalActiveSessions>0?"info":"default"}),t.jsx(Ze,{label:`${e.stats.dirtyNodes} dirty`,tone:e.stats.dirtyNodes>0?"warn":"good"}),t.jsx(Ze,{label:`${e.stats.offlineNodes} offline`,tone:e.stats.offlineNodes>0?"danger":"good"}),t.jsx(Ze,{label:`${(y==null?void 0:y.active)??0} active queue`,tone:((y==null?void 0:y.active)??0)>0?"info":"default"}),t.jsx(Ze,{label:`${I.recentFailures} recent failures`,tone:I.recentFailures>0?"danger":"good"}),j.length===0?t.jsx(Ze,{label:"no session metadata"}):j.slice(0,2).map(([P,me])=>t.jsx(Ze,{label:`${me} ${P}`,tone:sn(P)},P))]}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-xs text-slate-300",children:[t.jsx(Ze,{label:"Anchor = inferred default branch",tone:"info"}),t.jsx(Ze,{label:"Peer link = same-branch worktree",tone:"default"}),t.jsx(Ze,{label:"Submodule link = child checkout under a parent node",tone:"warn"})]}),t.jsx("div",{className:"mt-3 text-xs text-slate-400",children:"Tap a node to inspect workspace, session, and git details. Launch readiness and mesh transport details stay in the same drill-down. Queue rows and session rows are also selectable for drill-down. First open now focuses on the default-branch path; drag or scroll only when you want the wider topology."}),_.length>0&&t.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:_.map(P=>t.jsx("span",{className:"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100",children:P},P))})]}),e.nodes.length>0?t.jsx(mu,{data:e,selectedNodeId:l,onNodeClick:P=>{c(P.id),m({kind:"node",nodeId:P.id})}}):t.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:r})]})}),t.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-4 xl:w-[420px]",children:[t.jsx(cr,{title:"Selected detail",subtitle:"Node, session, or queue item drill-down.",children:t.jsx("div",{className:"flex flex-col gap-3",children:(d==null?void 0:d.kind)==="queue"&&w?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx(Ze,{label:w.status,tone:Aa(w.status)}),t.jsx(Ze,{label:w.id.slice(0,8),tone:"default"})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[rn(w)&&t.jsx(Ft,{label:"View node",onClick:()=>W(rn(w)||"")}),(()=>{const P=_a(w);if(!P)return null;const me=N.find(q=>q.session.sessionId===P)??null;return t.jsxs(t.Fragment,{children:[me&&t.jsx(Ft,{label:"View session",onClick:()=>C(me.nodeId,me.session.sessionId)}),t.jsx(Ft,{label:"Open chat",tone:"info",onClick:()=>S(P)})]})})()]}),t.jsx(Ge,{label:"Message",value:w.message}),t.jsx(Ge,{label:"Routing",value:Ra(w)}),t.jsx(Ge,{label:"Created",value:ts(w.createdAt)??"unknown"}),t.jsx(Ge,{label:"Updated",value:ts(w.updatedAt)??"unknown"}),t.jsx(Ge,{label:"Requeues",value:w.requeueCount??0}),t.jsx(Ge,{label:"Auto-launch",value:w.autoLaunch?`${w.autoLaunch.status}${w.autoLaunch.providerType?` · ${w.autoLaunch.providerType}`:""}`:"none"}),(()=>{var de,ae,xe;const P=w.assignedSessionId||w.targetSessionId||((de=w.autoLaunch)==null?void 0:de.sessionId)||null,me=w.assignedNodeId||w.targetNodeId||((ae=w.autoLaunch)==null?void 0:ae.nodeId)||null,q=Pl(me?(xe=f.get(me))==null?void 0:xe.daemonId:null,P);return q?t.jsx("a",{href:q,className:"inline-flex w-fit items-center rounded-full border border-sky-400/30 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-100 transition hover:bg-sky-500/20",children:"Open linked dashboard chat"}):null})(),w.cancelReason&&t.jsx(Ge,{label:"Cancel reason",value:w.cancelReason}),w.requeueReason&&t.jsx(Ge,{label:"Requeue reason",value:w.requeueReason})]}):(d==null?void 0:d.kind)==="session"&&B?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx(Ze,{label:B.session.state||B.session.lifecycle||"unknown",tone:sn(B.session.state||B.session.lifecycle)}),B.session.providerType&&t.jsx(Ze,{label:B.session.providerType,tone:"info"}),B.session.isCached&&t.jsx(Ze,{label:"cached",tone:"default"})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx(Ft,{label:"View node",onClick:()=>W(B.nodeId)}),t.jsx(Ft,{label:"Open chat",tone:"info",onClick:()=>S(B.session.sessionId)})]}),t.jsx(Ge,{label:"Session id",value:B.session.sessionId}),t.jsx(Ge,{label:"Node",value:B.machineLabel}),t.jsx(Ge,{label:"Workspace",value:B.workspace}),t.jsx(Ge,{label:"Branch",value:B.branch??"unknown"}),t.jsx(Ge,{label:"Node health",value:B.nodeHealth}),t.jsx(Ge,{label:"Lifecycle",value:B.session.lifecycle??"unknown"}),B.session.surfaceKind&&t.jsx(Ge,{label:"Surface",value:B.session.surfaceKind}),B.session.recoveryState&&t.jsx(Ge,{label:"Recovery",value:B.session.recoveryState}),B.session.lastActivityAt&&t.jsx(Ge,{label:"Last activity",value:ts(B.session.lastActivityAt)??B.session.lastActivityAt}),(()=>{var me;const P=Pl((me=f.get(B.nodeId))==null?void 0:me.daemonId,B.session.sessionId);return P?t.jsx("a",{href:P,className:"inline-flex w-fit items-center rounded-full border border-sky-400/30 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-100 transition hover:bg-sky-500/20",children:"Open dashboard chat"}):null})(),t.jsxs("div",{className:"rounded-xl border border-white/10 bg-slate-950/40 p-3",children:[t.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Git context"}),t.jsxs("div",{className:"flex flex-col gap-2 text-xs text-slate-300",children:[t.jsx("div",{children:D||"HEAD subject not present in cached mesh_status."}),(E==null?void 0:E.loading)&&t.jsx("div",{className:"text-slate-500",children:"Loading recent commits…"}),(E==null?void 0:E.error)&&t.jsxs("div",{className:"text-amber-200",children:["Recent history unavailable: ",E.error]}),((E==null?void 0:E.entries)??[]).slice(0,5).map(P=>t.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.03] px-2.5 py-2",children:[t.jsxs("div",{className:"font-medium text-slate-100",children:[wr(P.commit)," · ",P.message]}),t.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[P.authorName||"unknown author",Ms(P.committedAt)?` · ${Ms(P.committedAt)}`:""]})]},P.commit))]})]})]}):M?t.jsxs(t.Fragment,{children:[t.jsx(pu,{node:M}),v&&t.jsxs("div",{className:"rounded-xl border border-white/10 bg-slate-950/40 p-3",children:[t.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[t.jsx(Ze,{label:v.health,tone:Rl(v.health)}),v.machineStatus&&t.jsx(Ze,{label:v.machineStatus,tone:v.machineStatus==="online"?"good":"warn"}),t.jsx(Ze,{label:`launchReady ${La(v.launchReady)}`,tone:v.launchReady?"good":"warn"}),t.jsx(Ze,{label:Ma(v.connection),tone:_l(v.connection)}),v.worktreeBranch&&t.jsx(Ze,{label:v.worktreeBranch,tone:"info"})]}),t.jsxs("div",{className:"flex flex-col gap-0.5",children:[t.jsx(Ge,{label:"Repo root",value:v.repoRoot??v.workspace}),t.jsx(Ge,{label:"Provider(s)",value:(v.providers??[]).join(", ")||"none"}),t.jsx(Ge,{label:"Provider priority",value:(v.providerPriority??[]).join(", ")||"not configured"}),t.jsx(Ge,{label:"Drift",value:Dl(v)}),t.jsx(Ge,{label:"HEAD",value:D??"Not available"}),t.jsx(Ge,{label:"Daemon",value:v.daemonId??"unknown"}),t.jsx(Ge,{label:"Machine",value:v.machineId??v.machineLabel}),t.jsx(Ge,{label:"Launch ready",value:La(v.launchReady)}),t.jsx(Ge,{label:"Mesh connection",value:Ma(v.connection)}),t.jsx(Ge,{label:"Transport",value:((ye=v.connection)==null?void 0:ye.transport)??"unknown"}),t.jsx(Ge,{label:"Connection source",value:((he=v.connection)==null?void 0:he.source)??"unknown"}),t.jsx(Ge,{label:"Last seen",value:ts(v.lastSeenAt)??v.lastSeenAt??"not reported"}),t.jsx(Ge,{label:"Updated",value:ts(v.updatedAt)??v.updatedAt??"not reported"}),((ne=v.connection)==null?void 0:ne.lastConnectedAt)&&t.jsx(Ge,{label:"Last connected",value:ts(v.connection.lastConnectedAt)??v.connection.lastConnectedAt}),((pe=v.connection)==null?void 0:pe.lastCommandAt)&&t.jsx(Ge,{label:"Last mesh command",value:ts(v.connection.lastCommandAt)??v.connection.lastCommandAt}),((ke=v.connection)==null?void 0:ke.reason)&&t.jsx(Ge,{label:"Connection reason",value:v.connection.reason}),t.jsx(Ge,{label:"Sessions",value:v.activeSessions.length}),v.error&&t.jsx(Ge,{label:"Error",value:v.error})]}),R.length>0&&t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Active sessions"}),t.jsx("div",{className:"flex flex-col gap-2",children:R.map(P=>{const me=P.session.state||P.session.lifecycle||"unknown";return t.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200",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:"truncate font-medium text-slate-100",children:P.session.title||P.session.sessionId}),t.jsxs("div",{className:"mt-1 truncate text-[11px] text-slate-400",children:[P.session.providerType||"unknown provider"," · ",me]})]}),t.jsx(Ze,{label:me,tone:sn(me)})]}),t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[t.jsx(Ft,{label:"View session",onClick:()=>C(P.nodeId,P.session.sessionId)}),t.jsx(Ft,{label:"Open chat",tone:"info",onClick:()=>S(P.session.sessionId)})]})]},`${P.nodeId}:${P.session.sessionId}`)})})]}),T.length>0&&t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Related queue items"}),t.jsx("div",{className:"flex flex-col gap-2",children:T.map(P=>{const me=_a(P),q=me?N.find(de=>de.session.sessionId===me)??null:null;return t.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200",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:"truncate font-medium text-slate-100",children:P.message}),t.jsx("div",{className:"mt-1 truncate text-[11px] text-slate-400",children:Ra(P)})]}),t.jsx(Ze,{label:P.status,tone:Aa(P.status)})]}),t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[t.jsx(Ft,{label:"View queue detail",onClick:()=>m({kind:"queue",taskId:P.id})}),q&&t.jsx(Ft,{label:"View session",onClick:()=>C(q.nodeId,q.session.sessionId)}),me&&t.jsx(Ft,{label:"Open chat",tone:"info",onClick:()=>S(me)})]})]},P.id)})})]}),t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Recent commits"}),t.jsxs("div",{className:"flex flex-col gap-2",children:[(E==null?void 0:E.loading)&&t.jsx("div",{className:"text-xs text-slate-500",children:"Loading recent commits…"}),(E==null?void 0:E.error)&&t.jsxs("div",{className:"text-xs text-amber-200",children:["Recent history unavailable: ",E.error]}),!(E!=null&&E.loading)&&!(E!=null&&E.error)&&((E==null?void 0:E.entries)??[]).length===0&&t.jsx("div",{className:"text-xs text-slate-500",children:"Recent commit history not available from the current mesh snapshot yet."}),((E==null?void 0:E.entries)??[]).slice(0,5).map(P=>t.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200",children:[t.jsxs("div",{className:"font-medium text-slate-100",children:[wr(P.commit)," · ",P.message]}),t.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[P.authorName||"unknown author",Ms(P.committedAt)?` · ${Ms(P.committedAt)}`:""]})]},P.commit))]})]}),(((G=(Se=v.git)==null?void 0:Se.submodules)==null?void 0:G.length)??0)>0&&t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Submodules"}),t.jsx("div",{className:"flex flex-col gap-2",children:(((be=v.git)==null?void 0:be.submodules)??[]).map(P=>t.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"font-medium",children:P.path}),P.dirty&&t.jsx(Ze,{label:"dirty",tone:"warn"}),(P.outOfSync||P.error)&&t.jsx(Ze,{label:"drift",tone:"danger"})]}),t.jsx("div",{className:"mt-1 break-all text-[11px] text-slate-400",children:P.repoPath}),t.jsx("div",{className:"mt-1 text-[11px] text-slate-500",children:"Select the submodule node in the graph for its own HEAD and recent history."}),P.error&&t.jsx("div",{className:"mt-1 text-[11px] text-rose-200",children:P.error})]},`${v.nodeId}:${P.path}`))})]})]}),!v&&t.jsxs("div",{className:"rounded-xl border border-white/10 bg-slate-950/40 p-3",children:[t.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Git context"}),t.jsx("div",{className:"text-xs text-slate-300",children:D??"No daemon-owned node status is attached to this graph node."}),t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Recent commits"}),t.jsxs("div",{className:"flex flex-col gap-2",children:[(E==null?void 0:E.loading)&&t.jsx("div",{className:"text-xs text-slate-500",children:"Loading recent commits…"}),(E==null?void 0:E.error)&&t.jsxs("div",{className:"text-xs text-amber-200",children:["Recent history unavailable: ",E.error]}),!(E!=null&&E.loading)&&!(E!=null&&E.error)&&((E==null?void 0:E.entries)??[]).length===0&&t.jsx("div",{className:"text-xs text-slate-500",children:"Recent commit history not available for this detached graph node yet."}),((E==null?void 0:E.entries)??[]).slice(0,5).map(P=>t.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200",children:[t.jsxs("div",{className:"font-medium text-slate-100",children:[wr(P.commit)," · ",P.message]}),t.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[P.authorName||"unknown author",Ms(P.committedAt)?` · ${Ms(P.committedAt)}`:""]})]},P.commit))]})]})]})]}):t.jsx("div",{className:"text-xs text-slate-400",children:"Select a node, session, or queue item."})})}),t.jsxs(cr,{title:"Queue",subtitle:"Active work plus recent history from mesh_status.",children:[t.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:["active","history","all"].map(P=>t.jsx("button",{type:"button",onClick:()=>h(P),className:`rounded-full border px-3 py-1 text-xs transition ${u===P?"border-sky-400/30 bg-sky-500/10 text-sky-100":"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]"}`,children:P},P))}),t.jsxs("div",{className:"mb-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4 xl:grid-cols-2",children:[t.jsxs("div",{className:"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300",children:["Active ",t.jsx("span",{className:"ml-1 text-white",children:(y==null?void 0:y.active)??0})]}),t.jsxs("div",{className:"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300",children:["Pending ",t.jsx("span",{className:"ml-1 text-white",children:x.pending})]}),t.jsxs("div",{className:"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300",children:["Assigned ",t.jsx("span",{className:"ml-1 text-white",children:x.assigned})]}),t.jsxs("div",{className:"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300",children:["History ",t.jsx("span",{className:"ml-1 text-white",children:(y==null?void 0:y.historical)??0})]})]}),t.jsx("div",{className:"max-h-[24vh] overflow-y-auto pr-1",children:A.length===0?t.jsx("div",{className:"text-xs text-slate-400",children:"No queue items for this filter."}):t.jsx("div",{className:"flex flex-col gap-2",children:A.map(P=>{const me=_a(P),q=me?N.find(ae=>ae.session.sessionId===me)??null:null,de=rn(P);return t.jsxs("button",{type:"button",onClick:()=>m({kind:"queue",taskId:P.id}),className:`rounded-xl border px-3 py-2 text-left transition ${(d==null?void 0:d.kind)==="queue"&&d.taskId===P.id?"border-sky-400/30 bg-sky-500/10":"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]"}`,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:"truncate text-xs font-medium text-white",children:P.message}),t.jsx("div",{className:"mt-1 truncate text-[11px] text-slate-400",children:Ra(P)})]}),t.jsx(Ze,{label:P.status,tone:Aa(P.status)})]}),(de||q||me)&&t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[de&&t.jsx("button",{type:"button",onClick:ae=>{ae.stopPropagation(),W(de)},className:"text-[11px] text-slate-300 underline underline-offset-2 transition hover:text-white",children:"View node"}),q&&t.jsx("button",{type:"button",onClick:ae=>{ae.stopPropagation(),C(q.nodeId,q.session.sessionId)},className:"text-[11px] text-slate-300 underline underline-offset-2 transition hover:text-white",children:"View session"}),me&&t.jsx("button",{type:"button",onClick:ae=>{ae.stopPropagation(),S(me)},className:"text-[11px] text-sky-200 underline underline-offset-2 transition hover:text-white",children:"Open chat"})]})]},P.id)})})})]}),t.jsx(cr,{title:"Sessions",subtitle:"Node-level active session roster.",children:t.jsx("div",{className:"max-h-[22vh] overflow-y-auto pr-1",children:N.length===0?t.jsx("div",{className:"text-xs text-slate-400",children:"No active session metadata in this mesh snapshot."}):t.jsx("div",{className:"flex flex-col gap-2",children:N.map(P=>{const me=P.session.state||P.session.lifecycle||"unknown";return t.jsx("button",{type:"button",onClick:()=>{c(P.nodeId),m({kind:"session",nodeId:P.nodeId,sessionId:P.session.sessionId})},className:`rounded-xl border px-3 py-2 text-left transition ${(d==null?void 0:d.kind)==="session"&&d.nodeId===P.nodeId&&d.sessionId===P.session.sessionId?"border-sky-400/30 bg-sky-500/10":"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]"}`,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:"truncate text-xs font-medium text-white",children:P.machineLabel}),t.jsxs("div",{className:"mt-1 truncate text-[11px] text-slate-400",children:[P.session.title||P.session.providerType||"unknown provider"," · ",P.branch||"no branch"]})]}),t.jsxs("div",{className:"flex flex-col items-end gap-1",children:[t.jsx(Ze,{label:me,tone:sn(me)}),t.jsx("button",{type:"button",onClick:q=>{q.stopPropagation(),S(P.session.sessionId)},className:"text-[11px] text-sky-200 underline underline-offset-2 transition hover:text-white",children:"Open chat"})]})]})},`${P.nodeId}:${P.session.sessionId}`)})})})}),t.jsx(cr,{title:"Nodes",subtitle:"Health, branch, drift, and provider view per node.",children:t.jsx("div",{className:"max-h-[22vh] overflow-y-auto pr-1",children:t.jsx("div",{className:"flex flex-col gap-2",children:s.nodes.map(P=>t.jsx("button",{type:"button",onClick:()=>{c(P.nodeId),m({kind:"node",nodeId:P.nodeId})},className:`rounded-xl border px-3 py-2 text-left transition ${(d==null?void 0:d.kind)==="node"&&d.nodeId===P.nodeId?"border-sky-400/30 bg-sky-500/10":"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]"}`,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:"truncate text-xs font-medium text-white",children:P.machineLabel}),t.jsx("div",{className:"mt-1 truncate text-[11px] text-slate-400",children:Dl(P)}),t.jsx("div",{className:"mt-1 truncate text-[11px] text-slate-500",children:(P.providers??[]).join(", ")||"no provider metadata"}),t.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[t.jsx(Ze,{label:`launchReady ${La(P.launchReady)}`,tone:P.launchReady?"good":"warn"}),t.jsx(Ze,{label:Ma(P.connection),tone:_l(P.connection)})]})]}),t.jsxs("div",{className:"flex flex-col items-end gap-1",children:[t.jsx(Ze,{label:P.health,tone:Rl(P.health)}),P.machineStatus&&t.jsx(Ze,{label:P.machineStatus,tone:P.machineStatus==="online"?"good":"warn"}),P.activeSessions.length>0&&t.jsx(Ze,{label:`${P.activeSessions.length} sessions`,tone:"info"})]})]})},P.nodeId))})})}),t.jsx(cr,{title:"Recent mesh events",subtitle:"Read-only ledger tail from mesh_status.",children:t.jsx("div",{className:"max-h-[18vh] overflow-y-auto pr-1",children:(((fe=s.ledger)==null?void 0:fe.entries)??[]).length===0?t.jsx("div",{className:"text-xs text-slate-400",children:"No recent ledger entries."}):t.jsx("div",{className:"flex flex-col gap-2",children:(((ve=s.ledger)==null?void 0:ve.entries)??[]).map(P=>t.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2 text-xs text-slate-200",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("span",{className:"font-medium text-white",children:P.kind}),t.jsx("span",{className:"text-[11px] text-slate-500",children:ts(P.timestamp)??P.timestamp})]}),t.jsx("div",{className:"mt-1 truncate text-[11px] text-slate-400",children:P.nodeId||P.sessionId||P.providerType||"mesh-wide event"})]},P.id))})})})]})]})}function n0(e){const s=(e==null?void 0:e.result)??e,r=[e==null?void 0:e.status,s==null?void 0:s.status,s,e];for(const n of r)if(n&&Array.isArray(n.nodes)&&typeof n.meshId=="string")return n;return null}function a0({activeConv:e,sendDaemonCommand:s,onClose:r}){var N;const n=typeof((N=e.settings)==null?void 0:N.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,o=Dd(),[l,c]=i.useState(null),[d,m]=i.useState(null),[u,h]=i.useState(!1),[g,k]=i.useState(null),[f,p]=i.useState(null),b=i.useCallback(async()=>{if(!a||!n){k("This coordinator does not expose a live mesh id."),c(null),m(null);return}h(!0),k(null);try{const j=o!=null&&o.loadMeshStatus?await o.loadMeshStatus(a,n):await s(a,"mesh_status",{meshId:n}),A=n0(j);if(!A){c(null),m(null),k("mesh_status returned an unexpected payload.");return}const M=cu(A);m(A),c(M),p(A.refreshedAt||new Date().toISOString())}catch(j){c(null),m(null),k(j instanceof Error?j.message:"Failed to load live mesh status")}finally{h(!1)}},[a,n,o,s]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const j=A=>{A.key==="Escape"&&r()};return window.addEventListener("keydown",j),()=>window.removeEventListener("keydown",j)},[r]);const y=(l==null?void 0:l.meshName)||(d==null?void 0:d.meshName)||n||"Repo Mesh",x=f?new Date(f).toLocaleTimeString():null,I=i.useMemo(()=>u?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[u]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",onClick:r,children:t.jsxs("div",{role:"dialog","aria-modal":"true",className:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",onClick:j=>j.stopPropagation(),children:[t.jsxs("div",{className:"flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",children:[t.jsx("div",{className:"min-w-0 flex-1",children:t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:t.jsx(rs,{size:18})}),t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("h2",{className:"truncate text-lg font-semibold text-white md:text-xl",children:y}),t.jsx("span",{className:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",children:"Mesh observability"})]}),t.jsxs("p",{className:"mt-1 truncate text-sm text-slate-400",children:[dt(e),e.workspaceName?` · ${e.workspaceName}`:"",l!=null&&l.repoIdentity?` · ${l.repoIdentity}`:""]})]})]})}),t.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[x&&t.jsxs("span",{className:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",children:["Refreshed ",x]}),t.jsx("button",{type:"button",onClick:b,disabled:u,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:u?"Refreshing…":"Refresh"}),t.jsx("button",{type:"button",onClick:r,className:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white","aria-label":"Close mesh graph",children:t.jsx(vt,{size:16})})]})]}),g&&t.jsx("div",{className:"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5",children:g}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 md:px-5 md:py-5",children:l&&d?t.jsx(r0,{graph:l,status:d,emptyMessage:I,daemonId:a,sendDaemonCommand:s}):t.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",children:I})})]})})}function o0(e,s){const{sendCommand:r}=wt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);i.useEffect(()=>{if(!e||!s){a(null);return}l(!0),r(e,"git_remote_url",{workspace:s}).then(d=>{const m=(d==null?void 0:d.result)??d;a(typeof(m==null?void 0:m.remoteUrl)=="string"?m.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>l(!1))},[e,s,r]);const c=i0(n);return{remoteUrl:n,githubUrl:c,loading:o}}function i0(e){if(!e)return null;const s=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(s)return`https://github.com/${s[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const fu=5e3;function l0(e){return`git:${e}`}function c0({workspace:e,includeDiffSummary:s=!1,intervalMs:r=fu}){return{type:"subscribe",topic:"workspace.git",key:l0(e),params:{workspace:e,includeDiffSummary:s,intervalMs:r}}}function oi(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Is(e,s){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const r=e;if(typeof r.error=="string"&&r.error.trim())return r.error;if(typeof r.message=="string"&&r.message.trim())return r.message}return s}function d0(e){const s=oi(e);return(s==null?void 0:s.success)===!1?{status:null,error:Is(s,"Git status request failed")}:s!=null&&s.status?{status:s.status,error:null}:{status:null,error:Is(s,"Git status response did not include status")}}function u0(e){const s=oi(e);return(s==null?void 0:s.success)===!1?{diffSummary:null,error:Is(s,"Git diff summary request failed")}:s!=null&&s.diffSummary?{diffSummary:s.diffSummary,error:null}:{diffSummary:null,error:Is(s,"Git diff summary response did not include diffSummary")}}function Da(e){return e===void 0||typeof e=="boolean"}function m0(e){if(!e||typeof e!="object")return!1;const s=e;return typeof s.path=="string"&&typeof s.diff=="string"&&Da(s.binary)&&Da(s.truncated)&&Da(s.staged)}function p0(e){const s=oi(e);return(s==null?void 0:s.success)===!1?{diff:null,error:Is(s,"Git file diff request failed")}:m0(s==null?void 0:s.diff)?{diff:s.diff,error:null}:{diff:null,error:Is(s,"Git file diff response did not include a valid diff object")}}function f0({daemonId:e,workspace:s,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=fu}){const{sendCommand:o,sendData:l}=wt(),c=typeof s=="string"?s.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[h,g]=i.useState(null),[k,f]=i.useState(!1),[p,b]=i.useState(null),y=i.useCallback(async()=>{if(!(!d||!e||!c)){f(!0),b(null);try{const I=d0(await o(e,"git_status",{workspace:c}));if(I.error){u(null),g(null),b(I.error);return}if(u(I.status),!n){g(null);return}const N=u0(await o(e,"git_diff_summary",{workspace:c}));if(N.error){g(null),b(N.error);return}g(N.diffSummary)}catch(I){b(Is(I,"Git status request failed"))}finally{f(!1)}}},[d,e,n,o,c]),x=i.useMemo(()=>c?c0({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!x){u(null),g(null),f(!1),b(null);return}const I=l?Xt.subscribe({sendData:l},e,x,N=>{var j,A;N.workspace===c&&(u(N.status),g(N.diffSummary??null),b(((j=N.status)==null?void 0:j.error)||((A=N.diffSummary)==null?void 0:A.error)||null),f(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{I==null||I()}},[d,e,y,x,l,c]),{status:m,diffSummary:h,loading:k,error:p,refresh:y}}const h0={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},x0={added:"text-emerald-400",modified:"text-orange-400",deleted:"text-red-400",renamed:"text-sky-400",copied:"text-sky-400",untracked:"text-zinc-400",conflict:"text-red-400 font-bold"};function El(e){return e.split("/").pop()??e}function b0(e){const s=e.lastIndexOf("/");return s>0?e.slice(0,s):""}function g0({files:e,truncated:s,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?t.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):t.jsxs("div",{className:`flex flex-col ${a}`,children:[t.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(o=>{const l=n===o.path,c=h0[o.status]??"?",d=x0[o.status]??"text-zinc-400",m=b0(o.path),u=El(o.path),h=o.staged?t.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return t.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${l?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[t.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),t.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&t.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),t.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&t.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",El(o.oldPath)]}),h]}),!o.binary&&(o.insertions>0||o.deletions>0)&&t.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&t.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&t.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&t.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&t.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),s&&t.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",t.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function y0(e,s){let r="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?r="bg-emerald-500/10 text-emerald-300":e.startsWith("-")&&!e.startsWith("---")?r="bg-red-500/10 text-red-300":e.startsWith("@@")?r="text-sky-400":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(r="text-text-secondary"),t.jsx("div",{className:`px-3 ${r}`,children:t.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},s)}function v0({diff:e,binary:s,truncated:r,loading:n,error:a,className:o=""}){const l=i.useRef(null);if(i.useEffect(()=>{l.current&&(l.current.scrollTop=0)},[e]),n)return t.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return t.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});if(s)return t.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return t.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
|
|
65
|
-
`);return t.jsxs("div",{ref:l,className:`overflow-auto ${o}`,children:[t.jsx("div",{className:"py-1",children:c.map((d,m)=>y0(d,m))}),r&&t.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",t.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function w0(e,s){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${s.files.length} file(s) +${s.totalInsertions}/-${s.totalDeletions}`);const n={};for(const a of s.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,o]of Object.entries(n))r.push(`${a}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return r.join(`
|
|
66
|
-
`)}function hu({daemonId:e,workspace:s,onClose:r}){const{sendCommand:n}=wt(),{status:a,diffSummary:o,loading:l,error:c,refresh:d}=f0({daemonId:e,workspace:s,includeDiffSummary:!0}),[m,u]=i.useState(null),[h,g]=i.useState(null),[k,f]=i.useState(""),[p,b]=i.useState(!1),[y,x]=i.useState(!1),[I,N]=i.useState(null),[j,A]=i.useState(null),{githubUrl:M}=o0(e,s),v=i.useCallback(async E=>{if(!((m==null?void 0:m.path)===E.path&&!m.loading)){u({path:E.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const D=await n(e,"git_diff_file",{workspace:s,path:E.path,staged:E.staged}),S=p0(D);if(S.error||!S.diff){u({path:E.path,diff:"",binary:!1,truncated:!1,loading:!1,error:S.error??"Failed to load diff"});return}u({path:E.path,diff:S.diff.diff,binary:S.diff.binary??!1,truncated:S.diff.truncated??!1,loading:!1,error:null})}catch(D){const S=D instanceof Error?D.message:"Failed to load diff";u({path:E.path,diff:"",binary:!1,truncated:!1,loading:!1,error:S})}}},[e,n,m,s]),w=i.useCallback(E=>{f(""),b(!1),N(null),A(null),g(E)},[]),B=i.useCallback(()=>{g(null),N(null),x(!1)},[]),R=i.useCallback(async()=>{var E,D,S;if(h){x(!0),N(null);try{let C;h==="checkpoint"?C=await n(e,"git_checkpoint",{workspace:s,message:k,includeUntracked:p}):h==="stash"?C=await n(e,"git_stash_push",{workspace:s,message:k,includeUntracked:p}):h==="stash_pop"?C=await n(e,"git_stash_pop",{workspace:s}):h==="checkout_files"&&m&&(C=await n(e,"git_checkout_files",{workspace:s,paths:[m.path]}));const W=(C==null?void 0:C.result)??C;if((W==null?void 0:W.success)===!1||W!=null&&W.error){N((W==null?void 0:W.error)??"Action failed"),x(!1);return}h==="checkpoint"?A(`Checkpoint created: ${((D=(E=W==null?void 0:W.checkpoint)==null?void 0:E.commit)==null?void 0:D.slice(0,7))??"done"}`):h==="stash"?A(`Stashed as ${((S=W==null?void 0:W.stash)==null?void 0:S.stashRef)??"stash@{0}"}`):h==="stash_pop"?A("Stash restored"):(A("File reverted"),u(null)),g(null),await d()}catch(C){N(C instanceof Error?C.message:"Action failed")}finally{x(!1)}}},[h,n,e,s,k,p,m,d]),T=!!(a!=null&&a.hasConflicts),H=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:E=>{E.target===E.currentTarget&&r()},children:t.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[t.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[t.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),t.jsx("p",{className:"truncate text-xs text-text-secondary",children:s}),M&&t.jsx("a",{href:`${M}/tree/${(a==null?void 0:a.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-sky-400 underline",title:"Open on GitHub",children:"GitHub ↗"})]}),t.jsx("button",{onClick:d,disabled:l,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),t.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:t.jsx(vt,{className:"h-4 w-4"})})]}),a&&t.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[a.headCommit&&t.jsxs("span",{title:a.headMessage??void 0,children:[t.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&t.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&t.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&t.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&t.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&t.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&t.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&t.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&t.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&t.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),H===0&&!a.error&&t.jsx("span",{className:"text-emerald-500",children:"clean"}),o&&o.files.length>0&&t.jsxs("span",{className:"text-text-secondary",children:[o.files.length," file",o.files.length!==1?"s":"",o.totalInsertions>0&&t.jsxs("span",{className:"text-emerald-500",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&t.jsxs("span",{className:"text-red-400",children:[" -",o.totalDeletions]})]})]}),c&&t.jsx("div",{className:"shrink-0 border-b border-border/50 bg-red-500/10 px-4 py-2 text-xs text-red-400",children:c}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[l&&!o&&t.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&t.jsx(g0,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:v}),!l&&!o&&!c&&t.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),t.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?t.jsx(v0,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):t.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),j&&t.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-emerald-500/10 px-4 py-2 text-xs text-emerald-400 flex items-center justify-between",children:[t.jsx("span",{children:j}),t.jsx("button",{onClick:()=>A(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[t.jsx("button",{onClick:()=>w("checkpoint"),disabled:T,title:T?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),t.jsx("button",{onClick:()=>w("stash"),disabled:T,title:T?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),t.jsx("button",{onClick:()=>w("stash_pop"),disabled:T||!(a!=null&&a.stashCount),title:T?"Resolve conflicts before restoring a stash":a!=null&&a.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),t.jsx("button",{onClick:()=>w("checkout_files"),disabled:!m,title:m?`Revert changes to ${m.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),o&&o.files.length>0&&t.jsx("button",{onClick:()=>{const E=w0((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(E),A("Copied to clipboard"),setTimeout(()=>A(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),h&&t.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:t.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[t.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[h==="checkpoint"&&"Create checkpoint commit",h==="stash"&&"Stash changes",h==="stash_pop"&&"Restore latest stash?",h==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(h==="checkpoint"||h==="stash")&&t.jsxs(t.Fragment,{children:[t.jsx("input",{type:"text",value:k,onChange:E=>f(E.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-alt px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),t.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:p,onChange:E=>b(E.target.checked)}),"Include untracked files"]})]}),I&&t.jsx("p",{className:"text-xs text-red-400",children:I}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx("button",{onClick:B,disabled:y,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),t.jsx("button",{onClick:R,disabled:y||(h==="checkpoint"||h==="stash")&&!k.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:y?"Working…":"Confirm"})]})]})})]})})}function j0({isMobile:e,showMobileChatMode:s,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[m,u]=i.useState(!1),[h,g]=i.useState(!1),[k,f]=i.useState("quickstart"),[p,b]=i.useState("workspace"),y=i.useMemo(()=>!s&&!e,[s,e]),x=i.useCallback(v=>{a(v),v&&l(!1)},[]),I=i.useCallback(v=>{l(v),v&&a(!1)},[]),N=i.useCallback(()=>{f(r===0?"quickstart":"shortcuts"),b("workspace"),d(!0),a(!1),l(!1)},[r]),j=i.useCallback(()=>{d(!1)},[]),A=i.useCallback(()=>{u(!0)},[]),M=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!y){g(!1);return}g(!0);const v=window.setTimeout(()=>{g(!1)},1e4);return()=>window.clearTimeout(v)},[y]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:h,guideTab:k,shortcutSection:p,isDesktopDashboard:y,setGuideTab:f,setShortcutSection:b,handleInboxOpenChange:x,handleHiddenOpenChange:I,handleOpenShortcutHelp:N,closeShortcutHelp:j,openNewSession:A,closeNewSession:M}}function k0(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 N0(e){return e instanceof Error?e.message:String(e||"")}function S0(e){const s=N0(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function C0({showMobileChatMode:e,isMobile:s,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:l,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:h,ides:g,actionLogs:k,sendDaemonCommand:f,setActionLogs:p,setCliViewModeOverrides:b,isStandalone:y,initialDataLoaded:x,userName:I,requestedMobileTabKey:N,onRequestedMobileTabConsumed:j,requestedMachineId:A,onRequestedMachineConsumed:M,requestedMobileSection:v,onRequestedMobileSectionConsumed:w,containerRef:B,isSplitMode:R,numGroups:T,groupSizes:H,groupedConvs:E,clearedTabs:D,focusedGroup:S,focusGroup:C,moveTabToGroup:W,splitTabRelative:_,closeGroup:O,handleResizeStart:V,groupActiveTabIds:X,setGroupActiveTab:ye,groupTabOrders:he,setGroupTabOrder:ne,toggleHiddenTab:pe,visibleConversations:ke,requestedDesktopTabKey:Se,onRequestedDesktopTabConsumed:G,onDesktopActiveTabChange:be,onRequestScrollToBottom:fe,onHideConversation:ve,onShowHiddenConversation:P,onShowAllHiddenConversations:me,scrollToBottomRequest:q,machineEntries:de,layoutProfile:ae,onBrowseMachineDirectory:xe,onSaveMachineWorkspace:ue,onLaunchMachineIde:ce,onLaunchMachineProvider:te,onListMachineMeshes:$,onLaunchMeshCoordinator:J,onListMachineSavedSessions:oe,notifications:ee,notificationUnreadCount:Ne,liveSessionInboxState:Ce,onMarkNotificationRead:we,onMarkNotificationUnread:K,onDeleteNotification:Ie}){const Re=kt.useRef(null),{inboxOpen:Ke,hiddenOpen:He,shortcutHelpOpen:qe,newSessionOpen:Ye,guideNudgeVisible:st,guideTab:mt,shortcutSection:ht,isDesktopDashboard:yt,setGuideTab:Te,setShortcutSection:Ue,handleInboxOpenChange:et,handleHiddenOpenChange:ze,handleOpenShortcutHelp:at,closeShortcutHelp:U,openNewSession:z,closeNewSession:Z}=j0({isMobile:s,showMobileChatMode:e,visibleConversationCount:ke.length}),[ie,F]=kt.useState(null),[Y,re]=kt.useState(null),le=kt.useCallback((L,Q)=>{F({daemonId:L,workspace:Q})},[]),je=kt.useCallback(L=>{re(L)},[]),_e=kt.useCallback(L=>{var Q;kr.flushSync(()=>{P(L)}),(Q=Re.current)==null||Q.restoreHiddenTabToSavedLocation(L.tabKey)},[P]),De=kt.useCallback(L=>{var ge;const Q=u.find($e=>no($e,L))||h.find($e=>no($e,L));Q&&(h.some($e=>$e.tabKey===Q.tabKey)&&_e(Q),be(Q.tabKey),(ge=Re.current)==null||ge.activateConversationTab(Q.tabKey),fe(Q.tabKey,"notification-open")),we(L.id),et(!1)},[_e,h,u,be,we,fe]),Me=kt.useCallback(()=>{var Q;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Q=Re.current)==null||Q.resetAllPanelsToMain(),ze(!1))},[ze]),Ee=kt.useCallback(async L=>{var Be;if(!r)return;const Q=(Be=r.modalButtons)==null?void 0:Be[L];if(!Q)return;const ge=Us(r);if(!ge)return;const $e=Q.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Le=/^(run|approve|accept|yes|allow|always|proceed|save)/.test($e);try{await f(ge,"resolve_action",{button:Q,action:Le?"approve":"reject",buttonIndex:L,...fs(r)})}catch(rt){S0(rt)||console.error("[Shortcut approval] Failed:",rt)}},[r,f]),{isMac:Oe,actionDefinitions:Ae,actionShortcuts:Xe,shortcutListening:Qe,shortcutListeningDraft:xt,setShortcutListening:bt,setShortcutListeningDraft:ct,saveShortcuts:pt}=ly({enabled:yt&&!qe,onTrigger:L=>{var Q,ge,$e,Le,Be,rt,It,ft,Zt,Pr,Dr,Er,$r,Br,Or,Fr;if(L==="openShortcutHelp"){at();return}if(L==="openNewSession"){z();return}if(L==="hideCurrentTab"){r&&ve(r);return}if(L==="toggleHiddenTabs"){ze(!He);return}if(L==="openHistoryForActiveTab"){r&&!tt(r)&&o(r);return}if(L==="openRemoteForActiveTab"){r&&!nt(r)&&!tt(r)&&l(r);return}if(L==="splitActiveTabRight"){(Q=Re.current)==null||Q.splitActiveTabRight();return}if(L==="splitActiveTabDown"){(ge=Re.current)==null||ge.splitActiveTabDown();return}if(L==="floatActiveTab"){($e=Re.current)==null||$e.floatActiveTab();return}if(L==="popoutActiveTab"){(Le=Re.current)==null||Le.popoutActiveTab();return}if(L==="dockActiveTab"){(Be=Re.current)==null||Be.dockActiveTab();return}if(L==="focusLeftPane"){(rt=Re.current)==null||rt.focusLeftPane();return}if(L==="focusRightPane"){(It=Re.current)==null||It.focusRightPane();return}if(L==="focusUpPane"){(ft=Re.current)==null||ft.focusUpPane();return}if(L==="focusDownPane"){(Zt=Re.current)==null||Zt.focusDownPane();return}if(L==="moveActiveTabToLeftPane"){(Pr=Re.current)==null||Pr.moveActiveTabToLeftPane();return}if(L==="moveActiveTabToRightPane"){(Dr=Re.current)==null||Dr.moveActiveTabToRightPane();return}if(L==="moveActiveTabToUpPane"){(Er=Re.current)==null||Er.moveActiveTabToUpPane();return}if(L==="moveActiveTabToDownPane"){($r=Re.current)==null||$r.moveActiveTabToDownPane();return}if(L==="triggerPrimaryApprovalAction"){Ee(0);return}if(L==="triggerSecondaryApprovalAction"){Ee(1);return}if(L==="triggerTertiaryApprovalAction"){Ee(2);return}if(L==="setActiveTabShortcut"){(Br=Re.current)==null||Br.setShortcutForActiveTab();return}if(L==="selectPreviousGroupTab"){(Or=Re.current)==null||Or.activatePreviousTabInGroup();return}if(L==="selectNextGroupTab"){(Fr=Re.current)==null||Fr.activateNextTabInGroup();return}!r||!nt(r)||tt(r)||L==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),We=kt.useCallback(()=>{U(),bt(null),ct([])},[U,bt,ct]),Ot=kt.useMemo(()=>ht==="all"?Ae:Ae.filter(L=>k0(L)===ht),[Ae,ht]),se=kt.useCallback(()=>{const L=Object.fromEntries(Ae.map(Q=>[Q.id,""]));pt(L)},[Ae,pt]),Pe=kt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const L=Object.fromEntries(Ae.map(Q=>[Q.id,Q.defaultShortcut]));pt(L)},[Ae,pt]);return kt.useEffect(()=>{const L=Q=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Q.metaKey&&Q.key.toLowerCase()==="w":Q.ctrlKey&&Q.key.toLowerCase()==="w")&&(Q.preventDefault(),r&&ve&&ve(r))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[r,ve]),kt.useEffect(()=>{if(!qe||Qe)return;const L=Q=>{Q.key==="Escape"&&(Q.preventDefault(),We())};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[We,qe,Qe]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(ox,{activeConv:r,wsStatus:n,isConnected:a,conversations:ke,hiddenConversations:h,onOpenHistory:o,onHideConversation:ve,onShowConversation:_e,onShowAllHidden:me,onResetPanelsToMain:Me,notifications:ee,notificationUnreadCount:Ne,onOpenNotification:De,onMarkNotificationRead:we,onMarkNotificationUnread:K,onDeleteNotification:Ie,inboxOpen:Ke,onInboxOpenChange:et,hiddenOpen:He,onHiddenOpenChange:ze,onOpenNewSession:s?void 0:z,onOpenDashboardGuide:at,guideNudgeVisible:st,actionShortcuts:Xe,onOpenRemote:()=>{!r||nt(r)||tt(r)||l(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:le,onOpenMeshGraph:je}),e?t.jsx(Xg,{conversations:u,hiddenConversations:h,ides:g,actionLogs:k,sendDaemonCommand:f,setActionLogs:p,setCliViewModeOverrides:b,isStandalone:y,userName:I,requestedActiveTabKey:N,onRequestedActiveTabConsumed:j,requestedMachineId:A,onRequestedMachineConsumed:M,requestedMobileSection:v,onRequestedMobileSectionConsumed:w,onOpenHistory:o,onOpenRemote:l,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:me,onHideConversation:ve,onOpenMeshGraph:je,onOpenNewSession:z,liveSessionInboxState:Ce}):s?t.jsx(ny,{containerRef:B,isSplitMode:R,numGroups:T,groupSizes:H,groupedConvs:E,clearedTabs:D,ides:g,actionLogs:k,sendDaemonCommand:f,setActionLogs:p,isStandalone:y,hasRegisteredMachines:de.length>0,userName:I,focusedGroup:S,focusGroup:C,moveTabToGroup:W,splitTabRelative:_,closeGroup:O,handleResizeStart:V,groupActiveTabIds:X,setGroupActiveTab:ye,groupTabOrders:he,setGroupTabOrder:ne,toggleHiddenTab:pe,onOpenNewSession:z,allowTabShortcuts:!1,liveSessionInboxState:Ce}):t.jsx(jy,{visibleConversations:ke,clearedTabs:D,ides:g,actionLogs:k,sendDaemonCommand:f,setActionLogs:p,isStandalone:y,hasRegisteredMachines:de.length>0,initialDataLoaded:x,userName:I,toggleHiddenTab:pe,actionShortcuts:Xe,registerActionHandlers:L=>{Re.current=L},onActiveTabChange:be,requestedActiveTabKey:Se,onRequestedActiveTabConsumed:G,onRequestScrollToBottom:fe,scrollToBottomRequest:q,onOpenNewSession:z,liveSessionInboxState:Ce,layoutProfile:ae}),Ye&&t.jsx(Iy,{machines:de,ides:g,onClose:Z,onBrowseDirectory:xe,onSaveWorkspace:ue,onLaunchIde:ce,onLaunchProvider:te,onListMeshes:$,onLaunchMeshCoordinator:J,onListSavedSessions:oe}),Y&&t.jsx(a0,{activeConv:Y,sendDaemonCommand:f,onClose:()=>re(null)}),ie&&t.jsx(hu,{daemonId:ie.daemonId,workspace:ie.workspace,onClose:()=>F(null)}),qe&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick: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:L=>L.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(vt,{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(L=>t.jsx("button",{type:"button",className:`btn btn-sm ${mt===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>Te(L.id),children:L.label},L.id))}),mt==="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 ",Oe?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),mt==="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."]})]})]})]}),mt==="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(L=>t.jsx("button",{type:"button",className:`btn btn-sm ${ht===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ue(L.id),children:L.label},L.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:se,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:Pe,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:Ot.map(L=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${Qe===L.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:L.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:L.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:L.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:Qe===L.id?xt.length>0?`${xt.join(" ")} ...`:"Listening...":Xe[L.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{bt(L.id),ct([])},children:Qe===L.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Q={...Xe};Q[L.id]="",pt(Q)},children:"Disable"})]})]})},L.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Oe?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const Ea=[{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 I0({onClose:e}){const[s,r]=i.useState(0),n=Ea[s],a=s===Ea.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:o=>{o.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(vt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Ea.map((o,l)=>t.jsx("div",{style:{width:l===s?24:8,height:8,borderRadius:4,background:l===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},l))}),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(o=>o+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),t.jsx("style",{children:`
|
|
67
|
-
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
68
|
-
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
69
|
-
`})]})}function T0({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(o=>{const l=r===o.tabKey,c=o.status==="waiting_approval",d=o.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 ${l?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(o.tabKey),children:[t.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.title,c&&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:"!"})]},o.tabKey)})]}):null}function A0({ideData:e,allIdes:s,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,l]=i.useState(()=>a||"native"),c=i.useMemo(()=>ad(s),[s]),d=i.useMemo(()=>e?qo(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=i.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),h=i.useMemo(()=>e?Bt(d,e.id):null,[d,e]);i.useEffect(()=>{a&&l(a)},[a]),i.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||o===p||o==="native"&&l(p)},[o,h,a]),i.useEffect(()=>{var p;o!=="native"&&(u.some(b=>b.tabKey===o)||l(((p=u[0])==null?void 0:p.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(m||u[0]&&l(u[0].tabKey))},[o,m,u]);const g=i.useMemo(()=>o==="native"&&m?m:u.find(p=>p.tabKey===o)||h||m||u[0],[o,m,h,u]),k=i.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:Qc(p)||n,status:p.status})),[u,n]),f=i.useCallback(p=>{if(p)return d.find(b=>no(b,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:o,setActiveChatTab:l,activeConv:g,conversations:d,extensionTabs:k,hasExtensions:k.length>0,resolveConversationByTarget:f}}function M0({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:l,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:h}){const[g,k]=i.useState("split"),[f,p]=i.useState(()=>os(e)?"native":e.tabKey),b=i.useRef(null),y=i.useMemo(()=>s||r.find(C=>C.id===e.routeId),[e.routeId,s,r]),x=i.useMemo(()=>lt((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:I,extensionTabs:N,hasExtensions:j}=A0({ideData:y,allIdes:r,connectionStates:n,ideName:x||"IDE",preferredTabKey:os(e)?void 0:e.tabKey}),A=i.useMemo(()=>y?Bt(I,y.id):null,[y,I]);i.useEffect(()=>{const C=b.current,W={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(b.current=W,!(C&&C.routeId===W.routeId&&C.tabKey===W.tabKey&&C.streamSource===W.streamSource)){if(os(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(f==="native"){if(I.some(C=>C.streamSource==="native"))return;(A==null?void 0:A.streamSource)==="agent-stream"&&p(A.tabKey);return}if(!I.some(C=>C.tabKey===f)){if((A==null?void 0:A.streamSource)==="agent-stream"){p(A.tabKey);return}p("native")}},[I,f,A]);const M=i.useMemo(()=>f==="native"?I.find(C=>C.streamSource==="native")||e:I.find(C=>C.tabKey===f)||e,[e,I,f]),v=gd(M),w=i.useMemo(()=>v.status||v.modalMessage||v.modalButtons?{...M,...v.status?{status:v.status}:{},...v.modalMessage!==void 0?{modalMessage:v.modalMessage}:{},...v.modalButtons!==void 0?{modalButtons:v.modalButtons}:{}}:M,[M,v]),B=Mr(w),R=Kn({sendDaemonCommand:o,activeConv:w,setActionLogs:l,isStandalone:c}),{connScreenshot:T,screenshotUsage:H,handleRemoteAction:E}=qd({doId:B,targetSessionId:Dc(w),connState:w.connectionState||"new",viewMode:g}),D=i.useMemo(()=>a.filter(C=>C.routeId===w.tabKey),[a,w.tabKey]);i.useEffect(()=>{u==null||u(w)},[w,u]),i.useEffect(()=>{const C=W=>{W.key==="Escape"&&h()};return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[h]);const S=i.useCallback(C=>{C.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:h,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:S,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(Mt,{size:16})}),t.jsx("span",{className:"truncate",children:Eo(M)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,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(C=>{const W=g===C;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${W?"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:()=>k(C),title:C==="split"?"Split view":"Remote only",children:C==="split"?t.jsx($m,{size:15}):t.jsx(Mt,{size:15})},C)})}),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:()=>m(M),title:"Chat History",children:[t.jsx(No,{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:h,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${g==="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:[g!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${g==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(T0,{hasExtensions:j,ideName:x||"IDE",activeChatTab:f,extensionTabs:N,onSelectTab:p}),t.jsx(wc,{activeConv:w,onModalButton:R.handleModalButton}),t.jsx(oo,{activeConv:w,ideEntry:y,showMetaChips:!1,handleSendChat:R.handleSendChat,isSendingChat:R.isSendingChat,sendFeedbackMessage:R.sendFeedbackMessage,handleFocusAgent:R.handleFocusAgent,isFocusingAgent:R.isFocusingAgent,actionLogs:D,userName:d})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${g==="split"?"order-1 md:order-2":""}`,children:t.jsx(yc,{addLog:()=>{},connState:w.connectionState||"new",connScreenshot:T,screenshotUsage:H,transportType:w.transport,onAction:E})})]})]})})}function L0({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=Yh(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 ",o,"?"]}),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 R0({historyModal:e,remoteDialog:s,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var l;return t.jsxs(t.Fragment,{children:[t.jsx(ex,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&t.jsx(Go,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),s.conversation&&t.jsx(M0,{activeConv:s.conversation,ideEntry:s.ideEntry,ides:s.ides,connectionStates:s.connectionStates,actionLogs:s.actionLogs,sendDaemonCommand:s.sendDaemonCommand,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone,userName:s.userName,onOpenHistory:s.onOpenHistory,onConversationChange:s.onConversationChange,onClose:s.onClose}),r.open&&r.targetConv&&(nt(r.targetConv)||tt(r.targetConv))&&t.jsx(L0,{activeConv:r.targetConv,canSaveAndStop:nt(r.targetConv)&&!tt(r.targetConv)&&!!((l=r.targetConv.resume)!=null&&l.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),t.jsx(nd,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&t.jsx(I0,{onClose:o.onClose})]})}function _0({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:o}){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(Tr,{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(l=>{const c=At(l,{fallbackId:l.id}),d=n[l.id],m=l.version||l.daemonVersion||"unknown",u=l.versionUpdateRequired===!0,g=Rd(l)==="preview"?"Update to preview":u?"Update now":"Upgrade";return t.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[t.jsx("span",{className:"font-medium text-text-primary",children:c}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(l.id),children:"retry"}):t.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:u?"var(--status-danger)":"var(--status-warning)",background:u?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${u?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(l.id),children:g})]},l.id)})]}),!r&&t.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:t.jsx(vt,{size:16})})]})}function P0(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function D0(e){const s=e.machine;return typeof(s==null?void 0:s.cpus)!="number"||typeof(s==null?void 0:s.totalMem)!="number"||typeof(s==null?void 0:s.arch)!="string"||typeof(s==null?void 0:s.release)!="string"}function E0(e){return{metadataDaemonIds:e.map(s=>s.id),runtimeDaemonIds:e.filter(s=>D0(s)).map(s=>s.id)}}function $0(){var pi,fi,hi,xi;const{sendCommand:e}=wt(),s=Lr(),r=bd(),n=wo(),a=ls(),[o,l]=rm(),c=o.get("activeTab"),d=((pi=n.state)==null?void 0:pi.openRemoteForTabKey)||null,m=((fi=n.state)==null?void 0:fi.openMachineId)||null,u=((hi=n.state)==null?void 0:hi.mobileSection)||null,h=qc(),g=h.ides||[],k=h.initialLoaded??!0,{updateRouteChats:f,setToasts:p}=h,[b,y]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),x=h.toasts||[],I=h.wsStatus||"connected",N=h.isConnected??!0,j=h.connectionStates||{},A=h.showReconnected||!1,{layoutProfile:M,groupAssignments:v,updateGroupAssignments:w,focusedGroup:B,updateFocusedGroup:R,focusGroup:T,groupActiveTabIds:H,updateGroupActiveTabIds:E,setGroupActiveTab:D,groupTabOrders:S,updateGroupTabOrders:C,setGroupTabOrder:W,groupSizes:_,updateGroupSizes:O,isMobile:V,hasHydratedStoredLayout:X,hydrateStoredLayout:ye,focusConversationTab:he}=zb(),[ne,pe]=i.useState(()=>Qo());i.useEffect(()=>rb(pe),[]);const ke=i.useMemo(()=>P0({isMobile:V,mobileViewMode:ne}),[V,ne]),[Se,G]=i.useState([]),[be,fe]=i.useState({}),[ve,P]=i.useState({});Ar("Dashboard",{ideCount:g.length,toastCount:x.length,focusedGroup:B,groupCount:Object.keys(v).length,actionLogCount:Se.length});const me=i.useMemo(()=>g.filter(Ve=>Ve.type==="adhdev-daemon").sort(_o),[g]),q=me[0],de=!!q;i.useEffect(()=>{const{metadataDaemonIds:Ve,runtimeDaemonIds:Pt}=E0(me);for(const Js of Ve)s(Js,{minFreshMs:3e4}).catch(()=>{});for(const Js of Pt)r(Js,{minFreshMs:3e4}).catch(()=>{})},[s,r,me]);const ae=(q==null?void 0:q.terminalBackend)||null,xe=q?At(q,{fallbackId:q.id}):null,ue=(q==null?void 0:q.id)||null,ce=i.useMemo(()=>bb(g,be),[g,be]),{hiddenTabs:te,autoHiddenTabs:$,autoHideTarget:J,hideTarget:oe,toggleTarget:ee,showTarget:Ne,showAllTabs:Ce}=xb(),{conversations:we,visibleConversations:K,visibleTabKeys:Ie,resolveConversationBySessionId:Re,resolveConversationByTarget:Ke}=Mb({ides:ce,connectionStates:j,clearedTabs:ve,hiddenTabs:te}),He=i.useMemo(()=>new Map(we.map(Ve=>[Ve.tabKey,Ve])),[we]),qe=i.useMemo(()=>hb(we,te,$),[we,te,$]);i.useEffect(()=>{for(const Ve of qe)J(Ve)},[qe,J]),Ch(K,ke),i.useEffect(()=>{Object.keys(be).length!==0&&fe(Ve=>gb(Ve,g))},[g,be]);const Ye=i.useMemo(()=>_p(g),[g]),{notifications:st,unreadCount:mt}=ig({conversations:we,liveSessionInboxState:Ye}),{handleMarkDashboardNotificationRead:ht,handleMarkDashboardNotificationUnread:yt,handleDeleteDashboardNotification:Te}=lg({notifications:st,sendDaemonCommand:e}),{containerRef:Ue,normalizedGroupAssignments:et,numGroups:ze,isSplitMode:at,groupedConvs:U,moveTabToGroup:z,closeGroup:Z,handleResizeStart:ie,splitTabRelative:F}=Qb({groupAssignments:v,updateGroupAssignments:w,updateFocusedGroup:R,updateGroupActiveTabIds:E,updateGroupTabOrders:C,groupSizes:_,updateGroupSizes:O,isMobile:V,visibleConversations:K,visibleTabKeys:Ie}),{activeConv:Y,openDesktopConversation:re,requestScrollToBottom:le,scrollToBottomRequest:je,setDesktopActiveTab:_e}=jg({isMobile:V,conversations:we,visibleConversations:K,groupActiveTabIds:H,focusedGroup:B,groupedConvs:U,setSearchParams:l});Sg({activeConv:Y,isMobile:V,liveSessionInboxState:Ye,sendDaemonCommand:e});const{requestedDesktopTabKey:De,requestedMobileTabKey:Me,consumeRequestedActiveTab:Ee}=Lb({isMobile:V,urlActiveTab:c,resolveConversationBySessionId:Re,setSearchParams:l}),{remoteDialogConv:Oe,remoteDialogIdeEntry:Ae,remoteDialogActiveConv:Xe,setRemoteDialogActiveConv:Qe,openRemoteDialog:xt,closeRemoteDialog:bt,cliStopDialogOpen:ct,cliStopTargetConv:pt,requestCliStop:We,cancelCliStop:Ot,confirmCliStop:se}=Tg({isMobile:V,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:De,conversations:we,ides:g,resolveConversationByTarget:Ke,activeConv:Y,sendDaemonCommand:e}),{historyModalOpen:Pe,openHistoryModal:L,closeHistoryModal:Q,historyTargetConv:ge,isSavedSessionHistoryTarget:$e,isHistoryCreatingChat:Le,isHistoryRefreshingHistory:Be,handleHistorySwitchSession:rt,handleHistoryNewChat:It,handleHistoryRefresh:ft,savedHistorySessions:Zt,savedHistoryFilters:Pr,setSavedHistoryFilters:Dr,missingWorkspaceResumePath:Er,isSavedHistoryLoading:$r,resumingSavedHistorySessionId:Br,handleRefreshSavedHistory:Or,handleResumeSavedHistorySession:Fr}=Cg({activeConv:Y,remoteDialogConv:Oe,remoteDialogActiveConv:Xe,ides:g,sendDaemonCommand:e,updateRouteChats:f,setToasts:p,setClearedTabs:P,setSearchParams:l}),vu=i.useMemo(()=>K,[K]),Kr=V&&ne==="chat",wu=i.useMemo(()=>we.filter(Ve=>Hn(te,Ve)),[we,te]),di=i.useCallback(Ve=>{const Pt=new URLSearchParams(o);Pt.set("activeTab",Ve),l(Pt,{replace:!0})},[o,l]),{trackPendingLaunch:ju}=gg({ides:g,conversations:we,onOpenSession:di}),{handleBrowseMachineDirectory:ku,handleSaveMachineWorkspace:Nu,handleLaunchMachineIde:Su,handleLaunchMachineProvider:Cu,handleListMachineMeshes:Iu,handleLaunchMeshCoordinator:Tu,handleListMachineSavedSessions:Au,setActiveCliViewMode:Mu}=yg({sendDaemonCommand:e,trackPendingLaunch:ju,onOpenSession:di,activeConv:Y,ides:g,setCliViewModeOverrides:fe});yb({visibleConversations:K,clearedTabs:ve,setClearedTabs:P,setActionLogs:G}),Rb({ides:g,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Ke});const{isRefreshingHistory:Lu,handleRefreshHistory:Ru}=Ld({sendDaemonCommand:e,activeConv:Y,chats:(xi=g.find(Ve=>Ve.id===(Y==null?void 0:Y.routeId)))==null?void 0:xi.chats,updateRouteChats:f,setToasts:p,setClearedTabs:P});Gb({urlActiveTab:V&&!Kr?c:null,conversations:we,resolveConversationBySessionId:Re,normalizedGroupAssignments:et,hasHydratedStoredLayout:V&&!Kr?X:!0,hydrateStoredLayout:V&&!Kr?ye:()=>{},focusConversationTab:he,setSearchParams:l,historyModalOpen:Pe,activeConv:Y,isRefreshingHistory:Lu,ides:g,handleRefreshHistory:Ru});const _u=i.useMemo(()=>!Y||!nt(Y)||tt(Y)?null:Xs(Y),[Y]),{versionMismatchDaemons:Pu,hasRequiredVersionDaemons:ui,targetVersion:Du,versionBannerDismissed:Eu,setVersionBannerDismissed:$u,upgradingDaemons:Bu,handleBannerUpgrade:Ou}=eg({ides:g,sendDaemonCommand:e}),mi=i.useCallback(Ve=>{Ne(Ve),re(Ve)},[re,Ne]),Fu=i.useCallback(Ve=>{oe(Ve)},[oe]);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(tx,{terminalBackend:ae,isStandalone:de,machineLabel:xe,machineKey:ue}),(!Eu||ui)&&t.jsx(_0,{daemons:Pu,targetVersion:Du,required:ui,upgradingDaemons:Bu,onUpgrade:Ou,onDismiss:()=>$u(!0)}),t.jsx(C0,{showMobileChatMode:Kr,isMobile:V,activeConv:Y,wsStatus:I,isConnected:N,onOpenHistory:Ve=>{Ve&&Qe(Ve),L()},onOpenRemote:xt,onStopCli:We,activeCliViewMode:_u,onSetActiveCliViewMode:Mu,mobileChatConversations:vu,ides:g,actionLogs:Se,sendDaemonCommand:e,setActionLogs:G,setCliViewModeOverrides:fe,isStandalone:de,initialDataLoaded:k,userName:h.userName,requestedMobileTabKey:Me,onRequestedMobileTabConsumed:Ee,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ue,isSplitMode:at,numGroups:ze,groupSizes:_,groupedConvs:U,clearedTabs:ve,focusedGroup:B,focusGroup:T,moveTabToGroup:z,splitTabRelative:F,closeGroup:Z,handleResizeStart:ie,groupActiveTabIds:H,setGroupActiveTab:D,groupTabOrders:S,setGroupTabOrder:W,toggleHiddenTab:Ve=>ee(He.get(Ve)||{tabKey:Ve}),visibleConversations:K,hiddenConversations:wu,requestedDesktopTabKey:De,onRequestedDesktopTabConsumed:Ee,onDesktopActiveTabChange:_e,onRequestScrollToBottom:le,onHideConversation:Fu,onShowHiddenConversation:mi,onShowAllHiddenConversations:Ce,scrollToBottomRequest:je,machineEntries:me,layoutProfile:M,onBrowseMachineDirectory:ku,onSaveMachineWorkspace:Nu,onLaunchMachineIde:Su,onLaunchMachineProvider:Cu,onListMachineMeshes:Iu,onLaunchMeshCoordinator:Tu,onListMachineSavedSessions:Au,notifications:st,notificationUnreadCount:mt,liveSessionInboxState:Ye,onMarkNotificationRead:ht,onMarkNotificationUnread:yt,onDeleteNotification:Te}),t.jsx("style",{children:`
|
|
70
|
-
body { overflow: hidden; overscroll-behavior: none; }
|
|
71
|
-
`}),t.jsx(R0,{historyModal:{open:Pe,targetConv:ge,ides:g,isCreatingChat:Le,isRefreshingHistory:$e?!1:Be,savedSessions:Zt,savedHistoryFilters:Pr,missingWorkspaceResumePath:Er||null,onSavedHistoryFiltersChange:Dr,isSavedSessionsLoading:$r,isResumingSavedSessionId:Br,onClose:Q,onNewChat:It,onSwitchSession:rt,onRefreshHistory:$e?Or:ft,onResumeSavedSession:Fr},remoteDialog:{conversation:Oe,ideEntry:Ae,ides:g,connectionStates:j,actionLogs:Se,sendDaemonCommand:e,setActionLogs:G,isStandalone:de,userName:h.userName,onOpenHistory:Ve=>{Ve&&Qe(Ve),L()},onConversationChange:Qe,onClose:bt},cliStopDialog:{open:ct,targetConv:pt,onCancel:Ot,onStopNow:async()=>{await se("hard")},onSaveAndStop:async()=>{await se("save")}},connectionBanner:{wsStatus:I,showReconnected:A,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:x,onDismiss:Ve=>p(Pt=>Pt.filter(Js=>Js.id!==Ve)),onClick:Ve=>{if(Ve.targetKey){const Pt=Ke(Ve.targetKey);Pt&&(he(Pt.tabKey,et),mi(Pt),le(Pt.tabKey,"toast-open"))}}},onboarding:{open:b,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}}})]})}function B0({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,l]=i.useState([]),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,g]=i.useState(!1),[k,f]=i.useState(null),[p,b]=i.useState(!1),[y,x]=i.useState(""),I=i.useRef(null),N=i.useCallback(_=>{I.current=_},[]),j=i.useCallback((_,O,V=!1)=>{l(X=>[...X.slice(-100),{timestamp:Date.now(),level:_,message:O}]),setTimeout(()=>{var X;return(X=a.current)==null?void 0:X.scrollIntoView({behavior:"smooth"})},100),V&&ot.showToast(O,_==="error"||_==="warn"?"warning":"success")},[a]),A=i.useCallback(_=>{const O=_ instanceof Error?_.message:String(_||"");return O.includes("P2P command timeout")||O.includes("P2P not connected")||O.includes("P2P not available")},[]),M=i.useCallback(async(_,O)=>{var V;if(!e||c)return!1;d(_),j("info",`Launching ${lt(_)}${O!=null&&O.workspace?` in ${O.workspace}`:""}...`);try{const X={ideType:_,enableCdp:!0};(V=O==null?void 0:O.workspace)!=null&&V.trim()?X.workspace=O.workspace.trim():O!=null&&O.useDefaultWorkspace&&(X.useDefaultWorkspace=!0);const ye=await r(e,"launch_ide",X);return j(ye!=null&&ye.success?"info":"error",ye!=null&&ye.success?`${lt(_)} launched`:`Failed: ${ye==null?void 0:ye.error}`,!0),!!(ye!=null&&ye.success)}catch(X){return j("error",`Launch error: ${X.message}`,!0),!1}finally{d(null)}},[e,c,j,r]),v=i.useCallback(async _=>{if(!e)return{success:!1};const{cliType:O,dir:V,workspaceId:X,useDefaultWorkspace:ye,useHome:he,argsStr:ne,model:pe,resumeSessionId:ke}=_;if(!O)return j("warn","Select a CLI or ACP provider first",!0),{success:!1};const Se=ne?ne.split(/\s+/).filter(Boolean):void 0,G=(V==null?void 0:V.trim())||(X?"(saved id)":ye?"(default workspace)":he?"(home)":"");j("info",`Launching ${O}${G?` in ${G}`:""}${pe?` (model: ${pe})`:""}...`),u(O);try{const be={cliType:O,cliArgs:Se,initialModel:pe||void 0};V!=null&&V.trim()?be.dir=V.trim():X?be.workspaceId=X:ye?be.useDefaultWorkspace=!0:he&&(be.useHome=!0),ke&&(be.resumeSessionId=ke);const fe=await r(e,"launch_cli",be),ve=(fe==null?void 0:fe.result)||fe;return fe!=null&&fe.success?(j("info",`${O} launched`,!0),(ve==null?void 0:ve.launchSource)==="home"?j("info","📂 Running in home directory (explicit choice)"):(ve==null?void 0:ve.launchSource)==="defaultWorkspace"&&j("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ve==null?void 0:ve.sessionId}):(j("error",`Failed: ${(fe==null?void 0:fe.error)||(ve==null?void 0:ve.error)}`,!0),(fe==null?void 0:fe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&f({cliType:O,argsStr:ne,model:pe}),{success:!1,sessionId:ve==null?void 0:ve.sessionId})}catch(be){return A(be)?(j("warn",`${O} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(j("error",`Launch error: ${be.message}`,!0),{success:!1})}finally{u(null)}},[e,j,A,r]),w=i.useCallback(async(_,O,V,X)=>e?_?O.trim()?v({cliType:_,dir:O,argsStr:V,model:X}):(f({cliType:_,argsStr:V,model:X}),{success:!1}):(j("warn","Select a provider",!0),{success:!1}):{success:!1},[e,j,v]),B=i.useCallback(async(_,O,V)=>{if(e&&window.confirm(`Stop ${_}?
|
|
72
|
-
This will terminate the process.`))try{const X=await r(e,"stop_cli",{cliType:_,dir:O,targetSessionId:V});X!=null&&X.success?j("info",`${_} stopped`,!0):j("error",`Stop failed: ${(X==null?void 0:X.error)||"Unknown error"}`,!0)}catch(X){j("error",`Stop failed: ${X.message}`,!0)}},[e,j,r]),R=i.useCallback(async _=>{try{await r(_.daemonId,"restart_ide",{ideType:_.type}),j("info",`${lt(_.type)} restart initiated`,!0)}catch(O){j("error",`Restart failed: ${O.message}`,!0)}},[j,r]),T=i.useCallback(async _=>{if(window.confirm(`Stop ${lt(_.type)}?
|
|
73
|
-
This will disconnect CDP and optionally kill the process.`))try{const O=await r(_.daemonId,"stop_ide",{ideType:_.type,killProcess:!0});O!=null&&O.success?j("info",`${lt(_.type)} stopped`,!0):j("error",`Stop failed: ${(O==null?void 0:O.error)||"Unknown error"}`,!0)}catch(O){j("error",`Stop failed: ${O.message}`,!0)}},[j,r]),H=i.useCallback(async()=>{if(e)try{const _=await r(e,"detect_ides",{});j("info",`Found ${((_==null?void 0:_.result)||[]).length} IDE(s)`,!0)}catch(_){j("error",`Detection failed: ${_.message}`,!0)}},[e,j,r]),E=i.useCallback(async _=>{if(!e||!_.trim())return!1;g(!0);try{const O=await r(e,"workspace_add",{path:_.trim()});return O!=null&&O.success?(j("info",`Workspace added: ${_.trim()}`),!0):(j("error",(O==null?void 0:O.error)||"workspace_add failed"),!1)}catch(O){return j("error",O.message),!1}finally{g(!1)}},[e,j,r]),D=i.useCallback(async _=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const O=await r(e,"workspace_remove",{id:_});O!=null&&O.success?j("info","Workspace removed",!0):j("error",(O==null?void 0:O.error)||"workspace_remove failed",!0)}catch(O){j("error",O.message,!0)}finally{g(!1)}}},[e,j,r]),S=i.useCallback(async _=>{var O;if(e){g(!0);try{const V=await r(e,"workspace_set_default",_===null?{clear:!0}:{id:_});if(V!=null&&V.success){j("info",_?"Default workspace updated":"Default workspace cleared",!0);const X=typeof V.defaultWorkspacePath=="string"?V.defaultWorkspacePath:"";X&&((O=I.current)==null||O.call(I,X))}else j("error",(V==null?void 0:V.error)||"workspace_set_default failed",!0)}catch(V){j("error",V.message,!0)}finally{g(!1)}}},[e,j,r]),C=i.useCallback(async _=>{var V;if(!e||!_.trim())return;const O=_.trim();g(!0);try{const X=await r(e,"workspace_set_default",{path:O});X!=null&&X.success?(j("info","Default workspace set from history"),(V=I.current)==null||V.call(I,O)):j("error",(X==null?void 0:X.error)||"Could not set default (path missing on disk?)")}catch(X){j("error",X.message)}finally{g(!1)}},[e,j,r]),W=i.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:y})}catch(_){j("warn",`Live nickname updated, but account sync failed: ${_.message}`)}j("info",`Nickname set to "${y||"(cleared)"}"`),b(!1)}catch(_){j("error",`Failed: ${_.message}`)}},[e,y,s,j,n,r]);return{logs:o,launchingIde:c,launchingAgentType:m,workspaceBusy:h,launchPick:k,setLaunchPick:f,editingNickname:p,setEditingNickname:b,nicknameInput:y,setNicknameInput:x,addLog:j,handleLaunchIde:M,runLaunchCliCore:v,handleLaunchCli:w,handleStopCli:B,handleRestartIde:R,handleStopIde:T,handleDetectIdes:H,handleWorkspaceAdd:E,handleWorkspaceRemove:D,handleWorkspaceSetDefault:S,handleWorkspaceResumePath:C,handleSaveNickname:W,setOnDefaultWorkspaceChanged:N}}function O0({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:l}){var R;const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[h,g]=i.useState(!1),[k,f]=i.useState(""),[p,b]=i.useState([]),[y,x]=i.useState(!1),[I,N]=i.useState(""),j=i.useCallback(async T=>{x(!0),N("");try{const H=await Vn(l,e,T);f(H.path),b(H.directories)}catch(H){N(H instanceof Error?H.message:"Could not load folder")}finally{x(!1)}},[e,l]),A=i.useCallback(()=>{g(!0);const T=[...r.map(E=>E.workspace),...n.map(E=>E.workspace),...a.map(E=>E.workspace)],H=zn(s.platform,Un(T,s.defaultWorkspacePath,(s.workspaces||[]).map(E=>E.path)));j(H)},[a,n,r,j,s.defaultWorkspacePath,s.platform,s.workspaces]),M=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,w=M&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-v)/s.totalMem*100))):0,B=((R=s.loadavg)==null?void 0:R[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(Hr,{icon:t.jsx(dc,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Op(s.uptime):"Waiting…"}),t.jsx(Hr,{icon:t.jsx(Mt,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(Hr,{icon:t.jsx(Co,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(Hr,{icon:t.jsx(Om,{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(Ri,{value:M?Math.min(Math.round(B/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:M?`${B.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(Ri,{value:w,max:100,label:"Memory",color:"#3b82f6",detail:M?`${ra(s.totalMem-v)} / ${ra(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${ra(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(ks,{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:c,value:s.defaultWorkspaceId||"",onChange:T=>void u(T.target.value===""?null:T.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(T=>t.jsx("option",{value:T.id,children:T.label||T.path},T.id))]}),s.defaultWorkspacePath&&t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",className:"btn bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary px-3 py-1.5 rounded transition-colors text-xs",disabled:c,onClick:A,children:"Select workspace…"}),t.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&t.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(T=>t.jsxs("li",{className:"flex items-start gap-2 text-[11px] text-text-muted rounded-lg border border-border-subtle bg-bg-primary px-2.5 py-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[T.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:On(T.path,T.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:T.path,children:T.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(T.id),children:"Remove"})]},T.id))})]}),h&&t.jsx(Gn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:k,directories:p,busy:y,error:I,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:T=>{j(T)},onConfirm:T=>{(async()=>{if(!T)return;await d(T)&&g(!1)})()}})]})}function F0(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 K0(e,s,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const l=r!=null&&r.filterSchema?r.filterSchema(o):o;if(l.length===0)continue;const c=s.find(d=>d.type===a);n.push({type:a,displayName:(c==null?void 0:c.displayName)||a,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:l,values:e.values[a]||{}})}return n}function $a(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 $l(e){if(!e||typeof e!="object")return null;if($a(e))return e;const s=e,r=s.result;return $a(r)?r:$a(s.sourceConfig)?s.sourceConfig:null}function W0(e){const s=e.trim();return s||null}const Bl=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],H0=[{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 U0({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[l,c]=i.useState("codex-cli"),[d,m]=i.useState([]),[u,h]=i.useState(""),[g,k]=i.useState([]),[f,p]=i.useState(""),b=i.useRef(null),y=i.useRef(null),x=v=>{m(w=>w.includes(v)?w.filter(B=>B!==v):[...w,v])},I=()=>m([...Bl]),N=()=>m([]);i.useEffect(()=>{var v;(v=b.current)==null||v.scrollIntoView({behavior:"smooth"})},[g]),i.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const j=i.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const v=await r(e,"provider_auto_fix_status",{providerType:s.type});(v==null?void 0:v.running)===!1&&a==="running"&&(o("done"),k(w=>[...w,`
|
|
74
|
-
✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,s.type,r,a]),A=async()=>{if(d.length!==0){o("running"),k(["🚀 Starting auto-fix...",`Agent: ${l}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),p("");try{const v=await r(e,"provider_auto_fix",{providerType:s.type,functions:d,agent:l,...u?{comment:u}:{}});v!=null&&v.success&&(v!=null&&v.started||v!=null&&v.running)?(k(w=>[...w,"✅ Agent started. Monitoring progress..."]),j()):(o("error"),p((v==null?void 0:v.error)||"Failed to start auto-fix"))}catch(v){o("error"),p((v==null?void 0:v.message)||"Connection failed")}}},M=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),k(v=>[...v,`
|
|
75
|
-
⚠️ Auto-fix cancelled.`]),o("done"),y.current&&clearInterval(y.current)}catch{}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[560px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[85vh] overflow-hidden rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col",onClick:v=>v.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:H0.map(v=>t.jsxs("button",{onClick:()=>c(v.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:l===v.value?v.color+"66":"var(--border-subtle)",background:l===v.value?v.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:l===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:I,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:N,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Bl.map(v=>t.jsxs("button",{onClick:()=>x(v),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(v)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(v)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(v)?"#a78bfa":"var(--text-secondary)"},children:[d.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:u,onChange:v=>h(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,w)=>t.jsx("div",{className:v.startsWith("✅")?"text-green-400":"",style:v.startsWith("❌")||v.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:v},w)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:b})]}),f&&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:f})]})]}),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"&&d.length>0&&`${d.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:A,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&t.jsx("button",{onClick:M,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:()=>{o("config"),k([]),p("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function z0({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var j;const o=s.filter(A=>A.category==="ide"),[l,c]=i.useState(((j=o[0])==null?void 0:j.type)||""),[d,m]=i.useState(""),[u,h]=i.useState(""),[g,k]=i.useState(!1),[f,p]=i.useState(""),[b,y]=i.useState(!1),x=A=>{const M=A.toLowerCase().replace(/[^a-z0-9-]/g,"");m(M),(!u||u===I(d))&&h(I(M))},I=A=>A.split("-").map(M=>M.charAt(0).toUpperCase()+M.slice(1)).join(" "),N=async()=>{if(!(!d||!u||!l)){k(!0),p("");try{const A=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:l});A!=null&&A.success||A!=null&&A.created?(y(!0),a==null||a(d)):p((A==null?void 0:A.error)||"Failed to create provider")}catch(A){p((A==null?void 0:A.message)||"Connection failed")}k(!1)}};return t.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:n,children:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:A=>A.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:b?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:d})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," 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:o.map(A=>t.jsxs("button",{onClick:()=>c(A.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:l===A.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l===A.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:A.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:l===A.type?"#a78bfa":"var(--text-secondary)"},children:A.displayName})]},A.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:d,onChange:A=>x(A.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/",d||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:u,onChange:A=>h(A.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"})]}),f&&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:f})]})}),t.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:b?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:N,disabled:!d||!u||g,className:"machine-btn",style:{background:d&&u?"rgba(34,197,94,0.12)":void 0,borderColor:d&&u?"rgba(34,197,94,0.3)":void 0,color:d&&u?"#86efac":void 0,opacity:!d||!u||g?.4:1},children:g?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Ol(e){return e==="cli"||e==="acp"}function V0(e){switch(e){case"detected":return"Detected";case"not_detected":return"Not detected";case"enabled_unchecked":return"Enabled, not checked";case"disabled":return"Disabled";default:return"Disabled"}}function G0(e){switch(e){case"detected":return"bg-green-500/[0.10] border-green-500/25 text-green-400";case"not_detected":return"bg-red-500/[0.10] border-red-500/25 text-red-400";case"enabled_unchecked":return"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400";case"disabled":default:return"bg-white/[0.04] border-white/[0.10] text-text-muted"}}function Fl(e){if(!e)return"No result yet";const s=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${s}: ${r} — ${n}`:`${s}: ${r}`}function q0({machineId:e,providers:s,sendDaemonCommand:r}){var E;const[n,a]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(null),[m,u]=i.useState("all"),[h,g]=i.useState(null),[k,f]=i.useState(!1),[p,b]=i.useState(null),[y,x]=i.useState("normal"),[I,N]=i.useState(""),[j,A]=i.useState(!1),M=i.useCallback(async()=>{if(e)try{const D=await r(e,"get_provider_source_config",{}),S=$l(D);S&&(b(S),x(S.sourceMode),N(S.explicitProviderDir||""))}catch{}},[e,r]),v=i.useCallback(async()=>{if(e){l(!0);try{const D=await r(e,"get_provider_settings",{}),S=F0(D);if(S){const C=K0(S,s,{filterSchema:W=>W.filter(_=>_.key!=="enabled")});C.sort((W,_)=>W.category.localeCompare(_.category)||W.displayName.localeCompare(_.displayName)),a(C)}}catch{}l(!1)}},[e,s,r]);i.useEffect(()=>{n.length===0&&v(),p||M()},[]);const w=async(D,S,C)=>{d(`${D}.${S}`),a(W=>W.map(_=>_.type===D?{..._,values:{..._.values,[S]:C}}:_));try{const W=await r(e,"set_provider_setting",{providerType:D,key:S,value:C});W!=null&&W.success||v()}catch{v()}d(null)},B=async(D,S)=>{await w(D,"enabled",S),await v()},R=async D=>{d(`${D}.detect`);try{await r(e,"detect_provider",{providerType:D})}finally{await v(),d(null)}},T=async D=>{await w(D,"executablePath",""),await w(D,"executableArgs",""),await v()},H=async()=>{A(!0);try{const D=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:W0(I)}),S=$l(D);S?(b(S),x(S.sourceMode),N(S.explicitProviderDir||"")):await M(),await v()}catch{await M()}A(!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(D=>t.jsx("button",{onClick:()=>u(D),className:`machine-btn text-[10px] px-2 py-0.5 ${m===D?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:D.toUpperCase()},D))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>f(!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:o,className:"machine-btn",children:o?"⏳ 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. Running CLI sessions refresh provider scripts/config; process binary changes still apply on next launch."})]}),t.jsx("button",{onClick:M,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:y,onChange:D=>x(D.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:I,onChange:D=>N(D.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void H(),disabled:j,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:j?"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:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((E=p==null?void 0:p.providerRoots)==null?void 0:E.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(D=>D.category===m).length>1&&(()=>{const D=n.filter(_=>_.category===m),S=new Map;for(const _ of D)for(const O of _.schema){if(O.type!=="boolean")continue;const V=S.get(O.key),X=!!(_.values[O.key]??O.default);V?(V.onCount+=X?1:0,V.total+=1):S.set(O.key,{label:O.label||O.key,onCount:X?1:0,total:1})}const C=[...S.entries()].filter(([,_])=>_.total===D.length);if(C.length===0)return null;const W=async(_,O)=>{for(const V of D)await w(V.type,_,O)};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 ",m.toUpperCase()," providers (",D.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:C.map(([_,O])=>{const V=O.onCount===O.total,X=O.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:O.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",O.onCount,"/",O.total,")"]}),t.jsx("button",{onClick:()=>void W(_,!0),disabled:V,className:`machine-btn text-[9px] px-1.5 py-px ${V?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void W(_,!1),disabled:X,className:`machine-btn text-[9px] px-1.5 py-px ${X?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},_)})})]})})(),o&&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(D=>m==="all"||D.category===m).map(D=>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:D.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:D.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:D.category==="acp"?"rgba(139,92,246,0.08)":D.category==="cli"?"rgba(59,130,246,0.08)":D.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:D.category==="acp"?"#a78bfa":D.category==="cli"?"#60a5fa":D.category==="ide"?"#86efac":"var(--status-warning)"},children:D.category}),Ol(D.category)&&(()=>{const S=s.find(_=>_.type===D.type),C=(S==null?void 0:S.enabled)===!0||D.values.enabled===!0,W=(S==null?void 0:S.machineStatus)||(C?"enabled_unchecked":"disabled");return t.jsxs(t.Fragment,{children:[t.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${G0(W)}`,children:V0(W)}),t.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[t.jsx("button",{onClick:()=>void B(D.type,!C),disabled:c===`${D.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${C?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:C?"Disable":"Enable"}),t.jsx("button",{onClick:()=>void R(D.type),disabled:!C||c===`${D.type}.detect`,title:C?"Run detection for the configured executable":"Enable this provider before detection",className:`machine-btn text-[9px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${C?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),t.jsx("button",{onClick:()=>void T(D.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),D.category==="ide"&&t.jsx("button",{onClick:()=>g(s.find(S=>S.type===D.type)||{type:D.type,name:D.displayName,displayName:D.displayName,icon:D.icon,category:D.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"})]}),Ol(D.category)&&(()=>{const S=s.find(C=>C.type===D.type);return t.jsxs("div",{className:"mb-2.5 grid gap-1 rounded-lg border border-white/[0.06] bg-bg-primary/40 px-3 py-2 text-[10px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",Fl(S==null?void 0:S.lastDetection)]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Fl(S==null?void 0:S.lastVerification)]}),t.jsx("div",{className:"text-[9px] text-text-muted",children:"Supported catalog entry only becomes launchable after Enable + Detect succeeds. Custom executable path/args below are machine-local overrides."})]})})(),t.jsx("div",{className:"flex flex-col gap-2",children:D.schema.map(S=>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:[S.label||S.key,c===`${D.type}.${S.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),S.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:S.description})]}),t.jsx("div",{className:"shrink-0",children:S.type==="boolean"?t.jsx("button",{onClick:()=>w(D.type,S.key,!(D.values[S.key]??S.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:D.values[S.key]??S.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:D.values[S.key]??S.default?21:3}})}):S.type==="number"?t.jsx("input",{type:"number",value:Number(D.values[S.key]??S.default??0)||0,min:S.min,max:S.max,onChange:C=>{const W=parseInt(C.target.value)||0;S.min!==void 0&&W<S.min||S.max!==void 0&&W>S.max||w(D.type,S.key,W)},className:"machine-input w-20 text-center text-[11px]"}):S.type==="select"&&S.options?t.jsx("select",{value:String(D.values[S.key]??S.default??""),onChange:C=>w(D.type,S.key,C.target.value),className:"machine-input text-[11px]",children:S.options.map(C=>t.jsx("option",{value:C,children:C},C))}):t.jsx("input",{type:"text",value:String(D.values[S.key]??S.default??""),onBlur:C=>w(D.type,S.key,C.target.value),className:"machine-input w-[120px] text-[11px]"})})]},S.key))})]},D.type))}),h&&t.jsx(U0,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>g(null)}),k&&t.jsx(z0,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>f(!1),onCreated:()=>{f(!1),v()}})]})}const Y0=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function X0({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function J0(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function Q0(e){return e.trim().toLowerCase()}function Yn(e,s){const r=Q0(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function ii(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function qs(e,s=220){const r=ii(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function Z0(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 ev(e,s){return e.filter(r=>Yn([r.level,r.message],s))}function Kl(e){return`${e.timestamp}:${e.level}:${e.message}`}function tv(e,s,r=300){if(s.entries.length>0){const n=new Map;for(const l of e.entries)n.set(Kl(l),l);for(const l of s.entries)n.set(Kl(l),l);const a=Array.from(n.values()).sort((l,c)=>l.timestamp-c.timestamp).slice(-r),o=a.reduce((l,c)=>Math.max(l,Number(c.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:o}}return s.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:s.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function sv(e,s,r=120){if(s.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of s)n.set(a.id,a);return Array.from(n.values()).sort((a,o)=>a.ts-o.ts).slice(-r)}function rv(e,s){return e.split(`
|
|
76
|
-
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Yn([r],s))}function nv(e,s){return e.filter(r=>Yn([r.level,r.category,r.stage,r.interactionId,ii(r.payload)],s))}function av(e,s){return e.filter(r=>Yn([r.kind,r.topic,r.interactionId,ii(r.payload)],s))}function Wl(e){return e==="warn"||e==="error"}function ov({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=>Wl(a.level)).length+r.filter(a=>Wl(a.level)).length}}function iv({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(o=>`${new Date(o.timestamp).toISOString()} ${o.level.toUpperCase()} ${o.message}`)].join(`
|
|
77
|
-
`)):s.length>0&&a.push(["[daemon logs]",...s].join(`
|
|
78
|
-
`)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${qs(o.payload,500)}`.trim())].join(`
|
|
79
|
-
`)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${qs(o.payload,500)}`.trim())].join(`
|
|
80
|
-
`)),a.join(`
|
|
81
|
-
|
|
82
|
-
`)}function lv({machineId:e,sendDaemonCommand:s}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[l,c]=i.useState(""),[d,m]=i.useState([]),[u,h]=i.useState([]),[g,k]=i.useState(null),[f,p]=i.useState(!0),[b,y]=i.useState("info"),[x,I]=i.useState("all"),[N,j]=i.useState(!0),[A,M]=i.useState(!0),[v,w]=i.useState(""),[B,R]=i.useState(""),[T,H]=i.useState(0),E=i.useRef(0),D=i.useRef(0),S=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),C=i.useRef([]),W=i.useCallback(()=>{const ne={entries:[],kind:"empty",rawText:"",lastTs:0};S.current=ne,E.current=0,n([]),c(""),o("empty"),j(!0)},[]),_=i.useCallback(()=>{C.current=[],D.current=0,m([]),M(!0)},[]),O=i.useCallback(ne=>{ne!==b&&(W(),y(ne))},[b,W]),V=i.useCallback(ne=>{I(pe=>pe===ne?pe:ne)},[]),X=i.useCallback(()=>{W(),_(),h([]),k(null),w(""),R(""),Fs.clear()},[W,_]),ye=i.useCallback(()=>{H(ne=>ne+1)},[]),he=i.useCallback(async()=>{if(!e)return;const ne=E.current,pe=D.current,[ke,Se]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:b,since:ne}),s(e,"get_debug_trace",X0({count:120,since:pe,category:x}))]);if(ke.status==="fulfilled"){const G=ke.value,be=(G==null?void 0:G.result)||G,fe=Z0(be),ve=tv(S.current,fe,300);S.current=ve,E.current=ve.lastTs,j(!1),w((G==null?void 0:G.success)===!1?String((G==null?void 0:G.error)||"Could not load daemon logs"):""),o(ve.kind),c(ve.rawText),n(ve.entries)}else j(!1),w(ke.reason instanceof Error?ke.reason.message:"Could not load daemon logs");if(Se.status==="fulfilled"){const G=Se.value,be=(G==null?void 0:G.result)||G;if((G==null?void 0:G.success)===!1)R(String((G==null?void 0:G.error)||"Could not load daemon trace"));else if(Array.isArray(be==null?void 0:be.trace)){const fe=be.trace,ve=sv(C.current,fe,120),P=fe.reduce((me,q)=>Math.max(me,Number(q.ts||0)),pe);C.current=ve,P>pe&&(D.current=P),R(""),m(ve)}else R("");M(!1)}else M(!1),R(Se.reason instanceof Error?Se.reason.message:"Could not load daemon trace");h(Fs.list({limit:120})),k(Date.now())},[b,e,s,x]);return i.useEffect(()=>{_()},[_,x]),i.useEffect(()=>{if(!e||(he(),!f))return;const ne=setInterval(()=>{he()},3e3);return()=>clearInterval(ne)},[f,he,e,T]),{daemonLogs:r,daemonLogKind:a,daemonRawText:l,debugTrace:d,webEvents:u,lastUpdatedAt:g,autoRefresh:f,logLevel:b,traceCategory:x,daemonLoading:N,traceLoading:A,daemonFetchError:v,traceFetchError:B,setAutoRefresh:p,setLogLevel:O,setTraceCategory:V,refresh:ye,clear:X}}function cv({daemonLoading:e,traceLoading:s,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:l,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||l>0?"ok":"empty",detail:r||(a==="text"?`${l} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":s?"loading":c>0?"ok":"empty",detail:n||`${c} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function Hl(e){return e==="warn"||e==="error"}function dv(e){const s=e.toLowerCase();return/\[(err|error)\]/i.test(e)||s.includes(" error ")||s.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||s.includes(" warning ")||s.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function uv(e,s){const r=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(r){const n=Date.parse(r[0]);if(Number.isFinite(n))return n}return Number.MAX_SAFE_INTEGER-1e5+s}function Ul(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function mv(e){const s=qs(e.payload,320);return s?`${e.category}.${e.stage} ${s}`:`${e.category}.${e.stage}`}function pv(e){const s=qs(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return s?`${e.kind}${r} ${s}`:`${e.kind}${r}`}function fv({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.forEach((o,l)=>{a.push({id:`daemon-log-${o.timestamp}-${l}`,source:"daemon_log",ts:Number(o.timestamp||0),severity:o.level,message:o.message,raw:o.message})}),n.forEach(o=>{a.push({id:`browser-event-${o.id}`,source:"browser_event",ts:Number(o.ts||0),severity:"info",message:pv(o),topic:o.topic,interactionId:o.interactionId,payload:o.payload})}),r.forEach(o=>{a.push({id:`daemon-trace-${o.id}`,source:"daemon_trace",ts:Number(o.ts||0),severity:o.level,message:mv(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),s.forEach((o,l)=>{a.push({id:`raw-file-${l}`,source:"raw_file",ts:uv(o,l),severity:dv(o),message:o,raw:o})}),a.sort((o,l)=>o.ts!==l.ts?o.ts-l.ts:Ul(o.source)-Ul(l.source))}function hv(e){return`${e.source}:${e.severity}:${e.message}`}function xv(e){const s=e.filter(n=>Hl(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Hl(n.severity))continue;const a=hv(n),o=r.get(a);o?(o.count+=1,o.firstTs=Math.min(o.firstTs,n.ts),o.lastTs=Math.max(o.lastTs,n.ts)):r.set(a,{key:a,source:n.source,severity:n.severity,message:n.message,count:1,firstTs:n.ts,lastTs:n.ts})}return{totalCount:e.length,issueCount:s.length,latestIssue:s[0]||null,repeatedPatterns:Array.from(r.values()).filter(n=>n.count>1).sort((n,a)=>a.count!==n.count?a.count-n.count:a.lastTs-n.lastTs).slice(0,5)}}function bv(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function zl(e){const s=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${bv(e.ts)} ${e.severity.toUpperCase()} ${e.source}${s}${r} ${e.message}`.trim()}function gv({events:e,summary:s,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${s.totalCount}`,`issue_events: ${s.issueCount}`].join(`
|
|
83
|
-
`)),a.push(["[source status]",...r.map(l=>`${l.label}: ${l.status} - ${l.detail}`)].join(`
|
|
84
|
-
`)),s.latestIssue&&a.push(["[latest issue]",zl(s.latestIssue)].join(`
|
|
85
|
-
`)),s.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...s.repeatedPatterns.map(l=>`${l.count}x ${l.severity.toUpperCase()} ${l.source} ${l.message}`)].join(`
|
|
86
|
-
`));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(zl):["No diagnostic events captured."]].join(`
|
|
87
|
-
`)),a.join(`
|
|
88
|
-
|
|
89
|
-
`)}function yv(e,s){return s==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):s==="info"?e.filter(r=>r.level!=="debug"):e}function vv(e,s){return s==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):s==="info"?e.filter(r=>r.level!=="debug"):e}function wv({daemonLogs:e,daemonRawText:s,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:l,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h}){const g=J0(n,o),k=ev(e,c),f=rv(s,c),p=nv(g,c),b=av(a,c),y=yv(k,l),x=l==="all"?f:[],I=vv(p,l),N=l==="issues"?[]:b,j=ov({daemonLogs:k,daemonRawLines:f,trace:p,webEvents:b}),A=fv({daemonLogs:y,daemonRawLines:x,trace:I,webEvents:N}),M=xv(A),v=cv({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h,daemonLogKind:r,daemonLogsCount:k.length,daemonRawLineCount:f.length,traceCount:p.length,webEventCount:b.length});return{filteredDaemonLogs:k,filteredDaemonRawLines:f,filteredTraceEntries:p,filteredWebEvents:b,visibleDaemonLogs:y,visibleDaemonRawLines:x,visibleTraceEntries:I,visibleWebEvents:N,quickFilterCounts:j,diagnosticEvents:A,diagnosticsSummary:M,sourceStates:v}}function jv(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function xu(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function bo(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 Ba(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 li(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function kv({event:e}){return t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${bo(e.severity)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:xu(e.ts)}),t.jsx("span",{children:e.severity.toUpperCase()}),t.jsx("span",{children:li(e.source)}),e.category&&e.stage&&t.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&t.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&t.jsxs("span",{children:["ix=",e.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function Nv({quickFilter:e,quickFilterCounts:s,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:l,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return 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:"View"}),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+ (${s.info})`},{id:"issues",label:`Issues (${s.issues})`},{id:"all",label:`All (${s.all})`}].map(h=>t.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),t.jsx("input",{value:r,onChange:h=>o(h.target.value),placeholder:"Search diagnostics…",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.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{onClick:l,className:"machine-btn",children:"Copy diagnostics"}),t.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function Sv({logLevel:e,traceCategory:s,onLogLevelChange:r,onTraceCategoryChange:n}){return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:t.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>t.jsxs("button",{onClick:()=>r(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),t.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:Y0.map(a=>t.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${s===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function Cv({diagnosticsSummary:e,diagnosticEventsCount:s,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:l,traceFetchError:c}){var u,h;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=l||c?"danger":o?"good":"neutral";return t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${Ba(e.issueCount>0?"warning":"good")}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[s," visible event(s) · ",e.issueCount," issue signal(s)"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:n.trim()?`Filtered by “${n.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${Ba(d)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[li(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),t.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:xu(e.latestIssue.ts)})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${Ba(m)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:l||c?"Needs attention":o?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",jv(a)]}),t.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(g=>t.jsxs("div",{children:[g.label,": ",g.status]},g.id))})]})]})}function Iv({patterns:e}){return e.length===0?null:t.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),t.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(s=>t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[t.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[s.count,"× ",s.severity.toUpperCase()," · ",li(s.source)]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:s.message})]},s.key))})]})}function Tv({streams:e,sectionsOpen:s,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:l,visibleWebEvents:c,quickFilter:d,searchQuery:m}){return 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:()=>r(u=>({...u,timeline:!u.timeline})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.timeline?"Hide":"Show"})]}),s.timeline&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&t.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&t.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&t.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>t.jsx(kv,{event:u},u.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:()=>r(u=>({...u,daemon:!u.daemon})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.daemon?"Hide":"Show"})]}),s.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:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,h)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((u,h)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${bo(u.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),t.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),t.jsx("span",{className:"break-words",children:u.message})]},`log-${h}`))]})]}),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:()=>r(u=>({...u,trace:!u.trace})),children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.trace?"Hide":"Show"})]}),s.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:[e.traceLoading&&l.length===0&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&l.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&l.length===0&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No trace entries match the current search.":e.traceCategory==="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."}),l.map(u=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${bo(u.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),t.jsx("span",{children:u.level.toUpperCase()}),t.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&t.jsxs("span",{children:["ix=",u.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:qs(u.payload,360)||"No payload"})]},u.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:()=>r(u=>({...u,web:!u.web})),children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.web?"Hide":"Show"})]}),s.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:[c.length===0&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:m.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(u=>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(u.ts).toLocaleTimeString()}),t.jsx("span",{children:u.kind}),u.topic&&t.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&t.jsxs("span",{children:["ix=",u.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:qs(u.payload,360)||"No payload"})]},u.id))]})]})]})}function Av({machineId:e,sendDaemonCommand:s}){const r=lv({machineId:e,sendDaemonCommand:s}),[n,a]=i.useState("info"),[o,l]=i.useState(""),[c,d]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=i.useRef(null),u=i.useRef(!1),h=i.useMemo(()=>wv({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);i.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const f=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:f}),u.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const g=i.useCallback(async()=>{var p;const f=iv({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!f.trim()){ot.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(f)),ot.showToast("Copied visible logs to clipboard.","success")}catch(b){ot.showToast(b instanceof Error?b.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),k=i.useCallback(async()=>{var p;const f=gv({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(f)),ot.showToast("Copied diagnostic bundle to clipboard.","success")}catch(b){ot.showToast(b instanceof Error?b.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return t.jsxs("div",{className:"space-y-4",children:[t.jsx(Nv,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:l,onCopyDiagnostics:()=>{k()},onCopyVisible:()=>{g()},onToggleAutoRefresh:()=>r.setAutoRefresh(f=>!f),onRefresh:r.refresh,onClear:r.clear}),t.jsx(Sv,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),t.jsx(Cv,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),t.jsx(Iv,{patterns:h.diagnosticsSummary.repeatedPatterns}),t.jsx(Tv,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:o}),t.jsx("div",{ref:m})]})}function Mv(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 bu(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 Lv(e){var a;const s=[],r=[],n=[];for(const o of e||[]){const l=String((o==null?void 0:o.lifecycle)||"").trim(),c=bu((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(l)?s.push(o):(l==="stopped"||l==="failed")&&(d||c)?r.push(o):n.push(o)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function Rv(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Oa(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 Fa(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Ka(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Vl(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 _v(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Pv(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 Dv(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 o=`${n.providerType}::${n.workspace}::${a}`;s.set(o,(s.get(o)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function Ev({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,l]=i.useState(null),[c,d]=i.useState(!1),m=db(e,{enabled:!!e,includeSessions:!0,limit:Wi,intervalMs:oh}),u=m.diagnostics,h=m.loading,g=m.applyDiagnostics,k=i.useMemo(()=>Mv({diagnostics:u,loading:h,refreshing:c,error:n}),[u,h,c,n]),f=i.useMemo(()=>new Map(s.map(R=>[R.sessionId||R.id,R])),[s]),p=i.useCallback(async()=>{if(e){d(!0);try{const R=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Wi}),T=Fa(R);if(!(T!=null&&T.success))throw new Error((T==null?void 0:T.error)||"Could not load hosted runtime diagnostics");g(T.diagnostics||T.result||null),a("")}catch(R){const T=R instanceof Error?R.message:"Could not load hosted runtime diagnostics";a(T)}finally{d(!1)}}},[g,e,r]);i.useEffect(()=>{!e||u||h||c||p()},[u,h,e,p,c]);const b=i.useCallback(async(R,T)=>{const H=`${R}:${T.sessionId}`;if(!(R==="session_host_stop_session"&&!window.confirm(`Stop ${T.displayName}?
|
|
90
|
-
This will terminate the hosted runtime.`))){l(H);try{const E=await r(e,R,{sessionId:T.sessionId}),D=Fa(E);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Session host action failed");const S=R==="session_host_resume_session"?"resumed":R==="session_host_restart_session"?"restarted":"stopped";ot.showToast(`Session host ${S}: ${T.displayName}`,"success"),await p()}catch(E){const D=E instanceof Error?E.message:"Session host action failed";ot.showToast(D,"warning"),a(D)}finally{l(E=>E===H?null:E)}}},[e,p,r]),y=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
91
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){l("session_host_prune_duplicate_sessions");try{const T=await r(e,"session_host_prune_duplicate_sessions",{}),H=Fa(T);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Duplicate prune failed");const E=H.result||{},D=Array.isArray(E.prunedSessionIds)?E.prunedSessionIds.length:0,S=typeof E.duplicateGroupCount=="number"?E.duplicateGroupCount:0;ot.showToast(`Pruned ${D} duplicate runtime(s) across ${S} group(s)`,"success"),await p()}catch(T){const H=T instanceof Error?T.message:"Duplicate prune failed";ot.showToast(H,"warning"),a(H)}finally{l(T=>T==="session_host_prune_duplicate_sessions"?null:T)}}},[e,p,r]),x=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((R,T)=>(T.lastActivityAt||0)-(R.lastActivityAt||0)),[u==null?void 0:u.sessions]),I=i.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:Lv(x),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,x]),N=I.liveRuntimes,j=I.recoverySnapshots,A=I.inactiveRecords,M=i.useMemo(()=>Dv(N),[N]),v=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),w=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(R=>R.level==="warn"||R.level==="error")||null,[u==null?void 0:u.recentLogs]),B=(R,T)=>{var V;const H=o===`session_host_resume_session:${R.sessionId}`,E=o===`session_host_restart_session:${R.sessionId}`,D=o===`session_host_stop_session:${R.sessionId}`,S=bu(R.meta),C=f.get(R.sessionId),W=R.attachedClients.length===1?"1 client":`${R.attachedClients.length} clients`,_=T==="recovery"?"Recover":"Resume",O=Rv(T);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:R.displayName||(C==null?void 0:C.cliName)||R.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Pv(R.lifecycle)}`,children:R.lifecycle}),S&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:S})]}),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:R.workspaceLabel||(C==null?void 0:C.runtimeWorkspaceLabel)||R.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:R.runtimeKey}),R.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",R.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((V=R.writeOwner)==null?void 0:V.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:_v(R.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(oc,{size:11})," ",W]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",Vl(R.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",O]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[T==="recovery"&&(R.lifecycle==="interrupted"||R.lifecycle==="failed"||R.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{b("session_host_resume_session",R)},children:H?`${_}ing…`:_}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{b("session_host_restart_session",R)},children:E?"Restarting…":"Restart"}),T==="live"&&(R.lifecycle==="running"||R.lifecycle==="starting"||R.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:!!o,onClick:()=>{b("session_host_stop_session",R)},children:D?"Stopping…":"Stop"})]})]})},R.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(as,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:ux()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[M>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${M})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${k.toneClass}`,children:k.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||c,children:[t.jsx(Tr,{size:13}),h||c?"Refreshing…":"Refresh"]})]})]}),n&&!u&&t.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(Sr,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:j.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Vl(u.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Ka(u.hostStartedAt)})]})]}),w&&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(Sr,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:w.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Ka(w.timestamp),w.sessionId?` · ${w.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(Co,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Oa("live")}),N.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:N.map(R=>B(R,"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(as,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Oa("recovery")}),j.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:j.map(R=>B(R,"recovery"))})]}),A.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:Oa("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:A.map(R=>B(R,"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(R=>{var H;const T=x.find(E=>E.sessionId===R.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(T==null?void 0:T.displayName)||((H=f.get(R.sessionId))==null?void 0:H.cliName)||R.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[R.action,R.lifecycle?` · ${R.lifecycle}`:"",R.detail?` · ${R.detail}`:"",R.error?` · ${R.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${R.success===!1?"text-red-300":"text-text-secondary"}`,children:Ka(R.timestamp)})]},`${R.sessionId}:${R.timestamp}:${R.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function $v({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(o=>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:o.id,argsStr:s.argsStr,model:s.model})},children:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.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 Wa({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 Ha({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 Bv({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:l}){const c=n.slice(0,6),d=r.slice(0,4),m="0.9.81",u=Rd(e),h=Ps(e,m),g=yr(e,h),k=u==="preview"?"Update to preview":"Update daemon";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:[c.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Wa,{icon:t.jsx(Jt,{size:13}),children:"Current Chats"}),t.jsx(Ha,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(f=>{const p=po(f);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>l(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:dt(f)}),p>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:$n(p)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Ss(f)})]},f.tabKey)})})})]}),d.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Wa,{icon:t.jsx(dc,{size:13}),children:"Recent Launches"}),t.jsx(Ha,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const{metaText:p,updatedLabel:b}=Ud(f);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),b&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:b})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Wa,{icon:t.jsx(Sr,{size:13}),children:"Daemon Update"}),t.jsx(Ha,{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:g?"Daemon update required":"Version mismatch detected"}),t.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[g?"This machine is on an incompatible daemon version. Update it before starting more sessions.":u==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",h&&t.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",h,u?` (${u})`:""]})]}),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(Tr,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:k})]})]})})]})]})}function Ov(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function Fv({machine:e,selectedWorkspace:s,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:l,onOpenBrowseDialog:c}){return t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:s,onChange:d=>{const m=d.target.value;if(o(m),m==="__custom__"&&a){c();return}m!=="__custom__"&&l("")},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:(e.workspaces||[]).length>0?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>t.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",On(d.path,d.label)]},d.id)),t.jsx("option",{value:"__custom__",children:a?"📁 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:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),s==="__custom__"&&(a?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:c,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>l(d.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:s==="__custom__"?r?t.jsx("span",{className:"font-mono truncate block",title:r,children:r}):a?"Browse to a folder before launching there.":"Enter an absolute path to launch there.":r?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:s===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const Kv={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 nn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ua({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:l,sendDaemonCommand:c,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const h=ls(),{handleLaunchIde:g,handleStopCli:k,handleRestartIde:f,handleStopIde:p,handleDetectIdes:b,launchingIde:y,launchingAgentType:x,addLog:I}=l,[N,j]=i.useState(null),A=i.useCallback(L=>{L&&h(zt(L))},[h]),M=Kv[e],v=e==="ide",w=e==="acp",B=i.useMemo(()=>n.filter(L=>Cs(L,e)),[e,n]),R=i.useMemo(()=>new Map(B.map(L=>[L.type,L.displayName||L.type])),[B]),[T,H]=i.useState(""),[E,D]=i.useState(""),[S,C]=i.useState([]),[W,_]=i.useState(""),[O,V]=i.useState(""),[X,ye]=i.useState([]),[he,ne]=i.useState(!1),[pe,ke]=i.useState(!1),[Se,G]=i.useState(""),[be,fe]=i.useState(!1),[ve,P]=i.useState(()=>Nt()),[me,q]=i.useState(null),[de,ae]=i.useState(m?"__custom__":d||s.defaultWorkspaceId||""),[xe,ue]=i.useState(m||""),[ce,te]=i.useState([]),[$,J]=i.useState(!1),[oe,ee]=i.useState(""),[Ne,Ce]=i.useState([]),[we,K]=i.useState(!1),[Ie,Re]=i.useState(""),Ke=i.useRef(null),[He,qe]=i.useState(null),Ye=i.useRef("__home__"),[st,mt]=i.useState("__home__"),[ht,yt]=i.useState(!1),Te=i.useRef(0),Ue=ce.filter(L=>!a.some(Q=>Q.type===L&>(Q.status)!=="stopped")),et=i.useRef({});i.useEffect(()=>{s.defaultWorkspaceId&&!de&&ae(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),i.useEffect(()=>{if(m){ae("__custom__"),ue(m);return}d&&(ae(d),ue(""))},[d,m]),i.useEffect(()=>{v||T&&(B.some(L=>L.type===T)||(H(""),V("")))},[B,v,T]);const ze=(()=>{if(de==="__custom__")return xe.trim();if(!de)return"";const L=(s.workspaces||[]).find(Q=>Q.id===de);return(L==null?void 0:L.path)||""})(),at=i.useCallback(L=>{const Q=et.current[L];Q&&(clearTimeout(Q),delete et.current[L]),te(ge=>ge.includes(L)?ge.filter($e=>$e!==L):ge)},[]),U=i.useRef(new Set),z=i.useCallback(async L=>{if(c){K(!0),Re("");try{const Q=await Vn(c,r,L);ee(Q.path),ue(Q.path),Ce(Q.directories)}catch(Q){Re(Q instanceof Error?Q.message:"Could not load folder")}finally{K(!1)}}},[r,c]),Z=i.useCallback(()=>{if(!c)return;ae("__custom__"),J(!0);const L=a.map(ge=>ge.workspace),Q=zn(s.platform,Un(xe.trim(),ze,m,L,s.defaultWorkspacePath,(s.workspaces||[]).map(ge=>ge.path)));z(Q)},[xe,m,z,s.defaultWorkspacePath,s.platform,s.workspaces,a,ze,c]),ie=i.useCallback(L=>{const Q=String(L.workspace||"").trim();if(!Q)return;const ge=(s.workspaces||[]).find($e=>nn($e.path)===nn(Q));if(ge){ae(ge.id),ue("");return}ae("__custom__"),ue(Q)},[s.workspaces]),F=i.useCallback(L=>{const Q=String(L.workspace||"").trim();if(!Q)return{workspaceId:null,workspacePath:"",useHome:!0};const ge=(s.workspaces||[]).find($e=>nn($e.path)===nn(Q));return ge?{workspaceId:ge.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Q,useHome:!1}},[s.workspaces]),Y=i.useCallback(async L=>{if(!c||!L||e!=="cli"){ye([]),ne(!1),ke(!1),G("");return}const Q=Te.current+1;Te.current=Q,ne(!0),G("");try{const ge=await c(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(Te.current!==Q)return;const $e=(ge==null?void 0:ge.result)??ge;ye(Array.isArray($e==null?void 0:$e.sessions)?$e.sessions:[])}catch(ge){if(Te.current!==Q)return;ye([]),G(ge instanceof Error?ge.message:"Could not load saved sessions")}finally{Te.current===Q&&(ne(!1),ke(!0))}},[e,r,c]),re=i.useMemo(()=>{if(e!=="cli"||!T)return null;const L=R.get(T)||T;return{routeId:r,daemonId:r,providerSessionId:O||void 0,transport:"pty",mode:"chat",agentName:L,agentType:T,status:"idle",title:L,messages:[],ideType:T,workspaceName:ze,workspacePath:ze,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${T}`}},[e,r,R,ze,O,T]),le=i.useCallback(L=>{if(e==="ide"||!L){C([]);return}C(xo(r,L))},[e,r]),je=i.useCallback((L,Q)=>{e==="ide"||!L||(Ny(r,L,Q),C(xo(r,L)))},[e,r]);i.useEffect(()=>{Te.current+=1,V(""),le(T),ke(!1),ye([]),G(""),ne(!1)},[e,le,Y,T]);const _e=i.useMemo(()=>X.find(L=>L.providerSessionId===O)||null,[X,O]);i.useEffect(()=>{if(!O)return;const L=X.find(Q=>Q.providerSessionId===O);L!=null&&L.canResume||V("")},[X,O]);const De=i.useCallback((L,Q)=>{Ke.current=Q,Ye.current=L.selectedWorkspaceKey||"__home__",mt(L.selectedWorkspaceKey||"__home__"),qe(L)},[]),Me=i.useCallback(()=>{Ke.current&&(yt(!0),Ke.current().finally(()=>{Ke.current=null,yt(!1),qe(null)}))},[]),Ee=i.useCallback(L=>{if(!L)return;te(ge=>ge.includes(L)?ge:[...ge,L]);const Q=et.current[L];Q&&clearTimeout(Q),et.current[L]=setTimeout(()=>{te(ge=>ge.includes(L)?ge.filter($e=>$e!==L):ge),delete et.current[L]},2e4)},[]);i.useEffect(()=>{for(const Q of a)gt(Q.status)!=="stopped"&&(ce.includes(Q.type)&&!U.current.has(Q.type)&&(U.current.add(Q.type),I("info",`${R.get(Q.type)||Q.type} launched`,!0)),at(Q.type));const L=new Set(a.filter(Q=>gt(Q.status)!=="stopped").map(Q=>Q.type));U.current.forEach(Q=>{!ce.includes(Q)&&!L.has(Q)&&U.current.delete(Q)})},[I,at,a,ce,R]),i.useEffect(()=>()=>{Object.values(et.current).forEach(clearTimeout),et.current={}},[]);const[Oe,Ae]=i.useState({}),[Xe,Qe]=i.useState(null);i.useEffect(()=>{if(!v||!r||!c)return;(async()=>{try{const Q=await c(r,"get_ide_extensions",{}),ge=(Q==null?void 0:Q.result)||Q;ge!=null&&ge.success&&(ge!=null&&ge.ideExtensions)&&Ae(ge.ideExtensions)}catch{}})()},[v,r,c]);const xt=L=>v?lt(L.type):e==="cli"?L.cliName:L.acpName,bt=v?s.detectedIdes||[]:[],ct=i.useCallback(async L=>{const Q=(L==null?void 0:L.type)||T,ge=(L==null?void 0:L.workspacePath)??ze;if(v){await g(Q,ge?{workspace:ge}:void 0)&&Ee(Q);return}const $e=await l.runLaunchCliCore({cliType:Q,dir:L!=null&&L.workspaceId?void 0:ge||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!ge,argsStr:(L==null?void 0:L.argsStr)??(E||void 0),model:(L==null?void 0:L.model)??(w&&W||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!w&&e==="cli"&&Q===T&&O||void 0});if($e.success||$e.pending){const Le=(L==null?void 0:L.argsStr)??E;!v&&(Le!=null&&Le.trim())&&(nu(r,Q,Le),le(Q)),Ee(Q),$e.success&&$e.sessionId&&A($e.sessionId)}},[l,g,w,v,E,W,le,Ee,r,A,ze,O,T]),pt=sd(v?"ide":w?"acp":"cli",!v&&!w&&!!O),We=rd(v?"ide":w?"acp":"cli",!v&&!w&&!!O),Ot=()=>{var Le;const L=v?lt(T):R.get(T)||T,Q=!v&&!w&&!!O,{options:ge,selectedKey:$e}=ws({machine:s,currentWorkspaceId:de&&de!=="__custom__"?de:null,currentWorkspacePath:ze});De({title:Q?zo(L):xs("start-fresh",L),description:Q?Vo():bs("start-fresh"),confirmLabel:pt,busyLabel:We,workspaceOptions:ge,selectedWorkspaceKey:$e,details:[{label:"Mode",value:M.label},{label:"Provider",value:L},...!v&&e==="cli"&&O?[{label:"Resume",value:((Le=X.find(Be=>Be.providerSessionId===O))==null?void 0:Le.title)||O}]:[],...!v&&E.trim()?[{label:"Arguments",value:E.trim()}]:[],...w&&W.trim()?[{label:"Model",value:W.trim()}]:[]]},async()=>{const Be=ge.find(rt=>rt.key===Ye.current);Be!=null&&Be.workspaceId?(ae(Be.workspaceId),ue("")):Be!=null&&Be.workspacePath?(ae("__custom__"),ue(Be.workspacePath)):(ae(""),ue("")),await ct({workspaceId:(Be==null?void 0:Be.workspaceId)??null,workspacePath:(Be==null?void 0:Be.workspacePath)??"",useHome:!(Be!=null&&Be.workspaceId)&&!(Be!=null&&Be.workspacePath)})})},se=L=>{v?p(L):k(L.type,L.workspace,L.id)},Pe=i.useCallback(async(L,Q,ge=!1)=>{if(L.mode===Q){ge&&L.sessionId&&A(L.sessionId);return}if(!c||!L.sessionId){ge&&L.sessionId&&A(L.sessionId);return}try{await c(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:Q}),ge&&A(L.sessionId)}catch($e){const Le=kd($e);jd($e)?console.warn(Le?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",$e instanceof Error?$e.message:String($e)):console.error("Failed to switch CLI view mode:",$e)}},[r,A,c]);return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${M.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 ",M.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:v?bt.length>0?bt.map(L=>{const Q=a.find(rt=>(rt.type||"").toLowerCase()===(L.type||"").toLowerCase()&>(rt.status)!=="stopped"),ge=L.running||!!Q,$e=!!Q&&Q.cdpConnected,Le=ce.includes(L.type||L.id||""),Be=T===(L.type||"");return t.jsxs("button",{onClick:()=>{if($e&&Q){const rt=Q.sessionId;rt?h(zt(rt),{state:{openRemoteForTabKey:rt}}):h("/dashboard",{state:{openRemoteForTabKey:Q.id}});return}Le||H(rt=>rt===(L.type||"")?"":L.type||"")},disabled:!!y||Le,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${$e?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Be?"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:y&&y!==L.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:o(L.type)}),ge&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${$e?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.name||lt(L.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${$e?"text-green-400":Le?"text-orange-400":Be?"text-accent-primary":"text-text-muted"}`,children:$e?"Open Session":Le?"Starting...":Be?"Configure":"Select"})]})]},L.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:b,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(Pm,{size:14})," Scan System"]})]}):B.length>0?B.map(L=>{const Q=T===L.type,ge=ce.includes(L.type),Le=!!a.find(Be=>Be.type===L.type&>(Be.status)!=="stopped");return t.jsxs("button",{onClick:()=>H(Be=>Be===L.type?"":L.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Q?"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:L.icon}),Le&&t.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 rounded-full bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ge?"text-orange-400":Q?"text-accent-primary":"text-text-muted"}`,children:ge?"Starting...":Q?"Configure":"Select"})]})]},L.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."})]})}),T&&(v?bt.find(L=>L.type===T):B.find(L=>L.type===T))&&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:v?lt(T):R.get(T)||T})]}),t.jsx(Fv,{machine:s,selectedWorkspace:de,resolvedWorkspacePath:ze,customPath:xe,canBrowse:!!c,onWorkspaceChange:ae,onCustomPathChange:ue,onOpenBrowseDialog:Z}),!v&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!w&&e==="cli"&&t.jsx(ou,{busy:!!x||!!y||ce.includes(T),savedSessionsLoading:he,savedSessionsError:Se,savedSessionsLoaded:pe,savedSessionsCount:X.length,selectedSession:_e,onRefresh:()=>void Y(T),onOpenHistory:()=>{T&&(fe(!0),au({hasLoadedInitialResults:pe,isLoading:he})&&Y(T))},onClearSelection:()=>V("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[w&&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:W,onChange:L=>_(L.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:E,onChange:L=>D(L.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"}),S.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:S.map(L=>t.jsxs("div",{className:"inline-flex max-w-full items-stretch overflow-hidden rounded-md border border-[#ffffff1a] bg-bg-tertiary text-xs text-text-secondary transition-colors hover:border-accent-primary/40 hover:text-text-primary",title:L,children:[t.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>D(L),children:L}),t.jsx("button",{type:"button",className:"flex items-center justify-center border-l border-[#ffffff1a] px-1.5 text-text-muted transition-colors hover:bg-status-error/10 hover:text-status-error focus:outline-none focus:ring-1 focus:ring-status-error/50",onClick:()=>je(T,L),"aria-label":`Remove startup arguments: ${L}`,title:"Remove startup arguments",children:t.jsx(vt,{size:12})})]},L))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Ot,disabled:!!x||!!y||ce.includes(T),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:x===T||y===T?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+ce.filter(L=>!a.some(Q=>Q.type===L&>(Q.status)!=="stopped")).length,")"]}),a.length===0&&Ue.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 ",M.plural," running"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ue.map(L=>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:o(L)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:v?lt(L):R.get(L)||L}),t.jsx("div",{className:"text-[11px] text-text-muted",children:x===L?"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:${L}`)),a.map(L=>{const Q=v?L:null,ge=!v&&!w?L:null,$e=gt(L.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:o(L.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[xt(L),(Q==null?void 0:Q.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Q.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[t.jsx("span",{className:"truncate",children:L.workspace||"—"}),u&&L.git&&L.workspace?t.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Le=>{Le.stopPropagation(),u(L.daemonId??r,L.workspace)},children:t.jsx(zs,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):t.jsx(zs,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ge==null?void 0:ge.mode)&&t.jsx("span",{className:ge.mode==="chat"?"text-violet-400":"text-text-secondary",children:ge.mode==="chat"?"Chat view":"Terminal view"})]}),ge&&(ge.runtimeKey||ge.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ge.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 ",ge.runtimeKey]}),t.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Le;(Le=navigator.clipboard)==null||Le.writeText(`adhdev attach ${ge.runtimeKey}`),j(ge.runtimeKey||null),window.setTimeout(()=>{j(Be=>Be===ge.runtimeKey?null:Be)},1200)},children:N===ge.runtimeKey?"Copied":"Copy"})]}),ge.runtimeWriteOwner&&t.jsx("span",{style:{color:ge.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ge.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Ov(ge.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${$e==="stopped"?"bg-red-500/[0.08] text-red-500":$e==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:$e}),v&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Le=L.sessionId;if(Le){h(zt(Le),{state:{openRemoteForTabKey:Le}});return}h("/dashboard",{state:{openRemoteForTabKey:L.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(Mt,{size:13})}),t.jsx("button",{onClick:()=>{const Le=L.workspace||"",{options:Be,selectedKey:rt}=ws({machine:s,currentWorkspacePath:Le});De({title:xs("restart-ide",lt(L.type)),description:bs("restart-ide"),confirmLabel:Vs("restart-ide"),busyLabel:Gs("restart-ide"),workspaceOptions:Be,selectedWorkspaceKey:rt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:lt(L.type)}]},async()=>{const It=Be.find(Zt=>Zt.key===Ye.current),ft=(It==null?void 0:It.workspacePath)??"";if(ft&&ft!==Le){await ct({type:L.type,workspacePath:ft});return}await f(L)})},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(Tr,{size:14})})]}),w&&t.jsx("button",{onClick:()=>{const Le=L.sessionId;Le&&A(Le)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!L.sessionId,children:t.jsx(Jt,{size:14})}),ge&&$e!=="stopped"&&t.jsxs(t.Fragment,{children:[ge.mode&&t.jsx(Wo,{mode:ge.mode,onChange:Le=>void Pe(ge,Le,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Le=L.sessionId;Le&&A(Le)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!L.sessionId,children:ge.mode==="chat"?t.jsx(Jt,{size:14}):t.jsx(Mt,{size:13})})]}),$e==="stopped"?t.jsx("button",{onClick:()=>{const Le=L.workspace||"",Be=v?lt(L.type):xt(L),{options:rt,selectedKey:It}=ws({machine:s,currentWorkspacePath:Le});De({title:xs("restart-stopped",Be),description:bs("restart-stopped"),confirmLabel:Vs("restart-stopped"),busyLabel:Gs("restart-stopped"),workspaceOptions:rt,selectedWorkspaceKey:It,details:[{label:"Mode",value:M.label},{label:"Provider",value:Be}]},async()=>{const ft=rt.find(Zt=>Zt.key===Ye.current);await ct({type:L.type,workspaceId:(ft==null?void 0:ft.workspaceId)??null,workspacePath:(ft==null?void 0:ft.workspacePath)??"",useHome:!(ft!=null&&ft.workspaceId)&&!(ft!=null&&ft.workspacePath)})})},disabled:ce.includes(L.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:ce.includes(L.type)?"⏳":t.jsx(Io,{size:14})}):t.jsx("button",{onClick:()=>se(L),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(vt,{size:14})})]})]}),Q&&Q.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Q.aiAgents.map(Le=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${kn(Le.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Le.name," · ",gt(Le.status)]},Le.id))}),Q&&(Oe[Q.type]||[]).length>0&&c&&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:(Oe[Q.type]||[]).map(Le=>t.jsxs("button",{disabled:Xe===`${Q.type}.${Le.type}`,onClick:async()=>{const Be=`${Q.type}.${Le.type}`;Qe(Be);try{await c(r,"set_ide_extension",{ideType:Q.type,extensionType:Le.type,enabled:!Le.enabled}),Ae(rt=>({...rt,[Q.type]:(rt[Q.type]||[]).map(It=>It.type===Le.type?{...It,enabled:!It.enabled}:It)}))}catch(rt){console.error("Extension toggle failed:",rt)}finally{Qe(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Le.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Le.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Le.name,t.jsx("span",{className:"text-[9px] font-normal",children:Le.enabled?"ON":"OFF"})]},Le.type))})]})]},L.id)})]}),$&&c&&t.jsx(Gn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:oe,directories:Ne,busy:we,error:Ie,confirmLabel:"Use this folder",onClose:()=>J(!1),onNavigate:L=>{z(L)},onConfirm:L=>{ue(L),ae("__custom__"),J(!1)}}),He&&t.jsx(si,{title:He.title,description:He.description,details:He.details,workspaceOptions:He.workspaceOptions,selectedWorkspaceKey:st,onWorkspaceChange:L=>{Ye.current=L,mt(L)},confirmLabel:He.confirmLabel,busyLabel:He.busyLabel,busy:ht,onConfirm:Me,onCancel:()=>{Ke.current=null,qe(null)}}),be&&re&&t.jsx(Go,{activeConv:re,ides:[],isCreatingChat:!1,isRefreshingHistory:he,savedSessions:X,isSavedSessionsLoading:he,isResumingSavedSessionId:me,savedHistoryFilters:ve,missingWorkspaceResumePath:ze||null,onSavedHistoryFiltersChange:P,onClose:()=>fe(!1),onNewChat:()=>{V(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{Y(T)},onResumeSavedSession:L=>{if(!L.canResume||me)return;const Q=F(L);V(L.providerSessionId),ie(L),q(L.providerSessionId),fe(!1),ct({type:L.providerType,workspaceId:Q.workspaceId,workspacePath:Q.workspacePath,useHome:Q.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{q(ge=>ge===L.providerSessionId?null:ge)})}})]})}const Gl=[{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 Wv({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:l,getIcon:c,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:h,onOpenGitDialog:g}){var b;const[k,f]=i.useState(d);i.useEffect(()=>{f(d)},[d]);const p=i.useMemo(()=>({ide:n.length,cli:a.length,acp:o.length}),[n.length,a.length,o.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:Gl.map(y=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${k===y.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>f(y.id),children:[t.jsx("span",{children:y.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${k===y.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[y.id]})]},y.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(b=Gl.find(y=>y.id===k))==null?void 0:b.helper})]}),k==="ide"&&t.jsx(Ua,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:g}),k==="cli"&&t.jsx(Ua,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:g}),k==="acp"&&t.jsx(Ua,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:o,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:g})]})}function Hv({onNicknameSynced:e}={}){var ue,ce,te,$,J,oe,ee,Ne,Ce,we;const{id:s}=nm(),r=ls(),n=wo(),{sendCommand:a}=wt(),o=Lr(),l=bd(),c=qc(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(K=>K.id===s&&K.type==="adhdev-daemon"),h=d.some(K=>K.type==="adhdev-daemon"),g=s?(ue=c.connectionRetryStatuses)==null?void 0:ue[s]:void 0,k=!!(g!=null&&g.blocked),[f,p]=i.useState("workspace"),[b,y]=i.useState(null),x=i.useCallback((K,Ie)=>{y({daemonId:K,workspace:Ie})},[]),[I,N]=i.useState("ide"),j=i.useRef(null),[A,M]=i.useState(null),v=i.useRef("__home__"),[w,B]=i.useState("__home__"),[R,T]=i.useState(!1),H=i.useRef(null);i.useEffect(()=>{!s||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(s,{minFreshMs:3e4}).catch(()=>{})},[o,u,s]),i.useEffect(()=>{if(!s||!u||f!=="overview")return;const K=u.machine;(typeof(K==null?void 0:K.cpus)!="number"||typeof(K==null?void 0:K.totalMem)!="number"||typeof(K==null?void 0:K.arch)!="string"||typeof(K==null?void 0:K.release)!="string")&&l(s,{minFreshMs:3e4}).catch(()=>{})},[f,l,u,s]),cb(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:sh});const E=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},D=B0({machineId:s,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:H});i.useEffect(()=>ot.onToast(Ie=>{c.setToasts(Ke=>{if(Ke.some(Ye=>Ye.message===Ie.message&&Ie.timestamp-Ye.timestamp<3e3))return Ke;const qe={id:Ie.id,message:Ie.message,type:Ie.type,timestamp:Ie.timestamp,targetKey:Ie.targetKey,actions:Ie.actions};return[...Ke.slice(-4),qe]});const Re=Ie.duration||5e3;setTimeout(()=>c.setToasts(Ke=>Ke.filter(He=>He.id!==Ie.id)),Re)}),[c]);const S=(u==null?void 0:u.availableProviders)||[],C={};for(const K of S)C[K.type]=K.icon;const W=K=>C[K]||"",_=u?{id:u.id,hostname:jc(u,{fallbackId:u.id}),platform:((ce=u.machine)==null?void 0:ce.platform)||"unknown",arch:((te=u.machine)==null?void 0:te.arch)||"",cpus:(($=u.machine)==null?void 0:$.cpus)||0,totalMem:((J=u.machine)==null?void 0:J.totalMem)||0,freeMem:(oe=u.machine)==null?void 0:oe.freeMem,availableMem:(ee=u.machine)==null?void 0:ee.availableMem,loadavg:(Ne=u.machine)==null?void 0:Ne.loadavg,uptime:(Ce=u.machine)==null?void 0:Ce.uptime,release:((we=u.machine)==null?void 0:we.release)||"",cdpConnected:!!u.cdpConnected,machineNickname:u.machineNickname||null,p2p:u.p2p?{screenshotActive:!1,...u.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:u.detectedIdes||[],workspaces:u.workspaces||[],defaultWorkspaceId:u.defaultWorkspaceId??u.activeWorkspaceId??null,defaultWorkspacePath:u.defaultWorkspacePath??u.activeWorkspacePath??null}:null,O=d.filter(K=>K.daemonId===s&&K.type!=="adhdev-daemon").filter(K=>!Cr(K)&&!$s(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,version:K.version||"",instanceId:K.instanceId||"",status:K.status,workspace:K.workspace||null,terminals:K.terminals||0,aiAgents:Gp(K.aiAgents||(K.agents||[]).map(Ie=>({id:Ie.name,name:Ie.name,status:Ie.status,version:Ie.version}))),activeChat:K.activeChat||null,chats:K.chats||[],childSessions:K.childSessions||[],cdpConnected:K.cdpConnected||!1,daemonId:s,lastMessageAt:K.lastMessageAt})),V=d.filter(K=>K.daemonId===s&&Cr(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,cliName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,mode:K.mode,runtimeKey:K.runtimeKey,runtimeDisplayName:K.runtimeDisplayName,runtimeWorkspaceLabel:K.runtimeWorkspaceLabel,runtimeWriteOwner:K.runtimeWriteOwner||null,runtimeAttachedClients:K.runtimeAttachedClients||[],daemonId:s,lastMessageAt:K.lastMessageAt})),X=d.filter(K=>K.daemonId===s&&$s(K)).map(K=>({id:K.id,sessionId:K.sessionId,type:K.type,acpName:K.cliName||K.type,status:K.status,workspace:K.workspace||"",activeChat:K.activeChat||null,providerSessionId:K.providerSessionId,daemonId:s,lastMessageAt:K.lastMessageAt})),ye=u?At(u,{fallbackId:s}):"",he="workspace",ne=n.state,pe=ne==null?void 0:ne.initialMachineTab,ke=ne==null?void 0:ne.initialWorkspaceCategory,Se=ne==null?void 0:ne.initialWorkspaceId,G=ne==null?void 0:ne.initialWorkspacePath,be=pe==="ides"||pe==="clis"||pe==="acps"?"workspace":pe||he,fe=pe==="ides"?"ide":pe==="clis"?"cli":pe==="acps"?"acp":ke,ve=[...O.map(K=>{var Ie;return{id:`ide:${K.type}:${K.workspace||""}`,label:((Ie=K.activeChat)==null?void 0:Ie.title)||K.type,kind:"ide",providerType:K.type,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:K.lastMessageAt||0}}),...V.map(K=>{var Ie;return{id:`cli:${K.type}:${K.workspace||""}`,label:((Ie=K.activeChat)==null?void 0:Ie.title)||K.cliName,kind:"cli",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:K.lastMessageAt||0}}),...X.map(K=>{var Ie;return{id:`acp:${K.type}:${K.workspace||""}`,label:((Ie=K.activeChat)==null?void 0:Ie.title)||K.acpName,kind:"acp",providerType:K.type,providerSessionId:K.providerSessionId,subtitle:Ns(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace||void 0,lastLaunchedAt:K.lastMessageAt||0}})].sort((K,Ie)=>(Ie.lastLaunchedAt||0)-(K.lastLaunchedAt||0)),P=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(K=>({id:K.id,label:K.title||K.providerName||K.providerType,kind:K.kind,providerType:K.providerType,providerSessionId:K.providerSessionId,subtitle:Ns(K.summaryMetadata)||K.workspace||void 0,workspace:K.workspace,summaryMetadata:K.summaryMetadata,lastLaunchedAt:K.lastLaunchedAt})):ve,me=i.useMemo(()=>{var Ie;const K=((Ie=c.connectionStates)==null?void 0:Ie[s||""])||void 0;return d.filter(Re=>Re.daemonId===s&&Re.type!=="adhdev-daemon").flatMap(Re=>qo(Re,{connectionStates:s&&K?{[s]:K}:void 0,defaultConnectionState:K})).filter(Re=>!(Re.transport==="pty"&&Re.mode==="terminal")).sort((Re,Ke)=>po(Ke)-po(Re))},[d,c.connectionStates,s]),q=i.useCallback(K=>{const Ie=$d(K);Ie&&r(zt(Ie))},[r]),de=i.useCallback(()=>{j.current&&(T(!0),j.current().finally(()=>{j.current=null,T(!1),M(null)}))},[]),ae=i.useCallback(K=>{if(!_)return;const{options:Ie,selectedKey:Re}=ws({machine:_,currentWorkspacePath:K.workspace}),Ke=async()=>{N(K.kind),p("workspace")};j.current=async()=>{const He=Ie.find(st=>st.key===v.current),qe=(He==null?void 0:He.workspacePath)??null,Ye=(He==null?void 0:He.workspaceId)??null;if(K.kind==="ide"&&K.providerType){await D.handleLaunchIde(K.providerType,qe?{workspace:qe}:void 0);return}if((K.kind==="cli"||K.kind==="acp")&&K.providerType){await D.runLaunchCliCore({cliType:K.providerType,dir:Ye?void 0:qe||"",workspaceId:Ye||void 0,model:K.kind==="acp"&&Nc(K.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:K.providerSessionId});return}await Ke()},v.current=Re,B(Re),M({title:K.kind==="ide"?xs("restart-ide",K.label):K.providerSessionId?zo(K.label):xs("start-fresh",K.label),description:K.kind==="ide"?bs("restart-ide"):K.providerSessionId?Vo():bs("start-fresh"),confirmLabel:K.kind==="ide"?Vs("restart-ide"):K.providerSessionId?Tn(!0):Vs("start-fresh"),busyLabel:K.kind==="ide"?Gs("restart-ide"):K.providerSessionId?Ho(!0):Gs("start-fresh"),workspaceOptions:Ie,details:[{label:"Mode",value:K.kind.toUpperCase()},...K.providerType?[{label:"Provider",value:K.providerType}]:[]]})},[D,_]);if(i.useEffect(()=>{p(be)},[he,be,s]),i.useEffect(()=>{fe&&N(fe)},[fe,s]),!_)return m?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:E,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 xe=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Mt,{size:14})," Workspace"]}),count:O.length+V.length+X.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(as,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Dn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Em,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rm,{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:E,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:[D.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:D.nicknameInput,onChange:K=>D.setNicknameInput(K.target.value),onKeyDown:K=>{K.key==="Enter"&&D.handleSaveNickname(),K.key==="Escape"&&D.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:D.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:()=>D.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:()=>{D.setEditingNickname(!0),D.setNicknameInput(_.machineNickname||"")},title:"Click to set nickname",children:ye}),k?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&s&&t.jsx("button",{onClick:()=>c.retryConnection(s),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):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:[_.platform," · ",_.arch]}),t.jsxs("span",{children:[_.cpus," cores"]}),(u==null?void 0:u.version)&&t.jsxs("span",{children:["v",u.version]}),_.p2p.available&&t.jsxs("span",{children:["P2P ",_.p2p.state==="connected"?"connected":_.p2p.state]}),_.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:_.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:xe.map(K=>t.jsxs("button",{onClick:()=>p(K.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${f===K.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[K.label,K.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===K.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:K.count})]},K.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[f==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(Bv,{machineEntry:u,providers:S,recentLaunches:P,currentConversations:me,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",_d(u))}catch{}},onOpenRecent:ae,onOpenConversation:q}),t.jsx(Wv,{machine:_,machineId:s,providers:S,ideSessions:O,cliSessions:V,acpSessions:X,actions:D,getIcon:W,initialCategory:I,initialWorkspaceId:Se,initialWorkspacePath:G,sendDaemonCommand:a,onOpenGitDialog:x})]}),f==="providers"&&t.jsx(q0,{machineId:s,providers:S,sendDaemonCommand:a}),f==="overview"&&t.jsx(O0,{machineId:s,machine:_,ideSessions:O,cliSessions:V,acpSessions:X,actions:D,sendDaemonCommand:a}),f==="session-host"&&t.jsx(Ev,{machineId:s,cliSessions:V,sendDaemonCommand:a}),f==="logs"&&t.jsx(Av,{machineId:s,sendDaemonCommand:a})]})})}),D.launchPick&&_&&t.jsx($v,{machine:_,launchPick:D.launchPick,actions:D}),A&&t.jsx(si,{title:A.title,description:A.description,details:A.details,workspaceOptions:A.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:K=>{v.current=K,B(K)},confirmLabel:A.confirmLabel,busyLabel:A.busyLabel,busy:R,onConfirm:de,onCancel:()=>{j.current=null,M(null)}}),b&&t.jsx(hu,{daemonId:b.daemonId,workspace:b.workspace,onClose:()=>y(null)}),t.jsx(nd,{toasts:c.toasts||[],onDismiss:K=>c.setToasts(Ie=>Ie.filter(Re=>Re.id!==K)),onClickToast:K=>{K.targetKey&&r(zt(K.targetKey))}}),t.jsx("style",{children:`
|
|
92
|
-
@keyframes toast-in {
|
|
93
|
-
from { opacity: 0; transform: translateX(40px); }
|
|
94
|
-
to { opacity: 1; transform: translateX(0); }
|
|
95
|
-
}
|
|
96
|
-
`})]})}const an=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],Uv={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function xn(e){var n;const s=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return s.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function zv(e){const s=xn(e);return s.length?{configured:!0,label:s.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function Vv(e,s){return s.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function Gv(e){const s=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${s}: ${r}`}function qv(e,s){return[...Array.isArray(s==null?void 0:s.cliSessions)?s.cliSessions:[],...Array.isArray(s==null?void 0:s.acpSessions)?s.acpSessions:[],...Array.isArray(s==null?void 0:s.sessions)?s.sessions:[]].filter(n=>{var a;return((a=n==null?void 0:n.settings)==null?void 0:a.meshNodeId)===e.id||(n==null?void 0:n.workspace)===e.workspace}).map(n=>{var a;return{id:n.sessionId||n.id||n.instanceId||"unknown",provider:n.providerType||n.cliType||n.acpType||n.type||"unknown",status:n.status||((a=n.activeChat)==null?void 0:a.status)||"unknown"}})}function za(e){return{...Uv,...(e==null?void 0:e.policy)||{}}}function Yv({meshId:e,availableCliAgents:s}){const r=s.find(a=>{const o=a.id.toLowerCase(),l=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||l.includes("hermes")}),n=Ed(r==null?void 0:r.meshCoordinator,{meshId:e});return n?t.jsx(jt,{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",children:t.jsx(iu,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function Xv(){var te;const{sendCommand:e}=wt(),{ides:s}=is(),r=ls(),n=s.find($=>$.daemonMode||$.type==="adhdev-daemon"),a=(n==null?void 0:n.id)||"",o=[];let l=[];if(n){const $=n.availableProviders||[];l=kx($);for(const J of $)J.category==="cli"&&o.push({id:J.type||J.id,name:J.displayName||J.name||J.type,meshCoordinator:J.meshCoordinator})}const[c,d]=i.useState([]),[m,u]=i.useState(null),[h,g]=i.useState(!0),[k,f]=i.useState(null),[p,b]=i.useState(!1),[y,x]=i.useState(null),[I,N]=i.useState({}),[j,A]=i.useState([]),[M,v]=i.useState(null),[w,B]=i.useState(null),[R,T]=i.useState(!1),[H,E]=i.useState(null),[D,S]=i.useState(null),[C,W]=i.useState(!1),[_,O]=i.useState(""),[V,X]=i.useState(""),[ye,he]=i.useState(!1),[ne,pe]=i.useState(""),[ke,Se]=i.useState([]),G=c.find($=>$.id===m)||null,be=i.useCallback($=>{$&&r(zt($),{state:{openRemoteForTabKey:$}})},[r]);i.useEffect(()=>{N(Object.fromEntries(((G==null?void 0:G.nodes)||[]).map($=>[$.id,xn($)])))},[G]),i.useEffect(()=>{const $=Nx(l);ye&&ke.length===0&&$.length>0&&Se($)},[ye,l,ke.length]),i.useEffect(()=>{const $=new Set(((G==null?void 0:G.nodes)||[]).map(J=>J.id));M&&!$.has(M)&&v(null)},[G,M]);const fe=i.useCallback(async()=>{if(a){g(!0);try{const $=await e(a,"list_meshes");$!=null&&$.success?(d($.meshes||[]),f(null)):f(($==null?void 0:$.error)||"Failed to load meshes")}catch($){f(($==null?void 0:$.message)||"Failed to load meshes")}finally{g(!1)}}},[a,e]),ve=i.useCallback(async $=>{if(!a||!$){A([]);return}try{const J=await e(a,"get_mesh_queue",{meshId:$});J!=null&&J.success?A(Array.isArray(J.queue)?J.queue:[]):A([])}catch{A([])}},[a,e]);i.useEffect(()=>{fe()},[fe]),i.useEffect(()=>{ve(m)},[ve,m]);async function P(){if(!(!a||!m))try{T(!0),E(null);const $=await e(a,"mesh_status",{meshId:m});if($!=null&&$.success){const J=$.status||$.result||$;if(J&&typeof J=="object"){const oe=cu(J);B(oe)}else E("Invalid mesh_status response format")}else E(($==null?void 0:$.error)||"mesh_status failed")}catch($){E(($==null?void 0:$.message)||"Failed to load mesh graph")}finally{T(!1)}}i.useEffect(()=>{m&&(B(null),E(null),S(null),P())},[m]);async function me(){var $;if(!(!a||!_.trim()))try{const J=await e(a,"create_mesh",{name:_.trim(),repoIdentity:V.trim()||void 0});J!=null&&J.success?(W(!1),O(""),X(""),await fe(),u((($=J.mesh)==null?void 0:$.id)||null)):f((J==null?void 0:J.error)||"Create failed")}catch(J){f((J==null?void 0:J.message)||"Create failed")}}async function q($){if(!(!a||!confirm("Delete this mesh?")))try{await e(a,"delete_mesh",{meshId:$}),u(null),await fe()}catch(J){f((J==null?void 0:J.message)||"Delete failed")}}async function de(){if(!(!a||!m||!ne.trim()))try{const $=await e(a,"add_mesh_node",{meshId:m,workspace:ne.trim(),providerPriority:io(ke,l)});$!=null&&$.success?(he(!1),pe(""),Se([]),await fe(),await ve(m)):f(($==null?void 0:$.error)||"Add node failed")}catch($){f(($==null?void 0:$.message)||"Add node failed")}}async function ae($){var ee;if(!a||!m)return;const J=za(G),oe=((ee=an.find(Ne=>Ne.value===J.sessionCleanupOnNodeRemove))==null?void 0:ee.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
|
|
97
|
-
|
|
98
|
-
Node removal cleanup policy: ${oe}`))try{await e(a,"remove_mesh_node",{meshId:m,nodeId:$}),M===$&&v(null),await fe(),await ve(m)}catch(Ne){f((Ne==null?void 0:Ne.message)||"Remove node failed")}}async function xe($){if(!a||!m)return;const J={...za(G),...$};try{b(!0),f(null);const oe=await e(a,"update_mesh",{meshId:m,policy:J});if((oe==null?void 0:oe.success)===!1){f(oe.error||"Policy update failed");return}await fe()}catch(oe){f((oe==null?void 0:oe.message)||"Policy update failed")}finally{b(!1)}}async function ue($){if(!a||!m)return;const J=io(I[$.id]||xn($),l),oe={...$.policy||{}};delete oe.provider_priority,J.length?oe.providerPriority=J:delete oe.providerPriority;try{x($.id),f(null);const ee=await e(a,"update_mesh_node",{meshId:m,nodeId:$.id,policy:oe});if((ee==null?void 0:ee.success)===!1){f(ee.error||"Node policy update failed");return}await fe()}catch(ee){f((ee==null?void 0:ee.message)||"Node policy update failed")}finally{x(null)}}if(!a)return t.jsx(gr,{icon:t.jsx(rs,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:t.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!G)return t.jsxs(gr,{icon:t.jsx(rs,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>W(!0),children:"+ Create Mesh"}),children:[k&&t.jsx(Es,{variant:"error",className:"mb-4",children:k}),C&&t.jsx(jt,{title:"New Mesh",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Lt,{label:"Name",children:t.jsx(ua,{value:_,onChange:$=>O($.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),t.jsx(Lt,{label:"Repo Identity (optional)",children:t.jsx(ua,{value:V,onChange:$=>X($.target.value),placeholder:"github.com/user/repo"})}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:me,disabled:!_.trim(),children:"Create"}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>W(!1),children:"Cancel"})]})]})}),h?t.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):c.length===0?t.jsx(An,{icon:t.jsx(rs,{}),title:"No meshes",description:"Create a mesh to get started."}):t.jsx("div",{className:"flex flex-col gap-2",children:c.map($=>t.jsxs("button",{className:"text-left w-full p-4 rounded-xl border border-border-subtle bg-bg-panel hover:border-accent-primary/40 transition-colors",onClick:()=>u($.id),children:[t.jsx("div",{className:"font-semibold text-sm",children:$.name}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:$.repoIdentity||"No repo identity"}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[$.nodes.length," node(s)"]})]},$.id))})]});const ce=za(G);return t.jsxs(gr,{icon:t.jsx(rs,{}),title:G.name,subtitle:G.repoIdentity||"Repo Mesh",actions:t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>u(null),children:"← Back"}),t.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>q(G.id),children:"Delete"})]}),children:[k&&t.jsx(Es,{variant:"error",className:"mb-4",children:k}),t.jsxs(jt,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[t.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[t.jsx(Lt,{label:"Checkpoint before task",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.requirePreTaskCheckpoint?"yes":"no",onChange:$=>xe({requirePreTaskCheckpoint:$.target.value==="yes"}),disabled:p,children:[t.jsx("option",{value:"no",children:"No"}),t.jsx("option",{value:"yes",children:"Yes"})]})}),t.jsx(Lt,{label:"Checkpoint after task",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.requirePostTaskCheckpoint?"yes":"no",onChange:$=>xe({requirePostTaskCheckpoint:$.target.value==="yes"}),disabled:p,children:[t.jsx("option",{value:"yes",children:"Yes"}),t.jsx("option",{value:"no",children:"No"})]})}),t.jsx(Lt,{label:"Push approval",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.requireApprovalForPush?"required":"not_required",onChange:$=>xe({requireApprovalForPush:$.target.value==="required"}),disabled:p,children:[t.jsx("option",{value:"required",children:"Require approval before push"}),t.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),t.jsx(Lt,{label:"Destructive git approval",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.requireApprovalForDestructiveGit?"required":"not_required",onChange:$=>xe({requireApprovalForDestructiveGit:$.target.value==="required"}),disabled:p,children:[t.jsx("option",{value:"required",children:"Require approval"}),t.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),t.jsx(Lt,{label:"Dirty workspace behavior",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.dirtyWorkspaceBehavior||"warn",onChange:$=>xe({dirtyWorkspaceBehavior:$.target.value}),disabled:p,children:[t.jsx("option",{value:"warn",children:"Warn and continue"}),t.jsx("option",{value:"block",children:"Block task"}),t.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),t.jsx(Lt,{label:"Max parallel tasks",children:t.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:String(ce.maxParallelTasks??2),onChange:$=>xe({maxParallelTasks:Number($.target.value)}),disabled:p,children:[1,2,3,4,5,6,7,8].map($=>t.jsx("option",{value:$,children:$},$))})})]}),t.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[t.jsx(Lt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:t.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ce.sessionCleanupOnNodeRemove||"preserve",onChange:$=>xe({sessionCleanupOnNodeRemove:$.target.value}),disabled:p,children:an.map($=>t.jsx("option",{value:$.value,children:$.label},$.value))})}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((te=an.find($=>$.value===ce.sessionCleanupOnNodeRemove))==null?void 0:te.description)||an[0].description})]}),p&&t.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),t.jsxs(jt,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:P,disabled:R,children:R?"Loading...":"Refresh Graph"})]}),H&&t.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:H}),w?t.jsxs("div",{className:"flex gap-4",style:{minHeight:420},children:[t.jsx("div",{className:"flex-1 rounded-xl border border-border-subtle bg-bg-secondary overflow-hidden",style:{minHeight:420},children:t.jsx(mu,{data:w,onNodeClick:$=>S(J=>(J==null?void 0:J.id)===$.id?null:$),selectedNodeId:(D==null?void 0:D.id)||null})}),D&&t.jsxs("div",{className:"w-80 shrink-0 flex flex-col gap-3",children:[t.jsx(pu,{node:D,onClose:()=>S(null)}),D.type!=="submoduleNode"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/70 p-3 text-[12px] text-text-muted",children:[t.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wide text-text-secondary",children:"Active sessions"}),D.activeSessions.length===0?t.jsx("div",{children:"No active session ids on this node."}):t.jsx("div",{className:"flex flex-col gap-2",children:D.activeSessions.map($=>t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary/60 px-3 py-2",children:[t.jsx("div",{className:"font-mono text-[11px] text-text-primary break-all",children:$}),t.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:t.jsx("button",{type:"button",className:"text-[11px] text-accent hover:underline",onClick:()=>be($),children:"Open chat"})})]},$))})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/70 p-3 text-[12px] text-text-muted",children:[t.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wide text-text-secondary",children:"Related active queue"}),j.filter($=>($.status==="pending"||$.status==="assigned")&&($.assignedNodeId===D.id||$.targetNodeId===D.id)).length===0?t.jsx("div",{children:"No pending/assigned queue items targeting this node."}):t.jsx("div",{className:"flex flex-col gap-2",children:j.filter($=>($.status==="pending"||$.status==="assigned")&&($.assignedNodeId===D.id||$.targetNodeId===D.id)).map($=>{const J=$.assignedSessionId||$.targetSessionId||$.sessionId||null;return t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary/60 px-3 py-2",children:[t.jsx("div",{className:"text-text-primary text-[11px] break-words",children:$.message}),t.jsxs("div",{className:"mt-1 font-mono text-[10px] text-text-muted",children:[$.id," · ",$.status]}),J&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:t.jsx("button",{type:"button",className:"text-[11px] text-accent hover:underline",onClick:()=>be(J),children:"Open chat"})})]},$.id)})})]})]})]})]}):t.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:R?"Loading graph...":"Refresh the graph to view mesh topology."})]}),t.jsxs(jt,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[t.jsx("div",{className:"flex justify-end mb-3",children:t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>he(!0),children:"+ Add Node"})}),ye&&t.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[t.jsxs("div",{className:"flex justify-between items-center mb-3",children:[t.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),t.jsx("button",{onClick:()=>he(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:t.jsx(vt,{size:16})})]}),t.jsx(Lt,{label:"Workspace Path",children:t.jsx(ua,{value:ne,onChange:$=>pe($.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),t.jsx(Lt,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:t.jsx(Zi,{value:ke,availableProviders:l,onChange:Se})}),t.jsxs("div",{className:"flex gap-2 mt-3",children:[t.jsx("button",{onClick:de,disabled:!ne.trim(),className:"btn btn-primary btn-sm",children:"Add"}),t.jsx("button",{onClick:()=>he(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),G.nodes.length===0?t.jsx(An,{icon:t.jsx(ks,{}),title:"No nodes",description:"Add a workspace to this mesh."}):t.jsx("div",{className:"flex flex-col gap-2",children:G.nodes.map($=>{const J=xn($),oe=zv($),ee=Vv($,j),Ne=qv($,n),Ce=M===$.id;return t.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${Ce?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>v(Ce?null:$.id),onKeyDown:we=>{(we.key==="Enter"||we.key===" ")&&(we.preventDefault(),v(Ce?null:$.id))},children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"text-sm font-medium",children:$.workspace.split("/").pop()}),ee.length>0&&t.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[ee.length," active task",ee.length===1?"":"s"]})]}),t.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:$.workspace}),t.jsx("div",{className:"mt-3 max-w-2xl",onClick:we=>we.stopPropagation(),children:t.jsxs(Lt,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[t.jsx(Zi,{value:I[$.id]??J,availableProviders:l,onChange:we=>N(K=>({...K,[$.id]:we})),disabled:y===$.id,saveButton:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:we=>{we.stopPropagation(),ue($)},disabled:y===$.id,children:y===$.id?"Saving...":"Save policy"})}),t.jsxs("div",{className:"mt-2 text-[12px]",children:[t.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),t.jsx("span",{className:oe.configured?"text-text-primary font-mono":"text-amber-400",children:oe.label}),oe.launchBlockedMessage&&t.jsxs("span",{className:"ml-2 text-amber-400",children:["(",oe.launchBlockedMessage,")"]})]})]})})]}),t.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:we=>{we.stopPropagation(),ae($.id)},children:t.jsx(vt,{size:14})})]}),Ce&&t.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[t.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",t.jsx("span",{className:"font-mono",children:$.id})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",t.jsx("span",{className:oe.configured?"text-green-400":"text-amber-400",children:oe.configured?"yes":"provider priority not configured"})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",t.jsx("span",{className:"font-mono",children:$.repoRoot||$.workspace})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",Ne.length]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",ee.length>0||Ne.length>0?"active":"idle/unknown"]})]}),t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),ee.length===0?t.jsx("div",{children:"No active assigned queue task for this node."}):t.jsx("ul",{className:"m-0 pl-4",children:ee.map(we=>t.jsx("li",{className:"font-mono",children:Gv(we)},we.id))})]}),Ne.length>0&&t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),t.jsx("ul",{className:"m-0 pl-4",children:Ne.map(we=>t.jsxs("li",{className:"font-mono",children:[we.provider," / ",we.status," / ",we.id]},we.id))})]})]})]},$.id)})})]}),t.jsx(Yv,{meshId:G.id,availableCliAgents:o})]})}function ci(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Jv(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=ci();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 Kt(e,s){return await fetch(Jv(e),{credentials:"same-origin",...s})}function gu(){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 Qv{constructor(){Je(this,"adapters",new Map);Je(this,"states",new Map);Je(this,"runtimeListeners",new Map);Je(this,"screenshotCallbacks",new Map);Je(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,o,l){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a,cols:o,rows:l})}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,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const o=await Kt(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const l=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof l.seq=="number"?l.seq:0,text:typeof l.text=="string"?l.text:"",truncated:!!l.truncated,cols:typeof l.cols=="number"?l.cols:void 0,rows:typeof l.rows=="number"?l.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Gt=new Qv;function Zv(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=ci();return r?`${s}?token=${encodeURIComponent(r)}`:s}const on=Zv(),ql=3e3,ew=3e4;let Et=null,tw=0;const Pn=new Map;let us=null,jr=null;function Yl(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function dr(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function sw(e){return e==="connected"?"connected":e}async function bn(e,s,r){const n=ld(e,r||{}),a=Et;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++tw}_${Date.now()}`;return new Promise((l,c)=>{const d=setTimeout(()=>{Pn.delete(o),c(new Error(`WS command timeout: ${s}`))},3e4);Pn.set(o,{resolve:m=>{clearTimeout(d),l(m)},reject:m=>{clearTimeout(d),c(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function go(e,s){const r=Et;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}}function rw(e,s,r){const n=Et;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=ld(e,{sessionId:s,targetSessionId:s,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class nw{constructor(s){Je(this,"daemonId");Je(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Et==null?void 0:Et.readyState)===WebSocket.OPEN}get connectionState(){return(Et==null?void 0:Et.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return bn(this.daemonId,s,r)}async sendInput(s,r){return bn(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,us&&(clearInterval(us),us=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await bn(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(o=>o.blob());Gt.emitScreenshot(this.daemonId,a)}}catch{}};r(),us=setInterval(r,2e3)}stopScreenshots(s){us&&(clearInterval(us),us=null)}}let _t=null;function aw(e){return(!_t||_t.daemonId!==e)&&(_t=new nw(e)),_t}function ow({children:e}){const s=i.useRef(Nr()),r=Nr();s.current=r;const{setUserName:n}=is(),a=i.useRef(n);a.current=n;const o=i.useRef(null),l=i.useRef(null),[,c]=i.useState("disconnected"),d=i.useCallback((p,b)=>{c(p),jr==null||jr(p,b)},[]),m=i.useRef(null),u=i.useRef(),h=i.useRef(ql),g=i.useRef(!0),k=i.useRef(!1),f=i.useRef("initial_connect");return i.useEffect(()=>{g.current=!0,k.current=!1;function p(){var x,I;if(!g.current||((x=m.current)==null?void 0:x.readyState)===WebSocket.OPEN||((I=m.current)==null?void 0:I.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${on}...`),dr("connect_attempt",{url:on,reason:f.current,delayMs:h.current});let y;try{y=new WebSocket(on)}catch(N){console.error("[Standalone WS] Failed to create WebSocket:",N),b();return}m.current=y,y.onopen=()=>{if(!g.current){y.close();return}d("connected"),h.current=ql,dr("open",{url:on,reason:f.current}),Xt.resubscribeAll({sendData:go}),console.log("[Standalone WS] Connected")},Et=y,y.onmessage=N=>{var j,A;try{const M=JSON.parse(N.data);if((M.type==="command_result"||M.type==="error")&&M.requestId){const v=Pn.get(M.requestId);v&&(Pn.delete(M.requestId),M.type==="error"?v.reject(new Error(((j=M.data)==null?void 0:j.message)||"Command failed")):v.resolve(M.data));return}if(M.type==="session_output"){const v=M.sessionId||M.cliId||M.cliType;v&&Gt.emitSessionOutput(v,typeof M.data=="string"?M.data:"",typeof M.seq=="number"?M.seq:void 0);return}if(M.type==="runtime_snapshot"){Gt.emitRuntimeSnapshot(M.sessionId,typeof M.text=="string"?M.text:"",typeof M.seq=="number"?M.seq:0,!!M.truncated,typeof M.cols=="number"?M.cols:void 0,typeof M.rows=="number"?M.rows:void 0);return}if(M.type==="topic_update"){const v=M.update;v&&Xt.publish(v);return}if(M.type==="status"||M.type==="initial_state"){const v=M.data;if(!v)return;const{injectEntries:w,markLoaded:B,getIdes:R}=s.current,T=v.instanceId||"standalone",H=R().find(S=>S.id===T),E=aw(T);Gt.register(T,E),Gt.setState(T,"connected"),d("connected",T),Gt.emitStatus(T,v);const D=In(v,{daemonId:T,existingDaemon:H,existingEntries:R()});Yl("ws_status",{type:M.type,daemonId:T,sessions:(v.sessions||[]).map(S=>({id:S.id,parentId:S.parentId,providerType:S.providerType,kind:S.kind,transport:S.transport,unread:S.unread,inboxBucket:S.inboxBucket,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,title:S.title})),recentLaunches:(v.recentLaunches||[]).map(S=>({id:S.id,providerType:S.providerType,kind:S.kind,workspace:S.workspace,lastLaunchedAt:S.lastLaunchedAt}))}),Yl("entries",{daemonId:T,entries:D.filter(S=>S.type!=="adhdev-daemon").map(S=>({id:S.id,type:S.type,unread:S.unread,inboxBucket:S.inboxBucket,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,sessionId:S.sessionId}))}),D.length>0&&w(D,{authoritativeDaemonIds:[T]}),B(),l.current!==T&&((A=o.current)==null||A.call(o),l.current=T,o.current=Xt.subscribe({sendData:go},T,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${T}`,params:{includeSessions:!0}},S=>{if(S.topic!=="daemon.metadata")return;const C=s.current.getIdes(),W=C.find(O=>O.id===T),_=In(S.status,{daemonId:T,existingDaemon:W,existingEntries:C,timestamp:S.timestamp});_.length>0&&s.current.injectEntries(_,{authoritativeDaemonIds:[T]}),S.userName&&a.current&&a.current(S.userName)}))}}catch(M){console.error("[Standalone WS] Parse error:",M)}},y.onclose=N=>{g.current&&(_t==null||_t.stopScreenshots(),_t&&Gt.setState(_t.daemonId,"disconnected"),d("disconnected"),m.current=null,f.current=`close:${N.code}${N.wasClean?":clean":":unclean"}`,dr("close",{code:N.code,reason:N.reason||"",wasClean:N.wasClean}),b())},y.onerror=N=>{k.current||!g.current||(f.current="error",dr("error",{message:N instanceof Event?"event":String(N),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",N))}}function b(){if(!g.current)return;clearTimeout(u.current);const y=h.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),dr("schedule_reconnect",{reason:f.current,delayMs:y}),u.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,ew),p()},y)}return p(),()=>{var y;g.current=!1,k.current=!0,(y=o.current)==null||y.call(o),o.current=null,l.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Et=null),_t&&(_t.stopScreenshots(),Gt.unregister(_t.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function iw({children:e}){const[s,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(jr=(l,c)=>{r(l),c&&a(c)},()=>{jr=null}),[]);const o=i.useMemo(()=>{const l=s==="connected",c=sw(s),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:s,isConnected:l,connectionStates:d}},[s,n]);return t.jsx(wm,{connectionOverrides:o,children:t.jsx(ow,{children:e})})}const yu="adhdev_standalone_font_preferences",js={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Xn=[{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"}],Ir=[{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"}],lw=new Set(Xn.map(e=>e.id)),cw=new Set(Ir.map(e=>e.id));function Ht(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:gn("chat",s.chat),code:gn("code",s.code),terminal:gn("terminal",s.terminal)}}function gn(e,s){const r=js[e],n=s&&typeof s=="object"&&!Array.isArray(s)?s:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?lw:cw).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function yn(e,s){var a;const r=gn(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Xn:Ir;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function dw(e){const s=Ht(e),r=yn("chat",s.chat),n=yn("code",s.code),a=yn("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ps(e,s=document.documentElement){const r=Ht(e),n=dw(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))s.style.setProperty(a,o);return r}function yo(e){const s=Ht(e);try{localStorage.setItem(yu,JSON.stringify(s))}catch{}return s}function uw(){try{const e=localStorage.getItem(yu);if(e)return Ht(JSON.parse(e))}catch{}return js}function mw(){return ps(uw())}function ur(e,s){var n;const r=e==="chat"?Xn:Ir;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const pw=[{id:"dashboard",path:"/dashboard",icon:t.jsx(ac,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(as,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:t.jsx(Ws,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:t.jsx(Dn,{}),label:"Settings"}];function fw({children:e}){const s=ls(),r=wo(),n=i.useMemo(()=>pw.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>s(o.path)})),[r.pathname,s]),a=i.useMemo(()=>[{id:"docs",label:t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Docs"}),t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:t.jsx(ic,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:t.jsx(lc,{}),active:r.pathname==="/about",onSelect:()=>s("/about"),title:"About"}],[r.pathname,s]);return t.jsx(Dx,{brand:({collapsed:o})=>t.jsxs(t.Fragment,{children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&t.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.81"]}),footerActions:({collapsed:o,toggleCollapsed:l})=>t.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:l,title:o?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&t.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const hw=[{icon:t.jsx(as,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Jt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(cc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(Mt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Ws,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(ic,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],xw=[{icon:t.jsx(Bm,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(ac,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(En,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Lm,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(oc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(_m,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],bw=[{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 gw(){return t.jsxs(gr,{icon:t.jsx(lc,{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.9.81"]}),children:[t.jsx(jt,{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(jt,{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:hw.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(jt,{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:cd.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:ud.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:dd.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(jt,{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:xw.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(jt,{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:bw.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(An,{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(qm,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Va(e,s,r){return{...e,[s]:r}}function Ga({surface:e,title:s,description:r,value:n,options:a,onChange:o}){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:l=>{const c=l.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(l=>t.jsx("option",{value:l.id,children:l.label},l.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:l=>o({preset:"custom",customFamily:l.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:yn(e,n)})]})]})]})}function yw({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:o,onSave:l,onResetToSaved:c,onResetToDefaults:d}){const m=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(Ga,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Xn,onChange:u=>o(Va(e,"chat",u))}),t.jsx(Ga,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Ir,onChange:u=>o(Va(e,"code",u))}),t.jsx(Ga,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Ir,onChange:u=>o(Va(e,"terminal",u))})]}),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: ",ur("chat",e.chat.preset)," · Code: ",ur("code",e.code.preset)," · Terminal: ",ur("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",ur("chat",js.chat.preset)," / ",ur("code",js.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:l,disabled:r||!m,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:c,disabled:r||!m,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:d,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 vw(){const{ides:e}=is(),s=e.find(G=>G.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=wt(),{userName:a}=is(),[o,l]=i.useState(a||""),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,g]=i.useState(js),[k,f]=i.useState(!1),[p,b]=i.useState(""),[y,x]=i.useState(""),[I,N]=i.useState("127.0.0.1"),[j,A]=i.useState(""),[M,v]=i.useState(""),[w,B]=i.useState(""),[R,T]=i.useState(""),[H,E]=i.useState(""),[D,S]=i.useState(!1),C=async()=>{const be=await(await Kt("/auth/session")).json();d(be)},W=async()=>{const be=await(await Kt("/api/v1/standalone/preferences")).json();u(be),N(be.standaloneBindHost);const fe=Ht(be.standaloneFontPreferences);g(fe),ps(fe),yo(fe)};i.useEffect(()=>{a!==void 0&&l(a)},[a]),i.useEffect(()=>{Promise.all([C(),W()]).catch(G=>{T(G instanceof Error?G.message:String(G))})},[]),i.useEffect(()=>{ps(h)},[h]);const _=G=>{const be=G.target.value.trim();s!=null&&s.id&&be!==a&&n(s.id,"set_user_name",{userName:be}).catch(console.error)},[O,V]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),X=G=>{V(G);try{localStorage.setItem("adhdev_sound",G?"1":"0")}catch{}},ye=async()=>{b(""),x(""),f(!0);try{const G=Ht(h),be=await Kt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:G})}),fe=await be.json();if(!be.ok)throw new Error((fe==null?void 0:fe.error)||"Failed to save standalone font preferences");const ve=Ht(fe.standaloneFontPreferences);u(fe),g(ve),ps(ve),yo(ve),x("Standalone chat fonts saved for this self-hosted dashboard.")}catch(G){b(G instanceof Error?G.message:String(G))}finally{f(!1)}},he=()=>{const G=Ht(m==null?void 0:m.standaloneFontPreferences);b(""),x(""),g(G),ps(G)},ne=()=>{b(""),x(""),g(js),ps(js)},pe=async()=>{T(""),E(""),S(!0);try{const G=await Kt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:I})}),be=await G.json();if(!G.ok)throw new Error((be==null?void 0:be.error)||"Failed to save standalone network preference");u(be),N(be.standaloneBindHost),E(be.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(G){T(G instanceof Error?G.message:String(G))}finally{S(!1)}},ke=async()=>{if(T(""),E(""),M.trim().length<4){T("Password must be at least 4 characters.");return}if(M!==w){T("New password and confirmation do not match.");return}S(!0);try{const G=await Kt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,newPassword:M})}),be=await G.json();if(!G.ok)throw new Error((be==null?void 0:be.error)||"Failed to save password");d(be),await W(),A(""),v(""),B(""),E(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),gu()}catch(G){T(G instanceof Error?G.message:String(G))}finally{S(!1)}},Se=async()=>{T(""),E(""),S(!0);try{const G=await Kt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:j,clear:!0})}),be=await G.json();if(!G.ok)throw new Error((be==null?void 0:be.error)||"Failed to clear password");d(be),await W(),A(""),v(""),B(""),E("Standalone password disabled.")}catch(G){T(G instanceof Error?G.message:String(G))}finally{S(!1)}};return t.jsxs(gr,{icon:t.jsx(Dn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx(Es,{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."}),(c==null?void 0:c.publicHostWarning)&&t.jsx(Es,{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(jt,{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.9.81"]}),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:(m==null?void 0:m.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:c!=null&&c.hasPasswordAuth?"Password enabled":c!=null&&c.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(jt,{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:I==="127.0.0.1",onChange:()=>N("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:I==="0.0.0.0",onChange:()=>N("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:()=>{pe()},disabled:D,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:D?"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 ",(m==null?void 0:m.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(jt,{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:c!=null&&c.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."}),R&&t.jsx(Es,{variant:"error",children:R}),H&&t.jsx(Es,{variant:"success",children:H}),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:c!=null&&c.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:j,onChange:G=>A(G.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:c!=null&&c.hasPasswordAuth?"New password":"New standalone password",value:M,onChange:G=>v(G.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:w,onChange:G=>B(G.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{ke()},disabled:D,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:D?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{Se()},disabled:D,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(jt,{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(G=>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 ${G.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:G.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:G.type})]},G.type))})}),t.jsx(jt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Ux,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(jt,{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(qx,{})]}),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(sb,{})]}),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(yw,{value:h,savedValue:Ht(m==null?void 0:m.standaloneFontPreferences),saving:k,error:p,notice:y,onChange:g,onSave:()=>{ye()},onResetToSaved:he,onResetToDefaults:ne})]}),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(ab,{})]})]})}),t.jsx(jt,{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(Kx,{}),t.jsx(ms,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Gm,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:O,onChange:X})]})}),t.jsx(jt,{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(Mm,{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:o,onChange:G=>l(G.target.value),onBlur:_,onKeyDown:G=>{G.key==="Enter"&&G.currentTarget.blur()}})]})})})]})}_x();eb();mw();const ww=rc({baseUrl:"",getToken:ci});function jw({children:e}){const[s,r]=i.useState(null),[n,a]=i.useState(!0),[o,l]=i.useState(""),[c,d]=i.useState(""),[m,u]=i.useState(!1),h=async()=>{a(!0),d("");try{const f=await(await Kt("/auth/session")).json();r(f)}catch(k){d(k instanceof Error?k.message:String(k))}finally{a(!1)}};i.useEffect(()=>{h()},[]),i.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let k=!1;return(async()=>{try{const f=await Kt("/api/v1/standalone/preferences");if(!f.ok)return;const p=await f.json();if(k)return;const b=Ht(p.standaloneFontPreferences);ps(b),yo(b)}catch{}})(),()=>{k=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const g=async k=>{k.preventDefault(),u(!0),d("");try{const f=await Kt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await f.json();if(!f.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),l(""),gu()}catch(f){d(f instanceof Error?f.message:String(f))}finally{u(!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:o,onChange:k=>l(k.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:m||!o,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"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."}),c&&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:c})]})}):t.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",c||"unknown error"]})}function Xl(){const{ides:e,initialLoaded:s}=is();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(Xa,{to:`/machines/${r.id}`,replace:!0}):t.jsx(Xa,{to:"/dashboard",replace:!0})}function kw(){const e=i.useMemo(()=>({sendCommand:bn,sendData:go,sendPtyInput:rw}),[]);return t.jsx(am,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(Nm,{client:ww,children:t.jsx(jw,{children:t.jsx(iw,{children:t.jsx(Cm,{value:e,children:t.jsx(fw,{children:t.jsxs(om,{children:[t.jsx(es,{path:"/dashboard",element:t.jsx($0,{})}),t.jsx(es,{path:"/machine",element:t.jsx(Xl,{})}),t.jsx(es,{path:"/machines/:id",element:t.jsx(Hv,{})}),t.jsx(es,{path:"/machines",element:t.jsx(Xl,{})}),t.jsx(es,{path:"/about",element:t.jsx(gw,{})}),t.jsx(es,{path:"/settings",element:t.jsx(vw,{})}),t.jsx(es,{path:"/mesh",element:t.jsx(Xv,{})}),t.jsx(es,{path:"*",element:t.jsx(Xa,{to:"/dashboard",replace:!0})})]})})})})})})})}Hh({connectionManager:Gt});im(document.getElementById("root")).render(t.jsx(kw,{}));
|