@adhdev/daemon-standalone 0.9.82-rc.9 → 0.9.82-rc.90
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 +25362 -21190
- 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
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-D46M5EWH.js","assets/vendor-CgiI0UIA.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Zu=Object.defineProperty;var em=(e,t,r)=>t in e?Zu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Qe=(e,t,r)=>em(e,typeof t!="symbol"?t+"":t,r);import{r as i,j as s,M as wo,a as tm,b as sm,c as rm,R as St,d as Nr,t as nm,e as am,u as Ys,D as om,f as Ya,g as Xa,i as im,C as lm,h as cm,B as dm,k as um,l as mm,H as Si,P as Ni,m as pm,n as hm,o as jo,p as fm,q as xm,s as bm,v as gm,w as ss,N as Ja,x as ym}from"./vendor-CgiI0UIA.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.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 vm(e={}){const t=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>t&&r.splice(0,r.length-t),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=vm();function Ci(e){const t={};for(const r of e)r.transport&&(t[r.transport]=(t[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:t}}function wm(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Ii(e){return Array.isArray(e)?[...e]:[]}function Zl(e,t){if(!e)return t??null;const r=Object.prototype.hasOwnProperty.call(e,"messages"),n=Object.prototype.hasOwnProperty.call(e,"activeModal");return t?{...t,...e,messages:r?Ii(e.messages):t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:Ii(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function fr(e,t){const r=wm(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:r??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??r??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:Zl(e.activeChat,t==null?void 0:t.activeChat),controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel),settings:e.settings??(t==null?void 0:t.settings)}}function ec(e,t,r){if(!(t!=null&&t.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const n=t.map(a=>{const o=e.find(l=>l.id===a.id);return o?fr(a,o):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(t.map(o=>o.id));for(const o of e)a.has(o.id)||n.push(o)}return n}function Mi(e){return!!e&&typeof e=="object"&&"text"in e}function ko(e,t){const r=(t==null?void 0:t.joiner)??" ",n=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(o=>typeof o=="string"?o:Mi(o)?String(o.text||""):"").join(r):Mi(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Ws(e){return ko(e,{normalizeWhitespace:!0})}const tc=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}),sc=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Ai(e){var r,n;let t=0;return e.activeChat!==void 0&&(t+=4),(r=e.childSessions)!=null&&r.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(n=e.agents)!=null&&n.length&&(t+=1),t}function rc(e,t,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=t.version??r.version??e.version,o=t.serverVersion??e.serverVersion??r.serverVersion,l=t.versionMismatch===!0||e.versionMismatch===!0,c=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.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):((t.versionMismatch===!0||l&&a&&o&&a!==o)&&(n.versionMismatch=!0),c&&(n.versionUpdateRequired=!0),n)}function jm(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function ra(e){if(!e||typeof e!="object")return"";const t=e,r=jm(Ws(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),r].join(":")}function km(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=ra(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:ra(e[0]),last:ra(e[e.length-1])}}function Qa(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Za(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Qa(e)&&Qa(t)){const l=e.messages;Array.isArray(l)&&l===t.messages&&r.add(l)}if(Array.isArray(e)&&Array.isArray(t)){const l=Math.min(e.length,t.length);for(let c=0;c<l;c+=1)Za(e[c],t[c],r);return}const n=e,a=t,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const l of o)l!=="messages"&&Za(n[l],a[l],r)}function gr(e,t){return Array.isArray(e)?e.map(r=>gr(r,t)):!e||typeof e!="object"?e:Qa(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?km(a,t):gr(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,gr(n,t)]))}function Sm(e,t){try{const r=new WeakSet;return Za(e,t,r),JSON.stringify(gr(e,r))===JSON.stringify(gr(t,r))}catch{return!1}}function eo(e,t,r){return Sm(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function nc(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Nm(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function Ti(e,t,r,n){var c;const a=(c=t.chats)!=null&&c.length?t.chats:e.chats,o=ec(e.childSessions,t.childSessions,{preserveMissing:n}),l=Zl(t.activeChat,e.activeChat);return rc(e,t,{...e,...t,chats:a,childSessions:o,activeChat:l,_lastUpdate:r})}function Cm(e,t,r){var a,o;const n={};t.status&&t.status!==e.status&&(n.status=t.status),t.cdpConnected!==void 0&&(n.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(n.childSessions=ec(e.childSessions,t.childSessions,{preserveMissing:r})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=t.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"])Nm(n,t,l);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function Im(e,t,r,n){const a=Cm(e,t,n),o=Object.keys(a).length>0?rc(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return eo(e,o,r)}function Mm(e){const t=new Set(e.map(o=>o.id)),r=new Set,n=new Set,a=new Set;for(const o of e){const l=nc(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:t,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function Am(e,t,r,n,a,o){return!a.has(t)||!o.has(t)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function Tm(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function _m(e,t,r){var u,p;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(b=>({...b,_lastUpdate:n}));const o=new Map;for(const b of t)o.set(b.id,b);const{incomingIds:l,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=Mm(e);for(const b of e){const w=o.get(b.id);if(!w){o.set(b.id,{...b,_lastUpdate:n});continue}const x=Ai(b),h=Ai(w),g=nc(b),y=!a.has(g);if(x>h){const C=Ti(w,b,n,y);o.set(b.id,eo(w,C,n));continue}if(x<h){o.set(b.id,Im(w,b,n,y));continue}const f=b.timestamp||n,A=w._lastUpdate||w.timestamp||0;if(f>=A){const C=Ti(w,b,n,y);o.set(b.id,eo(w,C,n));continue}(u=b.chats)!=null&&u.length&&!((p=w.chats)!=null&&p.length)&&o.set(b.id,{...w,chats:b.chats})}for(const[b,w]of o){const x=w.daemonId||b.split(":")[0];if(!c.has(x))continue;if(a.has(x)&&m.has(x)&&!l.has(b)){o.delete(b);continue}const h=n-(w._lastUpdate||w.timestamp||0);Am(w,x,h,l,a,d)&&o.delete(b)}for(const[b,w]of o){const x=w.daemonId||b.split(":")[0];if(Tm(w,x,c,d,o))continue;n-(w._lastUpdate||w.timestamp||0)>3e5&&w.status!=="online"&&o.delete(b)}return Array.from(o.values())}function Lm(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Rm({children:e,connectionOverrides:t}){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 p=i.useCallback((y,f)=>{n(A=>{let C=!1;const v=A.map(N=>N.id!==y||N.chats===f?N:(C=!0,{...N,chats:f}));return C?v:A})},[]),b=i.useCallback((y,f)=>{n(A=>{const C=A.length===0?y:_m(y,A,f),v=!Lm(A,C);return v&&Fs.record({kind:"dashboard.entries_applied",payload:{incoming:Ci(y),next:Ci(C)}}),v?C:A})},[]),w=i.useCallback(()=>o(!0),[]),x=i.useMemo(()=>({injectEntries:b,markLoaded:w,getIdes:()=>u.current}),[b,w]),h=t,g=i.useMemo(()=>({ides:r,updateRouteChats:p,initialLoaded:a,toasts:l,setToasts:c,wsStatus:(h==null?void 0:h.wsStatus)??"connected",isConnected:(h==null?void 0:h.isConnected)??!0,connectionStates:(h==null?void 0:h.connectionStates)??{},connectionTransports:(h==null?void 0:h.connectionTransports)??{},showReconnected:(h==null?void 0:h.showReconnected)??!1,retryConnection:h==null?void 0:h.retryConnection,retryServerConnection:h==null?void 0:h.retryServerConnection,connectionLoginUrl:h==null?void 0:h.connectionLoginUrl,isP2PActive:(h==null?void 0:h.isP2PActive)??!1,p2pStates:(h==null?void 0:h.p2pStates)??{},userRole:h==null?void 0:h.userRole,connectionRetryStatuses:h==null?void 0:h.connectionRetryStatuses,userName:d,setUserName:m}),[r,p,a,l,h==null?void 0:h.wsStatus,h==null?void 0:h.isConnected,h==null?void 0:h.connectionStates,h==null?void 0:h.connectionTransports,h==null?void 0:h.showReconnected,h==null?void 0:h.retryConnection,h==null?void 0:h.retryServerConnection,h==null?void 0:h.connectionLoginUrl,h==null?void 0:h.isP2PActive,h==null?void 0:h.p2pStates,h==null?void 0:h.userRole,h==null?void 0:h.connectionRetryStatuses,d]);return s.jsx(sc.Provider,{value:x,children:s.jsx(tc.Provider,{value:g,children:e})})}function cs(){return i.useContext(tc)}function Cr(){return i.useContext(sc)}function ac(e){const{baseUrl:t,getToken:r,onUnauthorized:n}=e;function a(c){return c.startsWith("http")?c:`${t}${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")&&!t?`${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 p=a(c),b=new AbortController,w=setTimeout(()=>b.abort(),15e3);try{const x=await fetch(p,{...d,headers:m,signal:b.signal});if(x.status===401)throw n==null||n(),new Error("Unauthorized");if(!x.ok){const h=await x.json().catch(()=>({error:x.statusText}));throw new Error(h.error||`API Error: ${x.status}`)}return x.json()}finally{clearTimeout(w)}}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 Pm=ac({baseUrl:"http://localhost:3847"}),Dm=i.createContext(Pm);function Em({client:e,children:t}){return s.jsx(Dm.Provider,{value:e,children:t})}const $m={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},oc=i.createContext($m);function Bm({value:e,children:t}){return s.jsx(oc.Provider,{value:e,children:t})}function kt(){return i.useContext(oc)}function Om(e){let t=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)t^=n.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function Fm(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Wm(e){return e?Om([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Fm(e.content)]):""}const ze={size:18};function ic({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function So({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function os({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function lc({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Hm({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Km({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.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 cc({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.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"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Um({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Wn({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.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 dc({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function zm({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Zt({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function Rt({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function No({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Gm({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ss({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.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=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Ir({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Hs({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function ns({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function Vm({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),s.jsx("polyline",{points:"2 12 12 17 22 12"}),s.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function uc({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Co({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.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"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function mc({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function qm({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Io({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function Ym({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Mo({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function pc({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function jt({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Xm({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.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"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Jm({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Qm({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.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 Zm({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.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 Hn({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function ep({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function tp({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function sp({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function rp({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function np({size:e=ze.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function ap({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.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 op({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.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"}),s.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"}),s.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 ip({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function lp({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function cp({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function dp({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.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 up({size:e=ze.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Ao="adhdev_chat_activity_visible",_i=new Set(["hidden","debug","internal"]),Li=new Set(["visible","user","chat"]),mp=new Set(["debug","trace","internal"]),pp=new Set(["tool_call","terminal_command","runtime_activity"]),hp=new Set(["runtime_status","provider_chrome","control"]),fp=new Set(["thought","tool","terminal"]);function hc(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function _s(e){return typeof e=="string"?e.trim().toLowerCase():""}function na(e,t,r){return e[r]??(t==null?void 0:t[r])}function Ri(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function xp(e,t){const r=_s(e.kind);return r||(t==="tool"?"tool":"standard")}function aa(e,t,r){const n=hc(e),a=typeof(n==null?void 0:n.label)=="string"?n.label.trim():"";return a||(t==="terminal"||r==="terminal_command"?"Terminal":t==="tool"||r==="tool_call"?"Tool":t==="thought"?"Thought":r==="runtime_activity"?"Runtime":"Activity")}function bp(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function To(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=hc(e),r=_s(e.role),n=xp(e,r),a=_s(na(e,t,"visibility")),o=_s(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),l=_s(na(e,t,"audience")),c=_s(na(e,t,"source")),d=_i.has(a)||_i.has(o)||mp.has(l)||Ri(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),m=Li.has(a)||Li.has(o)||l==="chat"||Ri(e,t,["userFacing"]),u=fp.has(n)||pp.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:aa(e,n,c)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:aa(e,n,c)};if((r==="system"||n==="system")&&bp(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(hp.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:aa(e,n,c)};const p=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:p?"chat":"internal",isUserFacing:p,isActivityFacing:!1,isInternal:!p,role:r,kind:n,label:p?"Chat":"Internal"}}function gp(e){return(Array.isArray(e)?e:[]).filter(t=>To(t).isUserFacing)}function fc(e){return(Array.isArray(e)?e:[]).filter(t=>To(t).isActivityFacing)}function yp(e,t,r){return!r||t.length===0?e:[...e,...t].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 Pi(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(Ao))==="1"}catch{return!1}}function vp(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(Ao,e?"1":"0")}catch{}}const xc=[tm,{singleTilde:!1}],bc=[xc,sm,rm],wp=[xc],_o=200,jp=80,Di=650,tr=new Map;function Nn(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function kp(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(t||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${Wm(n)}`}function Sp(e,t,r,n){return e||!t?!1:Nn(r,n)}function Np({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=jp,bottomThresholdPx:a=_o}){const o=Math.max(0,Number(e)||0),l=Math.max(0,Number(t)||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 Cp(e){return Np({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function xr(e,t=_o){return!!e&&e.fromBottom>=t}function Ip(e,t){return Nn(e,t)?!xr(e):!0}function Mp({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function Ap({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function oa(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function gc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function Tp(e,t,r){return Number(e.receivedAt||r[Cn(e,t)]||0)||0}function yc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function _p(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function sr(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function ia(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 Ur(e,t,r){return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[s.jsx("span",{className:"font-medium",children:e}),t?s.jsx("span",{className:"ml-1 break-all",children:t}):null,r?s.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:r}):null]})}function Ei(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):yc(e)?s.jsx(wo,{remarkPlugins:bc,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function rr({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return s.jsx("div",{children:Ei(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=ia(r),o=r.alt||r.description||sr(r.uri,"image");return a?s.jsx("img",{src:a,alt:o,className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):s.jsx("div",{children:Ur("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=ia(r);return a?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),r.transcript?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r.transcript}):null]},`audio-${n}`):s.jsx("div",{children:Ur("Audio",sr(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=ia(r),o=r.title||r.name||r.alt||sr(r.uri,"video"),l=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
|
|
3
|
+
`);return s.jsxs("div",{className:"flex flex-col gap-1",children:[a?s.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):Ur("Video",o,l),a&&l?s.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||sr(r.uri,"resource"),o=[r.description,r.mimeType].filter(Boolean).join(`
|
|
4
|
+
`);return s.jsxs("div",{className:"flex flex-col gap-1",children:[r.uri?s.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:a}):Ur("Resource",a,o),r.uri&&o?s.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=sr(r.resource.uri,"resource");if(r.resource.text)return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),Ei(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return s.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function Cn(e,t){const r=e,n=ko(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:${t}`].filter(Boolean).join("|")}const Lp=i.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(wo,{remarkPlugins:wp,children:t.text}),s.jsx("span",{className:"action-time",children:gc(t.timestamp)})]})},(e,t)=>e.log===t.log),Rp=i.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:l,onToggleTextExpanded:c}){var k,j,B;const d=(t.role||"").toLowerCase(),m=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),p=To(t),b=_p(t.content)?t.content:null,w=!!(b!=null&&b.some(L=>L.type!=="text")),x=ko(t.content,{joiner:`
|
|
6
|
+
`});if(p.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const L=p.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:L})]}),w&&b?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(rr,{parts:b,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:x})]})}if(u==="thought"){const L=typeof((k=t.meta)==null?void 0:k.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":p.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Qm,{size:13}),s.jsx("span",{children:L})]}),s.jsx("div",{className:"chat-msg-body",children:x})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":p.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),w&&b?s.jsx("div",{className:"tool-text w-full",children:s.jsx(rr,{parts:b,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:x})]});if(u==="terminal"){const L=(j=t.meta)!=null&&j.isRunning?"⏳":"✅",S=typeof((B=t.meta)==null?void 0:B.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":p.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:L}),s.jsx("span",{children:S})]}),w&&b?s.jsx("div",{className:"chat-msg-body",children:s.jsx(rr,{parts:b,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:x})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:w&&b?s.jsx(rr,{parts:b,renderAsPreformatted:!1}):x.slice(0,100)});const h=t.meta,y=(typeof(h==null?void 0:h.renderMode)=="string"?h.renderMode.trim():"")==="preformatted",f=x,A=!1,C=f,v=y,N=!v&&yc(C),T=["chat-message-row",m?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:T,children:(f||w||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${f||w?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:m?a||"You":t.senderName||n}),r!=null&&s.jsx("span",{className:"chat-time",children:gc(r)})]}),(f||w)&&s.jsx("div",{className:"chat-markdown",children:w&&b?s.jsx(rr,{parts:b,renderAsPreformatted:v}):v?s.jsx("pre",{className:"chat-preformatted",children:C}):N?s.jsx(wo,{remarkPlugins:bc,children:C}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:C})}),A]})})},(e,t)=>e.message===t.message&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),Pp=i.forwardRef(function({messages:t,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:l=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:m,showActivityMessages:u=!1,emptyState:p,onLoadMore:b,isLoadingMore:w,hasMoreHistory:x,hiddenLiveCount:h=0,loadError:g,scrollToBottomRequestNonce:y,isVisible:f=!0},A){const C=i.useRef(null),v=i.useRef(null),N=i.useRef(null),T=i.useRef(0),k=i.useRef(""),j=i.useRef(""),B=i.useRef(!1),L=i.useRef(null),S=i.useRef(!1),D=i.useRef(null),$=i.useRef(!1),[E,I]=i.useState(new Set),[M,F]=i.useState({showTop:!1,showBottom:!1}),P=i.useRef(!1),R=i.useRef(!1),K=i.useRef(f),V=i.useRef(f),te=i.useRef(null);V.current=f;const ie=()=>{const ce=C.current;return ce?ce.scrollHeight-ce.scrollTop-ce.clientHeight<_o:!0},J=i.useCallback(()=>{const ce=C.current,pe=ce?Cp(ce):{showTop:!1,showBottom:!1};F(ae=>ae.showTop===pe.showTop&&ae.showBottom===pe.showBottom?ae:pe)},[]),me=i.useCallback((ce="auto")=>{var ae;const pe=C.current;pe&&(pe.scrollTo({top:pe.scrollHeight,behavior:ce}),(ae=pe.ownerDocument.defaultView)==null||ae.requestAnimationFrame(()=>J()))},[J]),je=i.useCallback((ce="auto")=>{var ae;const pe=C.current;pe&&(pe.scrollTo({top:0,behavior:ce}),(ae=pe.ownerDocument.defaultView)==null||ae.requestAnimationFrame(()=>J()))},[J]),ke=i.useCallback(()=>{var Ce;const ce=C.current,pe=(Ce=window.getSelection)==null?void 0:Ce.call(window);if(!ce||!pe||pe.rangeCount===0||pe.isCollapsed){$.current=!1;return}const ae=pe.anchorNode,Ie=pe.focusNode;$.current=!!(ae&&Ie&&ce.contains(ae)&&ce.contains(Ie))},[]),q=i.useMemo(()=>{const ce=gp(t),pe=fc(t);return yp(ce,pe,u)},[t,u]),ge=q.length===t.length?m:void 0,fe=kp(q,ge),we=i.useCallback(()=>{const ce=C.current;if(!ce||!c||!V.current)return;const pe={top:ce.scrollTop,fromBottom:Math.max(0,ce.scrollHeight-ce.scrollTop-ce.clientHeight),messageFingerprint:fe};te.current={contextKey:c,snapshot:pe},tr.set(c,pe)},[c,fe]),xe=i.useCallback((ce="auto")=>{L.current!=null&&cancelAnimationFrame(L.current),L.current=requestAnimationFrame(()=>{L.current=null,me(ce)})},[me]),Ne=i.useCallback(()=>{P.current=!1,S.current=!0,R.current=!0,D.current!=null&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{S.current=!1,D.current=null},Di)},[]);i.useEffect(()=>{const ce=!B.current,pe=j.current!==c;if(j.current=c,ce||pe){B.current=!0;const Ie=c?tr.get(c):null,Ce=!!Ie&&Nn(Ie,fe);P.current=Ce?xr(Ie):!1,S.current=Ip(Ie,fe),$.current||(Ce?requestAnimationFrame(()=>{const _e=C.current;_e&&(oa(_e,Ie),P.current=xr(Ie),J(),R.current=!0)}):xe("auto")),T.current=q.length,k.current=fe;return}q.length>T.current;const ae=fe!==k.current;Mp({hasSelection:$.current,userScrolledUp:P.current,hasChatContentChanged:ae})&&xe("auto"),T.current=q.length,k.current=fe},[fe,c,q.length,xe,J]),i.useEffect(()=>{y&&(Ne(),$.current||xe("auto"))},[Ne,xe,y]),i.useEffect(()=>{const ce=K.current;ce&&!f&&we(),V.current=f,K.current=f;const pe=c?tr.get(c):null;if(Sp(ce,f,pe,fe)){if(!pe)return;P.current=xr(pe),S.current=!1,$.current||requestAnimationFrame(()=>{const ae=C.current;ae&&(oa(ae,pe),J())});return}},[f,c,fe,Ne,we,xe,J]),i.useEffect(()=>()=>{const ce=te.current;ce&&tr.set(ce.contextKey,ce.snapshot),L.current!=null&&cancelAnimationFrame(L.current),D.current!=null&&window.clearTimeout(D.current)},[]),i.useEffect(()=>{const ce=v.current,pe=C.current;if(!ce||!pe)return;const ae=()=>{D.current!=null&&window.clearTimeout(D.current),D.current=window.setTimeout(()=>{S.current=!1,D.current=null},Di)},Ie=new ResizeObserver(()=>{J();const Ce=S.current;Ap({hasSelection:$.current,userScrolledUp:P.current,contextAutoScrollActive:Ce})&&(xe("auto"),Ce&&ae())});return Ie.observe(ce),pe!==ce&&Ie.observe(pe),()=>{Ie.disconnect(),D.current!=null&&(window.clearTimeout(D.current),D.current=null)}},[xe,c,J]),i.useImperativeHandle(A,()=>({scrollToBottom:(ce="smooth")=>{me(ce)}}),[me]),i.useEffect(()=>{const ce=C.current;if(!ce)return;let pe;const ae=()=>{we(),clearTimeout(pe),pe=setTimeout(()=>{P.current=!ie(),J()},50)};return ce.addEventListener("scroll",ae,{passive:!0}),()=>{ce.removeEventListener("scroll",ae),clearTimeout(pe)}},[we,J]),i.useEffect(()=>(document.addEventListener("selectionchange",ke),()=>document.removeEventListener("selectionchange",ke)),[ke]);const Q=i.useRef(0),he=i.useRef(!1);i.useEffect(()=>{const ce=C.current;if(!ce||!he.current||Q.current===0)return;const pe=ce.scrollHeight-Q.current;pe>0&&(ce.scrollTop=pe),J(),we(),Q.current=0,he.current=!1},[q.length,we,J]),i.useEffect(()=>{if(R.current||!c)return;const ce=tr.get(c),pe=C.current;if(!(!ce||!pe)){if(!Nn(ce,fe)){me("auto"),R.current=!0;return}oa(pe,ce),P.current=xr(ce),J(),R.current=!0}},[c,fe,q.length,me,J]);const oe=()=>{const ce=C.current;ce&&(Q.current=ce.scrollHeight),he.current=!0,b==null||b()},ue=()=>{P.current=!0,je("smooth"),we()},le=()=>{Ne(),me("smooth"),we()},de=i.useMemo(()=>{const ce=q.map((Ce,_e)=>({type:"message",data:Ce,index:_e,ts:Tp(Ce,_e,d)}));if(!r||r.length===0)return ce;const pe=[...r].sort((Ce,_e)=>Ce.timestamp-_e.timestamp).map((Ce,_e)=>({type:"action",data:Ce,index:_e,ts:Ce.timestamp})),ae=[];let Ie=0;for(const Ce of ce){for(;Ie<pe.length&&Ce.ts>0&&pe[Ie].ts<Ce.ts;)ae.push(pe[Ie++]);ae.push(Ce)}for(;Ie<pe.length;)ae.push(pe[Ie++]);return ae},[q,r,d]),Z=h>0||!!x,ve=h>0?`↑ Show ${Math.min(h,80)} earlier messages${h>80?` (${h} hidden)`:""}`:g?`↻ ${g}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:C,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:v,className:"chat-container-content",children:[w&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),Z&&!w&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:oe,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${g&&h===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:ve})}),de.length===0&&!Z&&(p||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),de.map(ce=>{if(ce.type==="action"){const Me=ce.data;return s.jsx(Lp,{log:Me},`action-${ce.index}`)}const pe=ce.data,ae=ce.index,Ie=Cn(pe,ae),Ce=pe.receivedAt||d[Ie],_e=`${c}-${Ie}`,H=E.has(_e);return s.jsx(Rp,{message:pe,receivedAt:Ce,agentName:n,userName:a,isCliMode:o,isTextExpanded:H,onToggleTextExpanded:()=>I(Me=>{const Ae=new Set(Me);return H?Ae.delete(_e):Ae.add(_e),Ae})},`msg-${Ie}`)}),l&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),s.jsx("div",{className:"min-h-10",ref:N})]})}),(M.showTop||M.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[M.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ue,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),M.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:le,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Dp=i.memo(Pp,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.showActivityMessages===t.showActivityMessages&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),Ep="modulepreload",$p=function(e){return"/"+e},$i={},Bp=function(t,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=$p(d),d in $i)return;$i[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const p=document.createElement("link");if(p.rel=m?"stylesheet":Ep,m||(p.as="script"),p.crossOrigin="",p.href=d,c&&p.setAttribute("nonce",c),document.head.appendChild(p),m)return new Promise((b,w)=>{p.addEventListener("load",b),p.addEventListener("error",()=>w(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 t().catch(o)})};let Bi=!1;const vc=i.forwardRef(({onInput:e,onViewportMetrics:t,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([]),p=i.useRef(!1),b=i.useRef(!1),w=i.useRef(!1),x=i.useRef(!1),h=()=>{const g=c.current;if(g){p.current&&(g.clear(),p.current=!1);for(const y of u.current)g.write(y.data,y.onProcessed);u.current=[],b.current&&(g.fit(),b.current=!1),w.current&&(g.bumpResize(),w.current=!1),x.current&&(g.scrollToTop(),x.current=!1)}};return i.useImperativeHandle(l,()=>({write:(g,y)=>{c.current?c.current.write(g,y):u.current.push({data:g,onProcessed:y})},clear:()=>{c.current?c.current.clear():(u.current=[],p.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],p.current=!0)},resize:(g,y)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(g,y)},fit:()=>{c.current?c.current.fit():b.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():w.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():x.current=!0},getSelection:()=>{var g,y;return((y=(g=c.current)==null?void 0:g.getSelection)==null?void 0:y.call(g))||""},getVisibleText:()=>{var g,y;return((y=(g=c.current)==null?void 0:g.getVisibleText)==null?void 0:y.call(g))||""}}),[]),i.useEffect(()=>{d&&h()},[d]),i.useEffect(()=>{let g=!1;return Bp(()=>import("./terminal-D46M5EWH.js"),__vite__mapDeps([0,1,2])).then(y=>{Bi||(Bi=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),g||m(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{g=!0}},[]),d?s.jsx(d,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});vc.displayName="CliTerminal";function zr({label:e,value:t,sub:r,icon:n}){return s.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:n}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),r&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function Oi({value:e,max:t,label:r,color:n="#8b5cf6",detail:a,compact:o=!1}){const l=t>0?Math.min(Math.round(e/t*100),100):0,c=l>85?"#ef4444":l>60?"var(--status-warning)":n;return o?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[l,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${l}%`,background:c}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[l,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${l}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Op({cursorPos:e,viewportRef:t,imgRef:r}){var f;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(f=t.current)==null?void 0:f.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,p,b,w;d>m?(u=a.width,p=a.width/d,b=0,w=(a.height-p)/2):(p=a.height,u=a.height*d,b=(a.width-u)/2,w=0);const x=a.left-o.left+b+u*e.nx,h=a.top-o.top+w+p*e.ny,g=Math.max(8,Math.min(o.width-8,x)),y=Math.max(8,Math.min(o.height-8,h));return s.jsxs("div",{style:{position:"absolute",left:g-8,top:y-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.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 Fp({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:l,setImeText:c,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:p,mobileFillZoom:b,onZoomOut:w,onZoomReset:x,onZoomIn:h,transportType:g,screenshotUsage:y,lastActionStatus:f}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:A=>A.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:[s.jsxs("div",{onClick:t,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:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{n(A=>!A),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:s.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&s.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:s.jsx("input",{type:"text",placeholder:"Type & Enter...",value:l,autoFocus:!0,onTouchStart:A=>A.stopPropagation(),onChange:A=>c(A.target.value),onKeyDown:A=>{d(A)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(A=>!A),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:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.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:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),g==="direct"&&s.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"}),g==="relay"&&s.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&&s.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`}),f&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:f})]})]}),a&&s.jsxs("div",{onTouchStart:A=>A.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:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(p?b:1)+.01?p?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:A=>{A.stopPropagation(),w()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:A=>{A.stopPropagation(),x()},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:p?"FILL":"FIT"}),s.jsx("button",{onClick:A=>{A.stopPropagation(),h()},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 Wp({waitingLabel:e,waitingHint:t,transportType:r}){return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.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:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),r==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function Hp(){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 Fi(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 _r(e,t){const r=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{if(!Hp())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([l,c])=>[l,Fi(c)]))}),r.current=t;return}const o=Object.keys({...a,...t}).filter(l=>!Object.is(a[l],t[l]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(l=>[l,Fi(t[l])]))}),r.current=t})}function Kp({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:l,panXRef:c,panYRef:d,setPanX:m,setPanY:u,setZoom:p,lastWheelTimeRef:b,onAction:w,setLastActionStatus:x,spawnRippleFromNormalized:h,clampPan:g,isMobile:y,mobileFillZoom:f}){const[A,C]=i.useState(null),v=i.useRef(null),N=i.useRef(null),T=i.useRef(null),k=i.useRef(!1),j=i.useRef(null),B=i.useRef(0),L=i.useRef(null),S=i.useRef(1),D=i.useRef({x:0,y:0}),$=i.useRef(!1),E=i.useRef(n),I=i.useRef(w),M=30,F=550,P=18,R=60,K=400,V=12,te=()=>{if(v.current)return;const me={nx:.5,ny:.5};v.current=me,C(me)};return i.useEffect(()=>{E.current=n,n==="mouse"&&te()},[n]),i.useEffect(()=>{I.current=w},[w]),i.useEffect(()=>{const me=e.current;if(!me)return;const je=xe=>{if(!r.current)return null;const Ne=r.current.getBoundingClientRect();return!Ne.width||!Ne.height?null:{nx:Math.max(0,Math.min(1,(xe.clientX-Ne.left)/Ne.width)),ny:Math.max(0,Math.min(1,(xe.clientY-Ne.top)/Ne.height))}},ke=(xe,Ne)=>{if(!r.current)return{dnx:0,dny:0};const Q=r.current,he=Q.getBoundingClientRect(),oe=Q.naturalWidth||he.width,ue=Q.naturalHeight||he.height,le=oe/ue,de=he.width/he.height;let Z,ve;return le>de?(Z=he.width,ve=he.width/le):(ve=he.height,Z=he.height*le),{dnx:xe/Z,dny:Ne/ve}},q=(xe,Ne,Q)=>{if(Q<=1.05)return;const he=-(xe-.5)*100,oe=-(Ne-.5)*100,ue=g(he,oe,Q);(Math.abs(ue.x-c.current)>.1||Math.abs(ue.y-d.current)>.1)&&(m(ue.x),u(ue.y),c.current=ue.x,d.current=ue.y)},ge=xe=>{const Ne=t.current;if(Ne&&xe.target instanceof Node&&Ne.contains(xe.target))xe.preventDefault();else return;if(xe.touches.length===1){const Q=xe.touches[0];N.current={x:Q.clientX,y:Q.clientY,time:Date.now()},T.current={x:Q.clientX,y:Q.clientY},$.current||(k.current=!1),j.current=setTimeout(()=>{if(!k.current&&!$.current)if(k.current=!0,E.current==="mouse"){const he=v.current||{nx:.5,ny:.5};x("Right Click"),h(he.nx,he.ny,"right"),I.current("input_click",{...he,button:"right"}).catch(()=>{})}else{const he=je(Q);he&&(x("Right Click"),h(he.nx,he.ny,"right"),I.current("input_click",{...he,button:"right"}).catch(()=>{}))}},500);return}if(xe.touches.length===2){j.current&&clearTimeout(j.current),k.current=!0,$.current=!0;const Q=xe.touches[1].clientX-xe.touches[0].clientX,he=xe.touches[1].clientY-xe.touches[0].clientY;L.current=Math.sqrt(Q*Q+he*he),S.current=l.current,D.current={x:(xe.touches[0].clientX+xe.touches[1].clientX)/2,y:(xe.touches[0].clientY+xe.touches[1].clientY)/2}}},fe=xe=>{const Ne=t.current;if(Ne&&xe.target instanceof Node&&Ne.contains(xe.target)&&xe.preventDefault(),xe.touches.length===1&&T.current){const Q=xe.touches[0],he=Q.clientX-T.current.x,oe=Q.clientY-T.current.y;if(!k.current&&N.current){const ue=Q.clientX-N.current.x,le=Q.clientY-N.current.y;Math.sqrt(ue*ue+le*le)>8&&(k.current=!0,j.current&&clearTimeout(j.current))}if(k.current)if(E.current==="mouse"){const ue=ke(he,oe),le=v.current||{nx:.5,ny:.5},de=Math.max(0,Math.min(1,le.nx+ue.dnx)),Z=Math.max(0,Math.min(1,le.ny+ue.dny));v.current={nx:de,ny:Z},C({nx:de,ny:Z}),x(`Cursor: ${Math.round(de*100)}%, ${Math.round(Z*100)}%`),q(de,Z,l.current);const ve=Date.now();ve-b.current>=30&&(b.current=ve,I.current("input_mouseMoved",{nx:de,ny:Z}).catch(()=>{}))}else if(l.current>1){const ue=t.current;if(ue){const le=ue.clientWidth,de=ue.clientHeight,Z=c.current+he/le*100,ve=d.current+oe/de*100,ce=g(Z,ve,l.current);m(ce.x),u(ce.y),c.current=ce.x,d.current=ce.y}}else{const ue=je(Q);if(ue){const le=Date.now();le-b.current>=40&&(b.current=le,x("Scroll"),I.current("input_wheel",{nx:ue.nx,ny:ue.ny,deltaX:Math.round(-he*2.5),deltaY:Math.round(-oe*2.5)}).catch(()=>{}))}}T.current={x:Q.clientX,y:Q.clientY};return}if(xe.touches.length===2&&L.current!==null){const Q=xe.touches[1].clientX-xe.touches[0].clientX,he=xe.touches[1].clientY-xe.touches[0].clientY,ue=Math.sqrt(Q*Q+he*he)/L.current,le=(xe.touches[0].clientX+xe.touches[1].clientX)/2,de=(xe.touches[0].clientY+xe.touches[1].clientY)/2,Z=le-D.current.x,ve=de-D.current.y,ce=Math.abs(ue-1)>.03;if(E.current==="mouse"){if(ce){const pe=Math.max(o,Math.min(5,S.current*ue));p(pe),l.current=pe}else if(Math.abs(Z)>2||Math.abs(ve)>2){const pe=v.current||{nx:.5,ny:.5},ae=Date.now();ae-b.current>=30&&(b.current=ae,x("Scroll"),I.current("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(-Z*3),deltaY:Math.round(-ve*3)}).catch(()=>{}))}}else{const pe=Math.max(o,Math.min(5,S.current*ue));p(pe),l.current=pe;const ae=t.current;if(ae&&pe>1){const Ie=ae.clientWidth,Ce=ae.clientHeight,_e=c.current+Z/Ie*100,H=d.current+ve/Ce*100,Me=g(_e,H,pe);m(Me.x),u(Me.y),c.current=Me.x,d.current=Me.y}}D.current={x:le,y:de}}},we=xe=>{var Ne;if(j.current&&clearTimeout(j.current),L.current=null,xe.touches.length===1&&$.current){const Q=xe.touches[0];N.current={x:Q.clientX,y:Q.clientY,time:Date.now()},T.current={x:Q.clientX,y:Q.clientY},k.current=!0;return}if(xe.touches.length===0){if($.current){$.current=!1,k.current=!1;return}if(xe.changedTouches.length===1){const Q=xe.changedTouches[0],he=Date.now(),oe=he-(((Ne=N.current)==null?void 0:Ne.time)||0),ue=N.current?Q.clientX-N.current.x:0,le=N.current?Q.clientY-N.current.y:0,de=Math.sqrt(ue*ue+le*le);if(E.current==="mouse"){if(oe<M||oe>F||de>P){k.current=!1;return}const Z=v.current||je(Q);Z&&(x(`Click: ${Math.round(Z.nx*100)}%, ${Math.round(Z.ny*100)}%`),h(Z.nx,Z.ny,"left"),I.current("input_click",{...Z}).catch(()=>{}))}else{if(k.current){k.current=!1;return}if(oe<R||oe>K||de>V){k.current=!1;return}const Z=je(Q);if(!Z)return;he-B.current<300?(x("Double tap"),h(Z.nx,Z.ny,"double"),I.current("input_click",{...Z,clickCount:2}).catch(()=>{}),B.current=0):(x(`Tap: ${Math.round(Z.nx*100)}%, ${Math.round(Z.ny*100)}%`),h(Z.nx,Z.ny,"left"),I.current("input_click",{...Z}).catch(()=>{}),B.current=he)}}k.current=!1}};return me.addEventListener("touchstart",ge,{passive:!1}),me.addEventListener("touchmove",fe,{passive:!1}),me.addEventListener("touchend",we,{passive:!1}),()=>{me.removeEventListener("touchstart",ge),me.removeEventListener("touchmove",fe),me.removeEventListener("touchend",we),j.current&&clearTimeout(j.current)}},[e,t,r,o,l,c,d,m,u,p,b,x,h,g]),{cursorPos:A,cursorPosRef:v,handleToggleInputMode:()=>{a(me=>{const je=me==="touch"?"mouse":"touch";return je==="mouse"&&te(),je})},handleZoomReset:()=>{const me=y?f:1;p(me),l.current=me,m(0),u(0),c.current=0,d.current=0}}}function wc({onAction:e,addLog:t,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),[p,b]=i.useState(""),[,w]=i.useState(!1),[x,h]=i.useState([]),g=i.useRef(0),[y,f]=i.useState(!1),[A,C]=i.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[N,T]=i.useState(v?"mouse":"touch"),[k,j]=i.useState(1),B=i.useRef(!1),[L,S]=i.useState(1),[D,$]=i.useState(0),[E,I]=i.useState(0);_r("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:N,zoom:L,panX:D,panY:E,isMenuOpen:y,isImeOpen:A});const M=i.useRef(0),F=i.useRef(L),P=i.useRef(D),R=i.useRef(E);i.useEffect(()=>{F.current=L},[L]),i.useEffect(()=>{P.current=D},[D]),i.useEffect(()=>{R.current=E},[E]),i.useEffect(()=>{var oe;(oe=l.current)==null||oe.focus()},[]);const K=r==="connected",V=n,te=K?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ie=K?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!v||B.current||!V)return;const oe=d.current,ue=c.current;if(!oe||!ue)return;const le=()=>{const de=ue.clientWidth,Z=ue.clientHeight,ve=oe.naturalWidth,ce=oe.naturalHeight;if(!ve||!ce||!de||!Z)return;const pe=Math.min(de/ve,Z/ce),Ie=Math.max(de/ve,Z/ce)/pe;Ie>1.01&&(j(Ie),S(Ie),F.current=Ie),B.current=!0};oe.complete&&oe.naturalWidth?le():oe.addEventListener("load",le,{once:!0})},[V,v]);const J=.5;i.useEffect(()=>{L<=J&&($(0),I(0))},[L,J]);const me=(oe,ue,le)=>{if(le<=J)return{x:0,y:0};const de=(le-1)/(2*le)*100,Z=(le-1)/(2*le)*100;return{x:Math.max(-de,Math.min(de,oe)),y:Math.max(-Z,Math.min(Z,ue))}},je=(oe,ue)=>{if(!d.current)return null;const le=d.current.getBoundingClientRect();return!le.width||!le.height?null:{nx:Math.max(0,Math.min(1,(oe-le.left)/le.width)),ny:Math.max(0,Math.min(1,(ue-le.top)/le.height))}},ke=(oe,ue,le)=>{const de=c.current;if(!de)return;const Z=de.getBoundingClientRect(),ve=++g.current;h(ce=>[...ce,{id:ve,x:oe-Z.left,y:ue-Z.top,type:le}]),setTimeout(()=>h(ce=>ce.filter(pe=>pe.id!==ve)),600)},q=(oe,ue,le)=>{const de=d.current,Z=c.current;if(!de||!Z)return;const ve=de.getBoundingClientRect(),ce=Z.getBoundingClientRect(),pe=de.naturalWidth||ve.width,ae=de.naturalHeight||ve.height,Ie=pe/ae,Ce=ve.width/ve.height;let _e,H,Me,Ae;Ie>Ce?(_e=ve.width,H=ve.width/Ie,Me=0,Ae=(ve.height-H)/2):(H=ve.height,_e=ve.height*Ie,Me=(ve.width-_e)/2,Ae=0);const He=ve.left-ce.left+Me+_e*oe,Ge=ve.top-ce.top+Ae+H*ue,Xe=++g.current;h(Ye=>[...Ye,{id:Xe,x:He,y:Ge,type:le}]),setTimeout(()=>h(Ye=>Ye.filter(tt=>tt.id!==Xe)),600)},ge=async oe=>{var le;const ue=je(oe.clientX,oe.clientY);if(ue){u(`Click: ${Math.round(ue.nx*100)}%, ${Math.round(ue.ny*100)}%`),ke(oe.clientX,oe.clientY,"left"),(le=l.current)==null||le.focus();try{const de=await e("input_click",{nx:ue.nx,ny:ue.ny});de!=null&&de.success||t(`❌ Click failed: ${de==null?void 0:de.error}`)}catch(de){t(`❌ Click error: ${de.message||de}`)}}},fe=async(oe,ue,le,de=0)=>{try{await e("input_key",{type:le?"char":"keyDown",key:oe,code:ue,text:le?oe:void 0,unmodifiedText:le?oe:void 0,modifiers:de})}catch(Z){t(`❌ Key error: ${Z.message||Z}`)}},we=async oe=>{if(oe.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(oe.key)&&oe.preventDefault();let le=0;oe.altKey&&(le|=1),oe.ctrlKey&&(le|=2),oe.metaKey&&(le|=4),oe.shiftKey&&(le|=8),u(`Key: ${oe.key}`),await fe(oe.key,oe.code,oe.key.length===1,le)},xe=async oe=>{if(oe.key==="Enter"){if(oe.nativeEvent.isComposing)return;if(p){const ue=p;b(""),u(`IME Sent: ${ue}`);try{const le=await e("input_type",{text:ue});le!=null&&le.success||t(`❌ IME error: ${le==null?void 0:le.error}`)}catch(le){t(`❌ IME error: ${le.message}`)}}else u("Key: Enter"),await fe("Enter","Enter",!1)}};i.useEffect(()=>{const oe=l.current;if(!oe)return;const ue=le=>{var de;if((de=d.current)!=null&&de.contains(le.target)){le.preventDefault();const Z=Date.now();if(Z-M.current<40)return;M.current=Z;const ve=je(le.clientX,le.clientY);if(!ve)return;u(`Scroll: ${Math.round(le.deltaY)}`),e("input_wheel",{nx:ve.nx,ny:ve.ny,deltaX:Math.round(le.deltaX),deltaY:Math.round(le.deltaY)}).catch(()=>{})}};return oe.addEventListener("wheel",ue,{passive:!1}),()=>oe.removeEventListener("wheel",ue)},[e]);const{cursorPos:Ne,handleToggleInputMode:Q,handleZoomReset:he}=Kp({containerRef:l,viewportRef:c,imgRef:d,inputMode:N,setInputMode:T,minZoom:J,zoomRef:F,panXRef:P,panYRef:R,setPanX:$,setPanY:I,setZoom:S,lastWheelTimeRef:M,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:q,clampPan:me,isMobile:v,mobileFillZoom:k});return s.jsxs("div",{ref:l,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:we,onContextMenu:oe=>oe.preventDefault(),onFocus:()=>w(!0),onBlur:()=>w(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[V?s.jsx("img",{ref:d,src:V,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${D}%, ${E}%)`,transformOrigin:"center center",cursor:N==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ge,onContextMenu:oe=>oe.preventDefault(),onDragStart:oe=>oe.preventDefault()}):s.jsx(Wp,{waitingLabel:te,waitingHint:ie,transportType:o}),N==="mouse"&&V&&s.jsx(Op,{cursorPos:Ne,viewportRef:c,imgRef:d}),x.map(oe=>{const le={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[oe.type];return s.jsxs("div",{style:{position:"absolute",left:oe.x,top:oe.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${le}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${le}, 0.9)`,boxShadow:`0 0 12px rgba(${le}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},oe.id)})]}),s.jsx(Fp,{inputMode:N,onToggleInputMode:Q,isImeOpen:A,setIsImeOpen:C,isMenuOpen:y,setIsMenuOpen:f,imeText:p,setImeText:b,handleImeSubmit:xe,isConnActive:K,zoom:L,isMobile:v,mobileFillZoom:k,onZoomOut:()=>S(oe=>Math.max(.5,oe-.25)),onZoomReset:he,onZoomIn:()=>S(oe=>Math.min(5,oe+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),s.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 Kn(e,t={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=t,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 jc=e=>Kn(e);function Up(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 Xs(e){const t=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:r,isGenerating:n,isWaiting:a}}function zp(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Up(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 t}function In(e,t){if(e.sessionId){const r=t.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 Un(e,t,r){const n=In(e,t),a=Xs(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,b=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:b,requiresAction:m,isWorking:u,isReconnecting:o,isConnecting:l,isGenerating:c,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":b?"task_complete":"idle"}}function Gp(e,t,r){return Un(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function kc({activeConv:e,onModalButton:t}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Xs(e).isWaiting||!e.modalButtons)return null;const o=c=>{r||(n(c),t(c))},l=c=>c.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.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&&s.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)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(Ir,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),s.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),p=/^(reject|deny|delete|remove|abort)/.test(m),b=r===c,w=r!==null;return s.jsx("button",{onClick:()=>o(c),disabled:w,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":p?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!b?"opacity-40":"opacity-100"} ${w?"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)"}:p?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:b?"⏳ ...":l(c)},d)})})]})]})}const Lo="adhdev_controls_bar_visible",to="adhdev:controlsbarvisibilitychange";function la(e){if(!e)return!1;try{return e.getItem(Lo)==="1"}catch{return!1}}function Vp(e,t){if(t)try{t.setItem(Lo,e?"1":"0")}catch{}}function qp(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(to,{detail:{visible:e}}))}function Ro(){const[e,t]=i.useState(()=>typeof window>"u"?!1:la(window.localStorage)),r=i.useRef(e),n=i.useCallback((l,c=!0)=>{r.current=l,t(l),typeof window<"u"&&Vp(l,window.localStorage),c&&qp(l)},[]);i.useEffect(()=>{const l=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:la(window.localStorage);r.current=u,t(u)},c=d=>{if(d.key!==Lo)return;const m=la(window.localStorage);r.current=m,t(m)};return window.addEventListener(to,l),window.addEventListener("storage",c),()=>{window.removeEventListener(to,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 Yp=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Xp(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function vt(e,t){if(Xp(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Yp.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 Mn(e){return vt(e)==="generating"}function Wi(e,t){return vt(e,t)==="waiting_approval"}function lt(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Jp(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const r=Math.floor(t/60),n=t%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 ca(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function zn(e,t){const r=typeof t=="string"?t.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 Qp(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),r=t[t.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function Zp(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function eh(e){return Qp(e.trim().replace(/\.local$/i,""))}function th(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function Sc(e,t={}){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&&!Zp(l));if(r&&r!=="Unknown")return eh(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Lt(e,t={}){return th(e)||Sc(e,t)}function Nc(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function Cc(e,t,r={}){const n=String(t).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,t){return Nc(e).join(" · ")}function Mr(e){return e.transport==="pty"}function $s(e){return e.transport==="acp"}function sh(e,t){var r,n;return(r=t==null?void 0:t.providerLabels)!=null&&r[e]?t.providerLabels[e]:(n=t==null?void 0:t.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:lt(e)}function Hi(e,t,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(t||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),l=lt(r||"").trim().toLowerCase();return n===a||n===o||n===l}function rh(e,t=[],r=[]){var d,m,u,p;const n=vt(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=t.find(b=>Wi(b.status,{activeModal:b.activeModal})||Mn(b.status));if(a)return vt(a.status,{activeModal:a.activeModal});const o=r.find(b=>Wi(b.status,{activeModal:b.activeModal})||Mn(b.status));if(o)return vt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const l=vt((d=t[0])==null?void 0:d.status,{activeModal:(m=t[0])==null?void 0:m.activeModal});if(l!=="idle")return l;const c=vt((u=r[0])==null?void 0:u.status,{activeModal:(p=r[0])==null?void 0:p.activeModal});return c!=="idle"?c:"idle"}function nh(e){return vt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function ah(e){if(!Array.isArray(e)||e.length<=1)return e;const t=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=t.get(a),l=vt(n.status);if(!o){t.set(a,{...n,status:l});continue}const c=r.indexOf(o.status||"idle"),d=r.indexOf(l||"idle");d>=0&&(c<0||d<c)&&t.set(a,{...n,status:l})}return Array.from(t.values())}function oh(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function ih(e){var r,n;const t=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return t&&oh(t.receivedAt)||0}function lh(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function so(e){return Math.max(lh(e),ih(e.activeChat))}function ch(e,t,r,n,a,o){const l=t-e;if(l!==0)return l;const c=r.localeCompare(n);return c!==0?c:a.localeCompare(o)}function Po(e,t){return ch(so(e),so(t),Lt(e,{fallbackId:e.id}),Lt(t,{fallbackId:t.id}),e.id,t.id)}const Ic="adhdev_notification_prefs",Ki={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function dh(){try{const e=localStorage.getItem(Ic);if(e){const t=JSON.parse(e);return{...Ki,...t}}}catch{}return{...Ki}}function uh(e){try{localStorage.setItem(Ic,JSON.stringify(e))}catch{}}let Xt=dh(),un=[];function mh(){un.forEach(e=>e())}function ph(e){Xt={...Xt,...e},uh(Xt),mh()}function hh(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return un.push(r),()=>{un=un.filter(n=>n!==r)}},[]);const t=i.useCallback(r=>{ph(r)},[]);return[{...Xt},t]}function yr(e){if(!Xt.globalEnabled)return!1;switch(e){case"disconnect":return Xt.disconnectAlert;case"completion":return Xt.completionAlert;case"approval":return Xt.approvalAlert;case"browser":return Xt.browserNotifications;default:return!0}}const fh={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Mc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Ac(){return"Notification"in window&&Notification.permission==="granted"}let ds=null;function xh(e){return e!==!1}async function bh(){if(ds!==null)return ds;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ds=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ds=!!await e.pushManager.getSubscription(),ds):(ds=!1,!1)}catch{return ds=!1,!1}}function ro(e,t,r){if(Ac())try{const n=new Notification(e,{body:t,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function gh(e,t={}){const r={...fh,...t},n=i.useRef(new Map),a=i.useRef(0),[o,l]=i.useState(null);i.useEffect(()=>{let d=!1;return bh().then(m=>{d||l(m)}),()=>{d=!0}},[]);const c=i.useCallback((d,m,u)=>{const p=Date.now();p-a.current<r.throttleMs||(a.current=p,ro(d,m,u))},[r.throttleMs]);i.useEffect(()=>{var d;if(!(!r.enabled||!Ac())&&yr("browser")&&!xh(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,vt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),p=vt(m.status,{activeModal:m.activeModal}),b=m.name||m.id;if(r.onApproval&&yr("approval")&&p==="waiting_approval"&&u!=="waiting_approval"){const w=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${b} — Approval needed`,w.slice(0,120),`approval-${m.id}`)}r.onComplete&&yr("completion")&&Mn(u)&&p==="idle"&&c(`✅ ${b} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&p==="error"&&u!=="error"&&c(`⚠️ ${b} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,p)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const yh=/^(run|approve|accept|yes|allow|always)/,vh=/^(run|approve|accept|yes|allow|always|proceed|save)/,wh=/^(reject|deny|delete|remove|abort|cancel|no)/;function Do(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function jh(e){const t=Do(e).toLowerCase();return yh.test(t)?"primary":wh.test(t)?"danger":"default"}function kh(e){return vh.test(Do(e).toLowerCase())?"approve":"reject"}function Sh(e){return e.map((t,r)=>({label:Do(t),variant:jh(t),action:kh(t),button:t,buttonIndex:r}))}function Nh(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function Ch(e,t,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,t,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,t,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class Ih{constructor(){Qe(this,"dedupMap",new Map);Qe(this,"DEDUP_WINDOW_MS",5e3);Qe(this,"DEDUP_MAX_SIZE",50);Qe(this,"DEDUP_CLEANUP_AGE_MS",1e4);Qe(this,"toastCallbacks",[]);Qe(this,"statusEventCallbacks",[]);Qe(this,"resolveActionFn",null);Qe(this,"viewRequestRespondFn",null);Qe(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const r of this.toastCallbacks)r(t)}showToast(t,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:t,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(t){const r=Date.now(),n=this.dedupMap.get(t)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,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(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=t.targetSessionId&&this.findOwningSession(t.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(t){for(const r of this.ides)if(r.id===t||r.sessionId===t||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===t))return r;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const r=this.findOwningSession(t.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}handleRawEvent(t,r){var x;const n=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=n||t.daemonId||"",l=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${l}`;if(this.isDuplicate(c))return;for(const h of this.statusEventCallbacks)h(t);const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=lt(m);const p=this.resolveOwningDaemon(t);if(p){const h=Lt(p,{fallbackId:p.id});h&&(u=!m||m==="adhdev-daemon"?h:`${h}/${u}`)}let b="",w="info";if(t.event==="agent:generating_completed"){const h=t.duration?` (${t.duration}s)`:"";b=`✅ ${u} agent task completed${h}`,w="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started")if(t.event==="agent:waiting_approval"){if(b=`⚡ ${u} approval needed`,w="warning",(x=t.modalButtons)!=null&&x.length&&this.resolveActionFn){const h=this.resolveActionRouteTarget(t);if(!h)return;const g=this.resolveActionFn,y=Sh(t.modalButtons).map(C=>({label:C.label,variant:C.variant,onClick:()=>{g(h,"resolve_action",{action:C.action,button:C.button,buttonIndex:C.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),f=Nh(u,t.modalMessage,b),A=Date.now();this.emitToast({id:A,message:f,type:w,timestamp:A,targetKey:n||h,actions:y,duration:15e3}),b=""}}else if(t.event==="monitor:long_generating"){const h=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";b=`⚠️ ${u} agent is taking a long time${h}`,w="warning",yr("browser")&&!document.hasFocus()&&ro(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${h.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const h=t.requesterName||"A team member",g=t.requestId,y=t.orgId;if(b=`👁️ ${h} wants to view your session`,w="warning",g&&y&&this.viewRequestRespondFn){const f=Date.now(),A=Ch(y,g,this.viewRequestRespondFn,(C,v)=>console.error(`[EventManager] ${C} view request failed:`,v));this.emitToast({id:f,message:b,type:w,timestamp:f,actions:A,duration:3e4}),b=""}yr("browser")&&!document.hasFocus()&&ro("👁️ View Request",`${h} wants to view your session`,`view-request-${g}`)}else t.event==="team:view_request_approved"?(b="✅ View request approved",w="success"):t.event==="team:view_request_rejected"&&(b=`❌ ${t.targetName||"Team member"} declined your view request`,w="warning");if(b){const h=Date.now();this.emitToast({id:h,message:b,type:w,timestamp:h,targetKey:n||t.daemonId,duration:5e3})}}}const ot=new Ih,Ui=new Map;function An(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Bs(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Gn(e){return An(e)?An(e.result)?e.result:e:null}function Mh(e){const t=Gn(e);return!t||!An(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Gr(e){const t=Gn(e);return!t||!An(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function nr(e){const t=Gn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Vr(e){const t=Gn(e);return!!t&&t.success===!1}function Ah(e){var t,r;for(const n of e||[]){if(n.type==="toast"&&((t=n.toast)!=null&&t.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 Th(e,t){return e&&Bs(e.currentValue)?e.currentValue:t}function _h(e,t){return Bs(t)?Bs(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Lh(e,t){var o,l;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(Bs(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if(Bs(n))return n;const a=(l=t.defaultValues)==null?void 0:l[e];return Bs(a)?a:void 0}function mn(e,t){return e.options||t[e.id]||[]}const Rh={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 Ph(e,t,r){var n;return((n=Rh[t])==null?void 0:n.has(r.id))===!0}function Eo(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Ph(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function da(e,t){return{value:t}}function Dh(e,t,r){var a;return r?((a=mn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Eh={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function $h({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:l}){const{sendCommand:c}=kt(),d=`${e}:${t||n}`,m=Eh[n]||"#94a3b8",[u,p]=i.useState({}),b=i.useRef({}),w=i.useRef(l);b.current=u,w.current=l;const x=i.useRef(0),h={};for(const M of o||[])M.defaultValue!==void 0&&(h[M.id]=M.defaultValue);const g={...h,...l||{},...Date.now()<x.current?u:{}};i.useEffect(()=>{l&&Date.now()>x.current&&p({})},[l]);const[y,f]=i.useState(Ui.get(d)||{}),[A,C]=i.useState(null),[v,N]=i.useState(null),T=i.useCallback(async(M,F={})=>{const P={...F,...t&&{targetSessionId:t}};return await c(e,M,P)},[e,t,c]),k=i.useCallback(async(M,F={})=>{const P=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await T("invoke_provider_script",{...P,scriptName:M,...F})},[T,n,r,t]),j=i.useCallback((M,F,P)=>{const R=Th(P,F);p(K=>({...K,[M.id]:R})),Ah(P==null?void 0:P.effects)},[]),B=i.useCallback((M,F)=>{p(P=>{const R={...P};return F===void 0?delete R[M.id]:R[M.id]=F,R}),x.current=0},[]);if(!o||o.length===0)return null;const L=Eo(o,{hostIdeType:r,providerType:n});if(L.length===0)return null;const S=async M=>{if(A===M.id){C(null);return}if(mn(M,y).length>0){C(M.id);return}if(M.dynamic&&M.listScript){N(M.id);try{const P=await k(M.listScript,{}),R=Mh(P);if(!R){const te=nr(P);te&&ot.showToast(te,"warning");return}const K=R.options;f(te=>{const ie={...te,[M.id]:K};return Ui.set(d,ie),ie});const V=Lh(M.id,{localOverrideUntil:x.current,localValues:b.current,controlValues:w.current,defaultValues:h});if(_h(V,R.currentValue)){const te=R.currentValue;p(ie=>({...ie,[M.id]:te}))}C(M.id)}catch(P){const R=P instanceof Error?P.message:`Could not load ${M.label}`;ot.showToast(R,"warning")}finally{N(null)}}},D=async(M,F)=>{C(null);const P=(l==null?void 0:l[M.id])??h[M.id];p(R=>({...R,[M.id]:F})),x.current=Date.now()+5e3;try{if(!M.setScript)return;const R=await k(M.setScript,da(M,F)),K=Gr(R);if(K&&!K.ok||Vr(R))throw new Error((K==null?void 0:K.error)||nr(R)||`Could not update ${M.label}`);j(M,F,K)}catch(R){B(M,P);const K=R instanceof Error?R.message:`Could not update ${M.label}`;ot.showToast(K,"warning")}},$=async M=>{const F=mn(M,y).map(ie=>ie.value);if(F.length===0)return;const P=String(g[M.id]||""),K=(F.indexOf(P)+1)%F.length,V=F[K];if(typeof V!="string")return;const te=(l==null?void 0:l[M.id])??h[M.id];p(ie=>({...ie,[M.id]:V})),x.current=Date.now()+5e3;try{if(!M.setScript)return;const ie=await k(M.setScript,da(M,V)),J=Gr(ie);if(J&&!J.ok||Vr(ie))throw new Error((J==null?void 0:J.error)||nr(ie)||`Could not update ${M.label}`);j(M,V,J)}catch(ie){B(M,te);const J=ie instanceof Error?ie.message:`Could not update ${M.label}`;ot.showToast(J,"warning")}},E=async M=>{const P=!g[M.id],R=(l==null?void 0:l[M.id])??h[M.id];p(K=>({...K,[M.id]:P})),x.current=Date.now()+5e3;try{if(!M.setScript)return;const K=await k(M.setScript,da(M,P)),V=Gr(K);if(V&&!V.ok||Vr(K))throw new Error((V==null?void 0:V.error)||nr(K)||`Could not update ${M.label}`);j(M,P,V)}catch(K){B(M,R);const V=K instanceof Error?K.message:`Could not update ${M.label}`;ot.showToast(V,"warning")}},I=async M=>{if(!M.invokeScript)return;if(M.confirmMessage){const P=[M.confirmTitle,M.confirmMessage,M.confirmLabel].filter(K=>typeof K=="string"&&K.trim().length>0);if(!window.confirm(P.join(`
|
|
30
|
+
|
|
31
|
+
`)))return}const F=(l==null?void 0:l[M.id])??h[M.id];try{const P=await k(M.invokeScript),R=Gr(P);if(R&&!R.ok||Vr(P))throw new Error((R==null?void 0:R.error)||nr(P)||`Could not run ${M.label}`);R&&j(M,F??!0,R)}catch(P){B(M,F);const R=P instanceof Error?P.message:`Could not run ${M.label}`;ot.showToast(R,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.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}),L.map(M=>{const F=String(g[M.id]||""),P=Dh(M,y,F),R=A===M.id,K=v===M.id,V=mn(M,y),te="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(M.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${te} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:R?`${m}55`:"var(--border-default)",background:R?`${m}10`:"var(--surface-tertiary)",color:F?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void S(M),title:M.label,children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:K?"Loading…":P||M.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),R&&V.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>C(null)}),s.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:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:M.label}),V.map(ie=>s.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:ie.value===F?`${m}14`:"transparent",color:ie.value===F?"var(--text-primary)":"var(--text-secondary)",borderLeft:ie.value===F?`2px solid ${m}`:"2px solid transparent"},title:ie.description||ie.label,onMouseEnter:J=>{J.currentTarget.style.background=`${m}10`},onMouseLeave:J=>{J.currentTarget.style.background=ie.value===F?`${m}14`:"transparent"},onClick:()=>void D(M,ie.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ie.label}),ie.value===F&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},ie.value))]})]})]},M.id);case"cycle":return s.jsxs("button",{type:"button",className:`${te} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:F?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void $(M),title:`Click to cycle: ${V.map(ie=>ie.label).join(" → ")}`,children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P||M.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},M.id);case"toggle":return s.jsxs("button",{type:"button",className:`${te} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:F?`${m}44`:"var(--border-default)",background:F?`${m}14`:"var(--surface-tertiary)",color:F?m:"var(--text-muted)"},onClick:()=>void E(M),"aria-pressed":!!F,children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),M.label]},M.id);case"action":return s.jsxs("button",{type:"button",className:`${te} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void I(M),children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:M.resultDisplay==="inline"&&F?`${M.label}: ${F}`:M.label})]},M.id);case"display":return s.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:F?"var(--text-primary)":"var(--text-muted)"},children:[M.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:M.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:F?`${M.label}: ${F}`:M.label})]},M.id);default:return null}})]})})}function Bh({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:c,controlValues:d}){const{isVisible:m}=Ro(),u=Eo(c,{hostIdeType:a,providerType:o});return!e||t||u.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx($h,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:u,controlValues:d})})}const ar=5,Tc=10*1024*1024;function Oh({hasDraft:e,isBusy:t=!1}){return!e||t}function Fh(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(n.result),n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}async function Wh(e){if(e.size>Tc)return null;const t=await Fh(e),r=t.indexOf(",");if(r<0)return null;const n=t.slice(r+1);return{mimeType:e.type||"image/png",data:n,name:e.name,previewUrl:t}}function Hh(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const _c=i.memo(function({contextKey:t,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:l,isActive:c=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u,messageInput:p}){const b=i.useRef(null),w=i.useRef(null),[x,h]=i.useState(""),[g,y]=i.useState([]),[f,A]=i.useState(null),[C,v]=i.useState(!1),N=i.useRef(!1),{isVisible:T,toggleVisibility:k}=Ro(),j=Hh(p),B=!!x.trim()||g.length>0;i.useEffect(()=>{h(""),y([]),A(null)},[t]),i.useEffect(()=>{var M;c&&((M=b.current)==null||M.focus({preventScroll:!0}))},[t,c]);const L=i.useCallback(async M=>{A(null);const F=Array.from(M).filter(ie=>ie.type.startsWith("image/"));if(F.length===0)return;const P=ar-g.length;if(P<=0){A(`Max ${ar} images`);return}const R=F.slice(0,P);if(R.filter(ie=>ie.size>Tc).length>0){A("Image too large (max 10 MB)");return}const te=(await Promise.all(R.map(Wh))).filter(ie=>ie!==null);y(ie=>[...ie,...te])},[g.length]),S=i.useCallback(M=>{y(F=>F.filter((P,R)=>R!==M))},[]),D=i.useCallback(async()=>{const M=x.trim();if(!M&&g.length===0||a||N.current)return;N.current=!0;const F=g.length>0?[...g]:void 0;try{await l(M,F)!==!1&&(h(""),y([]),A(null))}finally{N.current=!1}},[x,g,a,l]),$=i.useCallback(M=>{j&&(M.preventDefault(),v(!0))},[j]),E=i.useCallback(()=>v(!1),[]),I=i.useCallback(M=>{j&&(M.preventDefault(),v(!1),M.dataTransfer.files.length>0&&L(M.dataTransfer.files))},[j,L]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",C?"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:$,onDragLeave:E,onDrop:I,children:[g.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:g.map((M,F)=>s.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:[s.jsx("img",{src:M.previewUrl,alt:M.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>S(F),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 ${M.name}`,children:"✕"})]},F))}),s.jsxs("div",{className:"flex gap-2 items-center",title:c?`Send message to ${r}`:void 0,children:[d&&s.jsx("button",{type:"button",onClick:()=>{k(),u==null||u()},"aria-label":T?"Hide controls":"Show controls","aria-pressed":T,title:T?"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:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),j&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:w,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:M=>{M.target.files&&L(M.target.files),M.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var M;return(M=w.current)==null?void 0:M.click()},disabled:g.length>=ar,title:g.length>=ar?`Max ${ar} 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:s.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:s.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"})})})]}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("input",{ref:b,type:"text",placeholder:o||(j&&g.length>0?"Add a message (optional)...":`Send message to ${r}...`),value:x,onChange:M=>h(M.target.value),onPaste:M=>{if(j&&M.clipboardData.files.length>0&&Array.from(M.clipboardData.files).some(R=>R.type.startsWith("image/"))){M.preventDefault(),L(M.clipboardData.files);return}const F=M.clipboardData.getData("text");F&&h(P=>P+F),M.preventDefault()},onKeyDown:M=>{if(M.key==="Enter"){if(M.nativeEvent.isComposing){M.preventDefault();return}M.preventDefault(),D()}},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))"}})}),s.jsx("button",{onClick:()=>{D()},disabled:Oh({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:s.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:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(f||j&&C)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${f?"text-red-400":"text-[var(--accent-primary)]"}`,children:f||"Drop image here"}),o&&!f&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})}),at=e=>e.transport==="pty",Js=(e,t)=>at(e)?e.mode||"terminal":"chat",Lc=(e,t)=>at(e)&&Js(e)==="terminal",st=e=>e.transport==="acp",Kh=180;function is(e){return e.streamSource!=="agent-stream"}function As(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Rc(e){return e.machineName||""}function Lr(e){return As(e)}function Yt(e){return e.agentType||""}function Tn(e){return e.hostIdeType||""}function $o(e){return e.displayPrimary||e.agentName||"Agent"}function Pc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Uh(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Dc(e){const t=Uh(e),r=Ws(t==null?void 0:t.content),n=Ws(e.lastMessagePreview);return r||n||""}function zh(e,t=Kh){const r=Ws(e);if(!r||t<=0)return"";const n=Array.from(r);return n.length<=t?r:`${n.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function Gh(e){return zh(Dc(e)||e.displaySecondary||"")}function Ec(e){return[e.displaySecondary,Rc(e)].filter(Boolean)}function Ks(e){return e.agentName||lt(Yt(e))}function Vh(e){var t,r;if(!is(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return lt(Tn(e)||Yt(e))}function $c(e){return is(e)?e.sessionId:e.nativeSessionId}function zi(e){return is(e)?"native":e.tabKey}function qh(e){return e.sessionId}function Yh(e,t){if(t)return is(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Xh(e,t){const r=Yt(e),n=is(e),a=at(e)||st(e),o=n?a?Ks(e)||(t==null?void 0:t.cliName)||lt(Tn(e)||r):t!=null&&t.type?lt(t.type):lt(Tn(e)||r):Ks(e);return{isNativeConversation:n,isCli:at(e),isAcp:st(e),isCliTerminal:Lc(e),providerType:r,displayLabel:o,targetEntry:Yh(e,t)}}function fs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:at(e)||st(e)?{agentType:Yt(e)}:e.streamSource==="agent-stream"?{agentType:Yt(e)}:t}function Us(e){return e?Lr(e):""}function or(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Bo(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Jh(e){const t=e instanceof Error?e.message:String(e||""),r=t.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.":t||"Unable to send message right now."}function Bc(){return"select_session"}function Qh(){return"open_panel"}function Zh({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function ef(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Gi(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function _n(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Oo(e){return e instanceof Error?e.message:String(e||"")}function Vi(e){const t=Oo(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function qi(e,t){const r=Oo(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function tf(e,t,r){const n=fs(r);if(!t||t.length===0)return{message:e,...n};const a=t.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 Vn({sendDaemonCommand:e,activeConv:t,setActionLogs:r,isStandalone:n}){const[a,o]=i.useState(!1),[l,c]=i.useState(!1),[d,m]=i.useState(null),u=i.useRef(!1),p=i.useRef(null);i.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const b=i.useCallback(async(g,y)=>{if(!t||u.current)return!1;const f=g.trim(),A=Bo(t);if(Zh({hasMessage:!!f,blockedMessage:A,sendInFlight:u.current}))return A&&m(A),!1;const C=Date.now(),v={tabKey:t.tabKey,message:f,timestamp:C};if(ef(p.current,v))return m(null),!0;u.current=!0,c(!0),m(null),p.current=v;try{const N=Us(t);if(!N)return p.current=Gi(p.current,v),m("Unable to send message right now."),!1;const T=await e(N,"send_chat",tf(f,y,t)),k=_n(T);if(k!=null&&k.deduplicated)return m(null),!0;if((k==null?void 0:k.sent)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");if((k==null?void 0:k.success)===!1)throw new Error((k==null?void 0:k.error)||"Send failed");return m(null),!0}catch(N){const T=Oo(N);return T.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",T):console.warn("Send blocked/failed",N),p.current=Gi(p.current,v),m(Jh(N)),!1}finally{u.current=!1,c(!1)}},[t,e]),w=i.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(g){console.error("Relaunch failed",g)}},[t,e]),x=i.useCallback(async g=>{if(t)try{const f=(t.modalButtons||[]).indexOf(g),A=g.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),C=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A),v=Us(t);if(!v)return;const N=await e(v,"resolve_action",{button:g,action:C?"approve":"reject",...f>=0&&{buttonIndex:f},...fs(t)}),T=_n(N);T.success||r(k=>[...k,{routeId:t.tabKey,text:qi(g,T==null?void 0:T.error),timestamp:Date.now()}])}catch(y){Vi(y)||console.error("[ModalButton] Error:",y),r(f=>[...f,{routeId:t.tabKey,text:Vi(y)?qi(g,y):`❌ **${g}** error`,timestamp:Date.now()}])}},[t,e,r]),h=i.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,Qh(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(g){console.error("Focus agent failed",g)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:l,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:b,handleRelaunch:w,handleModalButton:x,handleFocusAgent:h}}const sf=10,rf=8e3,nf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function af(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 no(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(nf.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=af(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=>no(a,t,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,no(a,n,r+1)]))}function ir(e,t){return Array.isArray(e)?e.slice(-t):[]}function of(e,t=Date.now()){const r=e&&t-e.firstAt<=rf,n=r?e.count+1:1;return n>=sf?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Oc(e){var n,a;const{activeConv:t}=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:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((n=e.chatTailState.liveMessages)==null?void 0:n.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((a=e.chatTailState.historyMessages)==null?void 0:a.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:ir(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:ir(t.messages,10),visibleMessagesTail:ir(e.visibleMessages,5),historyMessagesTail:ir(e.chatTailState.historyMessages,5),actionLogsTail:ir(e.actionLogs.filter(o=>o.routeId===t.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 no(r)}function Fc(e,t={}){const r=e&&typeof e=="object"?e:{},n=t.locatorCopyStatus??(t.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 Wc(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.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 Hc(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&r.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&r.push("","warnings:",...t.warnings.map(n=>`- ${String(n)}`)),r.join(`
|
|
32
|
+
`)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
|
|
33
|
+
|
|
34
|
+
\`\`\`json
|
|
35
|
+
${JSON.stringify(t.bundle,null,2)}
|
|
36
|
+
\`\`\``:`# ADHDev Chat Debug Bundle
|
|
37
|
+
|
|
38
|
+
\`\`\`json
|
|
39
|
+
${JSON.stringify(t,null,2)}
|
|
40
|
+
\`\`\``}function ua(e,t){return`${e}:${t}`}function lf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function lr(e,t){lf()&&console.debug(`[subscription-manager] ${e}`,t)}class cf{constructor(){Qe(this,"active",new Map);Qe(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u;const l=ua(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 p={daemonId:r,request:n,handlers:new Set([a])};this.active.set(l,p),lr("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=t.sendData)==null?void 0:u.call(t,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(l,t,o.retryIntervalMs)}const m=()=>{var w;this.clearRetry(l);const p=this.active.get(l);if(!p||(p.handlers.delete(a),p.handlers.size>0))return;this.active.delete(l);const b={type:"unsubscribe",topic:n.topic,key:n.key};lr("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(w=t.sendData)==null||w.call(t,r,b)};return m.initialSendAccepted=d,m}publish(t){const r=ua(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Fs.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),n.handlers.forEach(a=>{a(t),Fs.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,r,n){const a=ua(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;lr("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=t.sendData)==null||r.call(t,n.daemonId,n.request)}resubscribeForDaemon(t,r){var a;const n=Array.from(this.active.values()).filter(o=>o.daemonId===t);lr("resubscribe_daemon",{daemonId:t,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(t,r,n){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var c;this.retryTimers.delete(t);const o=this.active.get(t);if(!o)return;const l=((c=r.sendData)==null?void 0:c.call(r,o.daemonId,o.request))??!1;lr("subscribe_retry",{id:t,accepted:l,topic:o.request.topic,key:o.request.key}),l||this.scheduleRetry(t,r,n)},n);this.retryTimers.set(t,a)}clearRetry(t){const r=this.retryTimers.get(t);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(t))}}const Qt=new cf;function df(e,t){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===t&&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 uf(e){const t=[],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 t.push(n);return{topLevel:t,childrenByParent:r}}function ma(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function mf(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function pf(e){mf()&&console.debug("[dashboard-conversations] statusPayloadToEntries",e.map(t=>({id:t.id,daemonId:t.daemonId,sessionId:t.sessionId,instanceId:t.instanceId,providerSessionId:t.providerSessionId,transport:t.transport,type:t.type})))}function Ln(e,t){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:l}=t,c=l||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=uf(d),p=df(o,n),b=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,w=m.filter(g=>g.kind==="workspace"&&g.transport==="cdp-page"),x=m.filter(g=>g.kind==="agent"&&g.transport==="pty"),h=m.filter(g=>g.kind==="agent"&&g.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...b&&{machine:b,platform:b.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:w.some(g=>!!g.cdpConnected)});for(const g of w){const y=p.get(g.id),f=fr(g,y),A=(u.get(g.id)||[]).map(C=>fr(C,p.get(C.id)));r.push({id:`${n}:ide:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,status:f.cdpConnected?"online":"detected",daemonId:n,instanceId:ma(n,g.id),workspace:f.workspace,terminals:0,childSessions:A,agents:A.map(C=>({id:C.id,name:C.providerName||C.providerType,type:C.providerType,status:C.status})),activeChat:f.activeChat,chats:[],cdpConnected:f.cdpConnected,...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,completionMarker:f.completionMarker,seenCompletionMarker:f.seenCompletionMarker,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},...f.settings!==void 0&&{settings:f.settings},...f.messageInput!==void 0&&{messageInput:f.messageInput},timestamp:c})}for(const g of x){const y=p.get(g.id),f=fr(g,y);r.push({id:`${n}:cli:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:ma(n,g.id),cliName:f.providerName||f.providerType,mode:f.mode||(y==null?void 0:y.mode)||"terminal",workspace:f.workspace||"",activeChat:f.activeChat,...f.resume!==void 0&&{resume:f.resume},...f.runtimeKey!==void 0&&{runtimeKey:f.runtimeKey},...f.runtimeDisplayName!==void 0&&{runtimeDisplayName:f.runtimeDisplayName},...f.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:f.runtimeWorkspaceLabel},...f.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:f.runtimeWriteOwner},...f.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:f.runtimeAttachedClients},...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,completionMarker:f.completionMarker,seenCompletionMarker:f.seenCompletionMarker,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},...f.settings!==void 0&&{settings:f.settings},...f.messageInput!==void 0&&{messageInput:f.messageInput},timestamp:c,_isCli:!0})}for(const g of h){const y=p.get(g.id),f=fr(g,y);r.push({id:`${n}:acp:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:f.parentId,sessionKind:f.kind,transport:f.transport,sessionCapabilities:f.capabilities,type:f.providerType,agentType:f.providerType,status:f.status||"running",daemonId:n,instanceId:ma(n,g.id),cliName:f.providerName||f.providerType,mode:"chat",workspace:f.workspace||"",activeChat:f.activeChat,...f.runtimeKey!==void 0&&{runtimeKey:f.runtimeKey},...f.runtimeDisplayName!==void 0&&{runtimeDisplayName:f.runtimeDisplayName},...f.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:f.runtimeWorkspaceLabel},...f.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:f.runtimeWriteOwner},...f.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:f.runtimeAttachedClients},...f.lastMessagePreview!==void 0&&{lastMessagePreview:f.lastMessagePreview},...f.lastMessageRole!==void 0&&{lastMessageRole:f.lastMessageRole},...f.lastMessageAt!==void 0&&{lastMessageAt:f.lastMessageAt},...f.lastMessageHash!==void 0&&{lastMessageHash:f.lastMessageHash},lastUpdated:f.lastUpdated,unread:f.unread,lastSeenAt:f.lastSeenAt,inboxBucket:f.inboxBucket,completionMarker:f.completionMarker,seenCompletionMarker:f.seenCompletionMarker,surfaceHidden:f.surfaceHidden,...f.controlValues!==void 0&&{controlValues:f.controlValues},...f.providerControls!==void 0&&{providerControls:f.providerControls},...f.summaryMetadata!==void 0&&{summaryMetadata:f.summaryMetadata},...f.settings!==void 0&&{settings:f.settings},...f.messageInput!==void 0&&{messageInput:f.messageInput},timestamp:c,_isAcp:!0})}return pf(r),r}const hf=15e3,ff=15e3,xf=6e4,bf=1200,Yi=12,gf=8e3,yf=4e3,pa=new Map,ha=new Map,qr=new Set,vr=new Map;function vf(e){if(!e||typeof e!="object")return null;const t=e,r=t.status;if(r&&typeof r=="object")return r;const n=t.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return t}function Xi(e,t){const r=vr.get(e);!r||r.size===0||(vr.delete(e),r.forEach(n=>n(t)))}function wf(e,t){return new Promise(r=>{const n=vr.get(e)||new Set;vr.set(e,n);const a=l=>{clearTimeout(o),n.delete(a),n.size===0&&vr.delete(e),r(l)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Rr(){const{sendCommand:e,sendData:t}=kt(),{injectEntries:r,getIdes:n}=Cr();return i.useCallback(async(a,o)=>{if(!a)return;const l=(o==null?void 0:o.minFreshMs)??xf,c=ha.get(a)||0;if(!(o!=null&&o.force)&&qr.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<l)return;const d=pa.get(a);if(d)return d;const m=(async()=>{if(t&&!qr.has(a)){const h=Qt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},g=>{const y=n(),f=y.find(C=>C.id===a),A=Ln(g.status,{daemonId:a,existingDaemon:f,existingEntries:y,timestamp:g.timestamp});A.length>0&&r(A),ha.set(a,Date.now()),Xi(a,!0)});if(h.initialSendAccepted?qr.add(a):qr.delete(a),!(o!=null&&o.force)&&h.initialSendAccepted&&await wf(a,bf))return}const u=await e(a,"get_status_metadata"),p=vf(u);if(!p)return;const b=n(),w=b.find(h=>h.id===a),x=Ln(p,{daemonId:a,existingDaemon:w,existingEntries:b,timestamp:p.timestamp||Date.now()});x.length>0&&r(x,{authoritativeDaemonIds:[a]}),ha.set(a,Date.now()),Xi(a,!0)})().finally(()=>{pa.delete(a)});return pa.set(a,m),m},[n,r,e,t])}function jf(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const kf=60,Sf=50;function Kc(e={}){return e.isCliLike?Sf:kf}function Nf(e={}){return Kc(e)}function Mt(e){return(typeof e=="string"?e.trim():"")||void 0}function Jt(e,t){const r=Mt(t);return r?`${e}:${r}`:void 0}function as(e,t,r){const n=Jt(t,r),a=Mt(r);n&&e.push(n),a&&e.push(a)}function Ds(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Uc(e){return Mt(e.providerSessionId)||Mt(e.sessionId)||Mt(e.tabKey)||Mt(e.routeId)}function Fo(e){return Ds([Mt(e.providerSessionId),Mt(e.sessionId)])}function Os(e){const t=[];return as(t,"provider",e.providerSessionId),as(t,"session",e.sessionId),as(t,"tab",e.tabKey),as(t,"route",e.routeId),Ds(t)}function Cf(e){const t=[];return Mt(e.providerSessionId)?(as(t,"provider",e.providerSessionId),Ds(t)):Mt(e.sessionId)?(as(t,"session",e.sessionId),Ds(t)):Mt(e.tabKey)?(as(t,"tab",e.tabKey),Ds(t)):Mt(e.routeId)?(as(t,"route",e.routeId),Ds(t)):[]}function Wo(e){return Jt("provider",e.providerSessionId)||Jt("session",e.sessionId)||Jt("tab",e.tabKey)||Jt("route",e.routeId)||"unknown:"}function Pr(e){return Fo(e)[0]}function If(e){const t=Mt(e.providerSessionId),r=Mt(e.sessionId),n=Mt(e.tabKey),a=Mt(e.routeId),o=[Jt("provider",t),Jt("session",r),Jt("tab",n),Jt("route",a)].filter(d=>typeof d=="string"),l=Os({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=Wo({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:Uc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:Pr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:l}}function ao(e,t){const r=If(e);return Cf(t).some(n=>r.lookupKeys.includes(n))}const Dr=60,Mf=1e3,Ho=12e4,Af=new Set(["generating","waiting_approval","starting","streaming","working"]),Ji=new Map;function zc(e,t){return`${e}::${t}`}function oo(e=Dr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Tf([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Tf(e,t=Dr){return{tailLimit:t}}function Qi(e,t){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 _f{constructor(t){Qe(this,"manager");Qe(this,"sendData");Qe(this,"daemonId");Qe(this,"sessionId");Qe(this,"historySessionId");Qe(this,"subscriptionKey");Qe(this,"fallbackRecentCount");Qe(this,"snapshot");Qe(this,"transportSubscription",null);Qe(this,"listeners",new Set);Qe(this,"retainCount",0);Qe(this,"loadHistoryPromise",null);Qe(this,"pendingDisconnectTimer",null);this.manager=t.manager||Qt,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.snapshot=oo(Math.max(0,t.tailLimit??Dr))}updateOptions(t){if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const r=Math.max(0,t.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}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(t){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 t({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(),t=>{this.handleUpdate(t)},{retryIntervalMs:Mf}))}disconnect(){var t;(t=this.transportSubscription)==null||t.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(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const r=Array.isArray(t.messages)?t.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};Qi(this.snapshot.liveMessages)===Qi(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:n},this.emit())}}function Gc(e){const t=zc(e.daemonId,e.sessionId),r=Ji.get(t);if(r)return r.updateOptions(e),r;const n=new _f(e);return Ji.set(t,n),n}function Lf(e,t){return{...e,loadHistoryPage:t}}function Rf(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Pf(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(Af.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??Ho)),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 Df(e=Ho){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Ef(e,t={}){const r=new Set,n=[];for(const a of e){if(!Pf(a,t))continue;const o=Lr(a),l=a.sessionId||"";if(!o||!l)continue;const c=zc(o,l);if(r.has(c))continue;r.add(c);const d=Pr(a);n.push({daemonId:o,sessionId:l,historySessionId:d||l,subscriptionKey:`daemon:${o}:session:${l}`})}return n.sort(Rf),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function $f(e,t){const{sendData:r,sendCommand:n}=kt(),a=(t==null?void 0:t.enabled)!==!1,o=Lr(e),l=e.sessionId||"",c=Pr(e)||l,d=`daemon:${o}:session:${l}`,m=Math.max(0,(t==null?void 0:t.tailLimit)??Dr),u=i.useMemo(()=>!a||!o||!l?null:Gc({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]),[p,b]=i.useState(()=>(u==null?void 0:u.getSnapshot())||oo(m));i.useEffect(()=>{if(!u){b(oo(m));return}u.retain(),b(u.getSnapshot());const x=u.subscribe(h=>{b(h)});return()=>{x(),u.release()}},[u,m]);const w=i.useCallback(async()=>{!u||!o||!l||await u.loadHistoryPage(async({offset:x,excludeRecentCount:h})=>{const g=e.agentType,y=await n(o,"chat_history",{agentType:g,offset:x,limit:30,targetSessionId:l,historySessionId:c,excludeRecentCount:h}),f=y&&typeof y=="object"&&"result"in y?y.result||{}:y||{};return{messages:Array.isArray(f.messages)?f.messages:[],hasMore:f.hasMore===!0}})},[e.agentType,u,o,c,n,l]);return i.useMemo(()=>Lf(p,w),[w,p])}function Bf(e,t){const{sendData:r}=kt(),n=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??Dr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Ho)),l=Df(o),[c,d]=i.useState(0);i.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(p=>p+1)},l);return()=>{clearInterval(u)}},[e.length,n,l]);const m=i.useMemo(()=>Ef(e,{recentActivityMs:o}),[e,o,c]);i.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(p=>Gc({...p,sendData:r,tailLimit:a}));return u.forEach(p=>{p.retain()}),()=>{u.forEach(p=>p.release())}},[m.signature,n,r,a])}function Of(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Zi(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function Ff(e,t){if(e.length===0)return[];if(t.some(Zi))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||!Zi(o))continue;const l=String(o.role||"").toLowerCase();n.has(l)||(n.add(l),r.unshift(o))}return r}function Wf(e){const{historyMessages:t,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=Ff(o,l),d=c.length>0?[...c,...l]:l;return t.length===0?d:[...t,...d]}function Hf(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Kf(e){return Hf(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Uf(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function zf(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Gf(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Vc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function qc(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function Vf(e){return Vc(e)?!1:e.inboxBucket==="task_complete"&&qc(e).length>0}function el(e){return e.branch||"detached HEAD"}function qf(e){if(e.error)return`${el(e)} · Git error: ${e.error}`;const t=[el(e)];return e.changedFiles>0?t.push(Uf(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function Yf(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${qf(t)}`}function Xf(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Jf(e,t={}){if(t.enabled===!1)return[];if(!Gf(e))return[];const r=Vc(e)?"working":Vf(e)?"complete":null;if(!r)return[];const n=r==="complete"?qc(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${zf(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Yf(r,e.git),timestamp:Xf(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 Qf=60;function io({activeConv:e,ideEntry:t,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:l,actionLogs:c,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:p=!0}){var Ne,Q,he,oe,ue,le,de;const b=i.useRef(new Map),w=i.useRef(void 0),x=Rr(),{sendCommand:h}=kt(),{isVisible:g}=Ro();_r("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const y=St.useMemo(()=>Xs(e),[e.status,e.connectionState]),f=i.useMemo(()=>Xh(e,t),[e,t]),A=i.useMemo(()=>{var Z;return Eo((Z=f.targetEntry)==null?void 0:Z.providerControls,{hostIdeType:e.hostIdeType,providerType:f.providerType})},[e.hostIdeType,f.providerType,(Ne=f.targetEntry)==null?void 0:Ne.providerControls]),C=Kc({isCliLike:f.isCli||f.isAcp}),v=Nf({isCliLike:f.isCli||f.isAcp}),N=$f(e,{enabled:p&&!!e.sessionId,tailLimit:v}),[T,k]=i.useState(C),[j,B]=i.useState(()=>Pi()),L=e.tabKey,S=N.historyMessages,D=N.hasMoreHistory,$=N.historyError,E=Of(e,N),I=fc(E).length;i.useEffect(()=>{k(C)},[C,L]);const M=Math.max(0,E.length-T),F=$o(e),P=Lr(e),R=Kf(e),K=Bo(e),V=a||K,te=!!K,[ie,J]=i.useState(!1);i.useEffect(()=>{const Z=f.targetEntry;P&&(!Z||Z.providerControls===void 0||Z.controlValues===void 0)&&x(P,{minFreshMs:3e4}).catch(()=>{})},[P,f.isAcp,(Q=f.targetEntry)==null?void 0:Q.providerControls,(he=f.targetEntry)==null?void 0:he.controlValues,x]);const me=i.useCallback(async()=>{if(!ie){if(E.length>T){k(Z=>Math.min(E.length,Z+Qf));return}J(!0);try{await N.loadHistoryPage()}finally{J(!1)}}},[N,ie,E.length,T]),{allMessages:je,receivedAtMap:ke}=i.useMemo(()=>{const Z=Wf({historyMessages:S,liveMessages:E,visibleLiveCount:T}),ve=Jf(e),ce=ve.length>0?[...Z,...ve]:Z,pe={};return ce.forEach((ae,Ie)=>{const Ce=`${e.tabKey}:${Cn(ae,Ie)}`;let _e=jf(ae)||b.current.get(Ce)||0;_e||(_e=Date.now(),b.current.set(Ce,_e)),pe[Cn(ae,Ie)]=_e}),{allMessages:ce,receivedAtMap:pe}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,M,S,E,T]),q=i.useMemo(()=>c.filter(Z=>Z.routeId===e.tabKey).sort((Z,ve)=>Z.timestamp-ve.timestamp),[c,e.tabKey]),ge=i.useCallback(async()=>{var Ie,Ce;if(!P)return;const Z=Oc({activeConv:e,visibleMessages:je,actionLogs:c,controls:(Ie=f.targetEntry)==null?void 0:Ie.providerControls,controlValues:(Ce=f.targetEntry)==null?void 0:Ce.controlValues,visibleBarControlCount:A.length,chatTailState:{liveMessages:N.liveMessages,hasLiveSnapshot:N.hasLiveSnapshot,hasMoreHistory:D,historyError:$,historyMessages:S},ui:{controlsVisible:g,visibleLiveCount:T,activityVisible:j,activityCount:I,hiddenLiveCount:M,isInputActive:u,isVisible:p}}),ve=await h(P,"get_chat_debug_bundle",{agentType:f.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:Z}),ce=_n(ve),pe=Hc(ce),ae=await Wc(pe);ae==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ot.showToast(Fc(ce,{locatorCopyStatus:ae}),ae==="failed"?"warning":"success")},[e,c,I,je,g,N.hasLiveSnapshot,N.liveMessages,f.providerType,(oe=f.targetEntry)==null?void 0:oe.controlValues,(ue=f.targetEntry)==null?void 0:ue.providerControls,P,D,M,S,u,p,$,h,j,A.length,T]),fe=i.useCallback(()=>{B(Z=>{const ve=!Z;return vp(ve),ve})},[]);i.useEffect(()=>{const Z=ve=>{ve.key===Ao&&B(Pi())};return window.addEventListener("storage",Z),()=>window.removeEventListener("storage",Z)},[]);const we=i.useCallback(()=>{const Z=of(w.current);w.current=Z.state,Z.shouldCollect&&ge().catch(ve=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ve),ot.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[ge]),xe=i.useMemo(()=>{if(E.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.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:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((y.isGenerating||e.status==="streaming")&&J(!1),e.status==="not_monitored"&&R)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Hs,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),s.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Switching...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ss,{size:14})," Open ",F," Panel"]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&R)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(uc,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),s.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Opening...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ss,{size:14})," Open ",F," Panel"]})}),s.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"&&!ie)return!D&&S.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,R,o,D,S.length,l,ie,E.length,F,y.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsxs("button",{type:"button",className:`chat-activity-toggle ${j?"chat-activity-toggle-active":""}`,onClick:fe,"aria-pressed":j,title:"Show tool, terminal, and runtime activity rows",children:[s.jsx("span",{className:"chat-activity-toggle-dot"}),"Activity",I>0&&s.jsx("span",{className:"chat-activity-toggle-count",children:I})]})}),s.jsx(Dp,{messages:je,actionLogs:q,agentName:Ks(e)||F||"Agent",userName:d,isCliMode:f.isCli||f.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:ke,lastMessageHash:e.lastMessageHash,showActivityMessages:j,onLoadMore:me,isLoadingMore:ie,hasMoreHistory:D,hiddenLiveCount:M,loadError:$??void 0,emptyState:xe,scrollToBottomRequestNonce:m,isVisible:p}),s.jsx(Bh,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:f.providerType,displayLabel:f.displayLabel,controls:(le=f.targetEntry)==null?void 0:le.providerControls,controlValues:(de=f.targetEntry)==null?void 0:de.controlValues,isActive:u,isCliTerminal:f.isCliTerminal}),!f.isCliTerminal&&s.jsx(_c,{contextKey:e.tabKey,panelLabel:F,isSending:n,isBusy:te,statusMessage:V,onSend:r,isActive:u,showControlsToggle:A.length>0,onControlsToggle:we,messageInput:e.messageInput})]})}let Yc=cs;function Xc(){return Yc()}class Zf{constructor(){Qe(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,r){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(r),()=>{var n;(n=this.listeners.get(t))==null||n.delete(r)}}emit(t,...r){var n;(n=this.listeners.get(t))==null||n.forEach(a=>a(...r))}}let Jc=new Zf;class ex{sendPtyInput(t,r,n){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,r){return!1}get(t){}onScreenshot(t,r){return()=>{}}onRuntimeEvent(t,r,n){return()=>{}}requestRuntimeSnapshot(t,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let ht=new ex;function tx(e){e.dashboardWS&&(Jc=e.dashboardWS),e.connectionManager&&(ht=e.connectionManager),e.useDaemonsHook&&(Yc=e.useDaemonsHook)}const sx=.5,rx=1.25;function ut(e){return $o(e)}function Cs(e){return Ec(e).join(" · ")}function Qc(e){const t=Dc(e);return t||(e.title?e.title:Cs(e)||"No messages yet")}function Zc(e,t){const{isReconnecting:r,isConnecting:n}=Xs(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function nx(e,t){const r=["Chat",...Ec(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function xs(e){return Zc(e)||Cs(e)}function ax(e){return`${ut(e)} · ${Qc(e)}`}function ox(e){const t=Tn(e),r=t?lt(t):Ks(e);return`${ut(e)} — ${r||"Agent"}`}function ix(e){return Ks(e)||"CLI"}function ed(e){return Pc(e)}function td(e){return e?`Remote · ${ut(e)||e.workspaceName||"Session"}`:"Remote"}function lx({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:l=!0,isInputActive:c=!0}){var re;cs();const{sendPtyInput:d}=kt(),[m,u]=i.useState(!1),p=i.useRef(!1);p.current=m;const[b,w]=i.useState("Runtime terminal unavailable"),[x,h]=i.useState(!1),[g,y]=i.useState(null),[f,A]=i.useState(!1),[C,v]=i.useState(!1),[N,T]=i.useState(1),[k,j]=i.useState(!1),[B,L]=i.useState({width:0,height:0}),[S,D]=i.useState({width:0,height:0}),[$,E]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[I,M]=i.useState(null),F=i.useRef(null),P=i.useRef(null),R=i.useRef(!1),K=i.useRef(!1),V=i.useRef(l),te=i.useRef(0),ie=i.useRef(!1),J=i.useRef(""),me=i.useRef(null),je=i.useRef(!1),ke=i.useRef(!1),q=i.useRef(null),ge=i.useRef(null),fe=i.useRef(null),we=32*1024,xe=()=>{var W,G,se,ne;return((G=(W=F.current)==null?void 0:W.ownerDocument)==null?void 0:G.defaultView)||((ne=(se=P.current)==null?void 0:se.ownerDocument)==null?void 0:ne.defaultView)||window},Ne=W=>{const G=xe();return{ownerWindow:G,frameId:G.requestAnimationFrame(W)}},Q=()=>{const W=q.current;if(W){try{W.ownerWindow.cancelAnimationFrame(W.frameId)}catch{}q.current=null}},he=()=>{const W=ge.current;if(W){try{W.ownerWindow.clearTimeout(W.timeoutId)}catch{}ge.current=null}},oe=()=>{const W=fe.current;if(W){try{W.ownerWindow.clearTimeout(W.timeoutId)}catch{}fe.current=null}},ue=()=>{l&&q.current===null&&(q.current=Ne(()=>{tt()}))},le=e.tabKey,de=e.sessionId||"",Z=e.daemonId||((re=e.routeId)==null?void 0:re.split(":")[0])||e.routeId||"",ve=Bo(e),ce=m?o||ve:b,pe=sx,ae=rx,Ie=.05,Ce=()=>{const W=S.width,G=S.height;if(!Number.isFinite(B.width)||B.width<=0||!Number.isFinite(B.height)||B.height<=0||!Number.isFinite(W)||W<=0||!Number.isFinite(G)||G<=0)return 1;const se=B.width/W,ne=B.height/G;return Number(Math.min(ae,Math.max(pe,Math.min(se,ne))).toFixed(2))},_e=Ce(),H=R.current&&N>_e,Me=Number.isFinite(S.width)&&S.width>0?Math.max(B.width,Math.round(S.width*N)):B.width,Ae=Number.isFinite(S.height)&&S.height>0?Math.max(B.height,Math.round(S.height*N)):B.height,He=()=>{Ne(()=>{const W=P.current;W&&(W.scrollLeft=0,W.scrollTop=W.scrollHeight-W.clientHeight)})},Ge=()=>{var W,G;te.current=0,ie.current=!1,J.current="",me.current=null,je.current=!1,ke.current=!1,R.current||(K.current=!1,T(1)),q.current!==null&&Q(),u(!1),w("Runtime terminal unavailable"),oe(),he(),y(null),M(null),j(!1),h(!1),A(!1),v(!1),(G=(W=r.current)==null?void 0:W.reset)==null||G.call(W)},Xe=()=>{var W,G;te.current=0,ie.current=!1,J.current="",me.current=null,je.current=!1,ke.current=!1,q.current!==null&&Q(),u(!0),w(""),oe(),he(),y(null),M(null),j(!1),h(!1),A(!1),v(!1),(G=(W=r.current)==null?void 0:W.reset)==null||G.call(W)},Ye=()=>{ke.current&&(ke.current=!1,Ne(()=>{var W,G;(G=(W=r.current)==null?void 0:W.scrollToTop)==null||G.call(W)}))},tt=()=>{if(q.current=null,!l)return;const W=J.current;if(!W)return;const G=W.slice(0,we);J.current=W.slice(G.length);const se=r.current;if(!se){J.current=G+J.current,ue();return}se.write(G,()=>{if(J.current.length>0){ue();return}Ye()})},ct=W=>{W&&(J.current+=W,ue())},mt=(W,G=0,se,ne,Se={})=>{var Oe,Re,Fe,Ue;const Ee=!!Se.force;!Ee&&G>0&&te.current>=G||!Ee&&G===0&&ie.current||(te.current=G,G>0&&A(!0),u(!0),w(""),typeof se=="number"&&typeof ne=="number"&&se>0&&ne>0&&((Re=(Oe=r.current)==null?void 0:Oe.resize)==null||Re.call(Oe,se,ne)),J.current="",(Ue=(Fe=r.current)==null?void 0:Fe.reset)==null||Ue.call(Fe),W?ct(W):Ye())};i.useEffect(()=>{Ge()},[de]),i.useEffect(()=>{var G;if(!de)return;const W=((G=ht.onRuntimeEvent)==null?void 0:G.call(ht,de,se=>{if(!(!se||se.sessionId!==de)){if(se.type==="runtime_snapshot"){if(!l){me.current={text:se.text||"",seq:se.seq||0,cols:se.cols,rows:se.rows,force:!!se.force};return}mt(se.text||"",se.seq||0,se.cols,se.rows,{force:!!se.force});return}if(se.type==="session_output"){ie.current=!0,typeof se.seq=="number"&&(te.current=Math.max(te.current,se.seq),se.seq>0&&A(!0)),p.current||u(!0),p.current||w(""),typeof se.data=="string"&&ct(se.data);return}if(se.type==="session_cleared"){if(!l){je.current=!0,J.current="",me.current=null;return}Xe();return}if(se.type==="session_io_error"){const ne=typeof se.error=="string"&&se.error?se.error:typeof se.reason=="string"&&se.reason?se.reason:"unknown error";u(!1),w(`Runtime input failed: ${ne}`);return}}},Z))||(()=>{});return()=>{W()}},[Z,de,r,l]);const pt=async(W={})=>{var G;if(!Z||!de)return{success:!1,error:"daemonId and sessionId are required"};W.preserveStatus||w(W.loadingMessage||"Loading runtime terminal...");try{const se=await((G=ht.requestRuntimeSnapshot)==null?void 0:G.call(ht,Z,de,{sinceSeq:W.sinceSeq,force:W.force}));return se&&se.success===!1?(W.preserveStatus||(u(!1),w(`Runtime terminal unavailable: ${se.error}`)),se):se||{success:!0}}catch(se){const ne=(se==null?void 0:se.message)||String(se);return W.preserveStatus||(u(!1),w(`Runtime terminal unavailable: ${ne}`)),{success:!1,error:ne}}},O=async W=>{var Ee,Oe;const G=((Ee=F.current)==null?void 0:Ee.ownerDocument)||document,se=G.defaultView||window,ne=(Oe=se.navigator)==null?void 0:Oe.clipboard;if(ne!=null&&ne.writeText&&se.isSecureContext)try{return await ne.writeText(W),!0}catch{}let Se=null;try{return Se=G.createElement("textarea"),Se.value=W,Se.setAttribute("readonly","true"),Se.style.position="fixed",Se.style.left="-9999px",Se.style.top="0",G.body.appendChild(Se),Se.focus(),Se.select(),G.execCommand("copy")}catch{return!1}finally{Se==null||Se.remove()}},be=W=>{he(),M(W);const G=xe();ge.current={ownerWindow:G,timeoutId:G.setTimeout(()=>{ge.current=null,M(se=>se===W?null:se)},2200)}},Te=W=>{oe(),y(W);const G=xe();fe.current={ownerWindow:G,timeoutId:G.setTimeout(()=>{fe.current=null,y(se=>se===W?null:se)},2200)}},Be=async()=>{var Se,Ee,Oe,Re;const W=((Ee=(Se=r.current)==null?void 0:Se.getSelection)==null?void 0:Ee.call(Se))||"",G=((Re=(Oe=r.current)==null?void 0:Oe.getVisibleText)==null?void 0:Re.call(Oe))||"",se=W.trimEnd()||G.trimEnd();if(!se){be("Nothing to copy");return}if(!await O(se)){be("Copy failed");return}be(W.trimEnd()?"Copied selection":"Copied visible terminal")},qe=W=>{if(!m||!l)return;((d==null?void 0:d(Z,de,W))??!1)||be("Terminal input failed")},z=async()=>{if(x)return;h(!0),y("Loading older terminal output..."),ke.current=!0;const W=await pt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(h(!1),(W==null?void 0:W.success)===!1){ke.current=!1,y(`Older terminal output unavailable: ${W.error}`);return}v(!0),Te("Older terminal output loaded"),Ne(()=>{var G;(G=r.current)==null||G.bumpResize()})};i.useEffect(()=>{var G,se;if(!de)return;Z&&((G=ht.getState)==null?void 0:G.call(ht,Z))==="connected"&&pt();const W=(se=ht.onStateChange)==null?void 0:se.call(ht,(ne,Se)=>{ne!==Z||Se!=="connected"||pt()});return()=>{W==null||W()}},[Z,de,r]),i.useEffect(()=>{t&&Ge()},[t,le,r]),i.useEffect(()=>{var ne,Se;const W=F.current,G=(Se=(ne=W==null?void 0:W.ownerDocument)==null?void 0:ne.defaultView)==null?void 0:Se.ResizeObserver;if(!W||!G)return;const se=new G(Ee=>{const Oe=Ee[0];if(!Oe)return;const{width:Re,height:Fe}=Oe.contentRect;L(Ue=>{const Le=Math.round(Re),Ze=Math.round(Fe);return Ue.width===Le&&Ue.height===Ze?Ue:{width:Le,height:Ze}})});return se.observe(W),()=>se.disconnect()},[]),i.useEffect(()=>{if(R.current)return;const W=Ce();!Number.isFinite(W)||W<=0||T(G=>K.current?W<G-Ie?W:G:(K.current=!0,W))},[S.height,S.width,B.height,B.width]),i.useEffect(()=>{H&&He()},[H,Ae,Me]),i.useEffect(()=>{var se;const W=V.current;if(V.current=l,!l)return;W||v(!1),je.current&&(je.current=!1,Xe());const G=me.current;G&&(me.current=null,mt(G.text,G.seq,G.cols,G.rows,{force:!!G.force})),Z&&de&&((se=ht.getState)==null?void 0:se.call(ht,Z))==="connected"&&pt(),J.current&&q.current===null&&ue(),Ne(()=>{var ne;(ne=r.current)==null||ne.bumpResize()})},[Z,l,de]),i.useEffect(()=>()=>{q.current!==null&&Q(),he(),oe()},[]),i.useEffect(()=>{const W=ne=>{var Ee;const Se=ne.detail;Se!=null&&Se.sessionId&&Se.sessionId!==de||m&&((Ee=r.current)==null||Ee.bumpResize())},G=xe(),se=G===window?[window]:[window,G];for(const ne of se)ne.addEventListener("adhdev:fit-cli-terminal",W);return()=>{for(const ne of se)ne.removeEventListener("adhdev:fit-cli-terminal",W)}},[m,de,r]);const X=m&&f&&!C&&($.atTop||!$.canScroll)||x||!!g;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:F,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[X&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.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:()=>{z()},disabled:!de||x,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:x?"Loading older...":"Load older terminal output"}),g&&s.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:g})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[I&&s.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:I}),s.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:()=>{Be()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),s.jsxs("div",{className:"relative",children:[s.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:()=>j(W=>!W),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":k,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),k&&s.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:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.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:()=>j(!1),"aria-label":"Close terminal control keys",children:"×"})]}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.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:()=>qe("\x1B"),children:"Esc"}),s.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:()=>qe(" "),children:"Tab"}),s.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:()=>qe("\r"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.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:()=>qe("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.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:()=>qe("\x1B[D"),"aria-label":"Arrow left",children:"←"}),s.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:()=>qe("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),s.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:()=>qe("\x1B[C"),"aria-label":"Arrow right",children:"→"}),s.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:()=>qe(""),children:"Ctrl-C"}),s.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:()=>qe(""),children:"Ctrl-D"}),s.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:()=>qe(""),children:"Bksp"})]})]})]}),s.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:()=>{R.current=!0,T(W=>{const G=Math.max(_e,Number((W-.1).toFixed(2)));return G>_e&&He(),G})},title:"Shrink terminal viewport",children:"-"}),s.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:()=>{R.current=!0,T(W=>{const G=Math.min(ae,Number((W+.1).toFixed(2)));return G>_e&&He(),G})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:P,className:H?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Me>0?`${Me}px`:"100%",height:Ae>0?`${Ae}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:S.width>0?`${S.width}px`:"100%",height:S.height>0?`${S.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:N},children:s.jsx(vc,{ref:r,readOnly:!m||!l,sizingMode:"measured",onViewportMetrics:D,onScrollMetrics:E,onInput:W=>{!m||(d==null||d(Z,de,W))}})})})}),!m&&s.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:b})]}),s.jsx(_c,{contextKey:e.tabKey,panelLabel:ut(e),isSending:a,isBusy:!!ve,statusMessage:ce,onSend:async W=>ve?!1:n(W),isActive:c&&l,showControlsToggle:!1,animateVisibility:!1})]})}const cx=5e3,dx=12e3;function ux(e){return e==="disconnected"||e==="reconnecting"}function mx({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=cx,reconnectActionDelayMs:o=dx}){const l=ux(e),[c,d]=i.useState(()=>!l||a<=0),[m,u]=i.useState(()=>!l||o<=0),p=i.useRef(!1);i.useEffect(()=>{if(!l){d(!1);return}if(p.current=!1,a<=0){p.current=!0,d(!0);return}d(!1);const v=setTimeout(()=>{p.current=!0,d(!0)},a);return()=>clearTimeout(v)},[a,l]),i.useEffect(()=>{if(!l){u(!1);return}if(o<=0){u(!0);return}u(!1);const v=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(v)},[o,l]);const b=l?c:e==="offline"||e==="auth_failed",w=!!(n&&e!=="auth_failed"&&(!l||m)),x=i.useMemo(()=>!t||e!=="connected"?!1:a<=0||p.current,[a,t,e]),h=e==="auth_failed"?"red":e==="offline"?"orange":"accent",g={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)"},f={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},A="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",C={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[b&&s.jsx("div",{className:A,style:C,children:s.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:g[h],border:y[h],color:f[h]},children:[s.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}}),s.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?s.jsxs(s.Fragment,{children:["Session expired."," ",s.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),w&&s.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"})]})}),x&&s.jsx("div",{className:A,style:C,children:s.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:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function px({terminalBackend:e,isStandalone:t=!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]),!t||!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 s.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:[s.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[s.jsxs("span",{children:[c," is using `xterm` fallback."]}),s.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),s.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 Ko({mode:e,onChange:t,compact:r=!1}){const n=r?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?s.jsx(Io,{size:n}):s.jsx(Zt,{size:n})})}const Vt="New session",sd="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 hx(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 t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function fx(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 xx(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:t="",compact:r=!1}){const n=hx(e),a=fx(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 s.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 ${xx(a)} ${t}`.trim(),title:o.join(" · ")||n,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:n})]})}function bx({wsStatus:e,isConnected:t,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..."}:t?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function tl({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function sl({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const l=Kn(e.updatedAt),c=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${c?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",l].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function gx({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:l,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:p,onShowAllHidden:b,onResetPanelsToMain:w,inboxOpen:x,onInboxOpenChange:h,hiddenOpen:g,onHiddenOpenChange:y,onOpenNewSession:f,onOpenDashboardGuide:A,guideNudgeVisible:C=!1,actionShortcuts:v,notifications:N,notificationUnreadCount:T,onOpenNotification:k,onMarkNotificationRead:j,onMarkNotificationUnread:B,onDeleteNotification:L,onOpenGitDialog:S,onOpenMeshGraph:D}){var Ne;const{ides:$,p2pStates:E={}}=cs(),I=!!e&&at(e)&&!st(e),M=!!e&&st(e),F=!!(e!=null&&e.daemonId)&&typeof((Ne=e==null?void 0:e.settings)==null?void 0:Ne.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,P=c||(e?Lc(e)?"terminal":"chat":null),[R,K]=i.useState(!1),V=i.useRef(null),te=i.useRef(null),ie=$.filter(Q=>Q.type==="adhdev-daemon"),J=bx({wsStatus:t,isConnected:r,daemonCount:ie.length,p2pStates:E}),me=J.subtitle,je=J.tone==="connected"?"#22c55e":J.tone==="limited"?"#eab308":"#ef4444",ke=J.tone==="connected"?"0 0 4px #22c55e80":J.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",q=i.useMemo(()=>N.filter(Q=>!Q.readAt),[N]),ge=i.useMemo(()=>N.filter(Q=>!!Q.readAt),[N]),fe=i.useMemo(()=>q.slice(0,9),[q]),we=T;i.useEffect(()=>{if(!x)return;const Q=he=>{var oe;(oe=V.current)!=null&&oe.contains(he.target)||h(!1)};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[x,h]),i.useEffect(()=>{if(!g)return;const Q=he=>{var oe;(oe=te.current)!=null&&oe.contains(he.target)||y(!1)};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[g,y]),i.useEffect(()=>{if(!g&&!x)return;const Q=he=>{if(!he.altKey)return;const oe=he.code.match(/^Digit([1-9])$/);if(!oe)return;const ue=Number(oe[1])-1,le=g?u[ue]:void 0,de=x?fe[ue]:void 0;if(!(!le&&!de)){if(he.preventDefault(),he.stopPropagation(),le){p==null||p(le),y(!1);return}de&&(k(de),h(!1))}};return window.addEventListener("keydown",Q,!0),()=>window.removeEventListener("keydown",Q,!0)},[u,g,x,fe,y,h,k,p]);const xe=Q=>{if(!Q)return;const he=n.find(oe=>oe.tabKey===Q);he&&(m==null||m(he))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Zt,{size:18}),s.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),s.jsx("span",{className:"header-title-mobile",children:e?ut(e):"Dashboard"}),s.jsx("span",{title:J.title,"aria-label":J.title,className:"header-title-status-dot",style:{background:je,boxShadow:ke}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:je,boxShadow:ke}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[me&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",me]}),f&&s.jsx("button",{type:"button",onClick:f,className:"btn btn-secondary btn-sm ml-2",title:`${Vt}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":Vt,children:s.jsx(pc,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[A&&s.jsxs("button",{type:"button",onClick:A,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:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),C&&s.jsx("span",{children:"Guide"})]}),e&&(I||M||!st(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:Cs(e)||ut(e),children:ut(e)}),S&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>S(e.daemonId,e.workspacePath),children:s.jsx(zs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(zs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),F&&D&&s.jsxs("button",{type:"button",onClick:()=>D(e),className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",title:"Open live repo mesh graph",children:[s.jsx(ns,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(I||M)&&l&&s.jsxs(s.Fragment,{children:[I&&d&&P&&s.jsx(Ko,{mode:P,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:M?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(jt,{size:14})})]}),!st(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:s.jsx(No,{size:14})}),!I&&!st(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(Rt,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:V,children:[s.jsxs("div",{className:`dashboard-header-hidden${R?" is-drop-target":""}`,ref:te,onDragEnter:Q=>{Q.dataTransfer.types.includes("text/tab-key")&&(Q.preventDefault(),K(!0))},onDragOver:Q=>{Q.dataTransfer.types.includes("text/tab-key")&&(Q.preventDefault(),Q.dataTransfer.dropEffect="move",K(!0))},onDragLeave:Q=>{Q.currentTarget.contains(Q.relatedTarget)||K(!1)},onDrop:Q=>{const he=Q.dataTransfer.getData("text/tab-key");Q.preventDefault(),K(!1),xe(he)},children:[s.jsxs("button",{type:"button",onClick:()=>y(!g),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[s.jsx(Co,{size:16}),u.length>0&&s.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),g&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),s.jsx(tl,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[w&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:w,children:"Reset panels"}),u.length>0&&b&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{b(),y(!1)},children:"Restore all"})]})]}),e&&m&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),s.jsx(tl,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:ut(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(Q=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{p==null||p(Q),y(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:ut(Q)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(Q)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(Q)+1]}):null,Cs(Q)]})]},Q.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!x),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Hn,{size:16}),we>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:we})]}),x&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[q.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),q.map(Q=>s.jsx(sl,{notification:Q,shortcutIndex:fe.indexOf(Q)>=0?fe.indexOf(Q)+1:void 0,onOpen:()=>k(Q),onMarkRead:()=>j(Q.id),onMarkUnread:()=>B(Q.id),onDelete:()=>L(Q.id)},Q.id))]}),ge.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),ge.map(Q=>s.jsx(sl,{notification:Q,onOpen:()=>k(Q),onMarkRead:()=>j(Q.id),onMarkUnread:()=>B(Q.id),onDelete:()=>L(Q.id)},Q.id))]}),N.length===0&&s.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 yx(e,t){return String(e||"")!==String(t||"")}function vx(e,t={}){const r=String(t.textQuery||"").trim().toLowerCase(),n=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.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&&!Nc(l.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
42
|
+
`).includes(a)))}function wx(e,t="recent"){const r=e.slice();return r.sort((n,a)=>{if(t==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="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 rd(e,t={}){return wx(vx(e,t),t.sortMode||"recent")}function Rn(e){return e?"Resume saved history":"Start fresh"}function Uo(e){return e?"Resuming saved history…":"Starting fresh…"}function jx(){return"Start fresh"}function nd(e,t=!1){return e==="cli"?Rn(t):e==="ide"?"Start IDE":"Start ACP session"}function ad(e,t=!1){return e==="cli"?Uo(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function kx(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Sx(){return"Open saved history"}function Nx(){return"Saved History"}function zo(){return"Use saved history when you want continuity in the same provider conversation."}function Cx(){return"No saved history found yet."}function Ix(){return"Refresh saved history"}function Mx(){return"Refreshing saved history…"}function bs(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function gs(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 Gs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Vs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Go(e){return`Resume saved history with ${e}?`}function Vo(){return"Review or change the target workspace before resuming saved history."}function Ax(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 qo({activeConv:e,ides:t,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:l=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:p,onSwitchSession:b,onRefreshHistory:w,onResumeSavedSession:x}){var L;const h=t.find(S=>S.id===e.routeId),g=(h==null?void 0:h.chats)||[],y=(L=h==null?void 0:h.activeChat)==null?void 0:L.id,f=at(e)&&!st(e),[A,C]=i.useState(()=>Nt()),v=c||A,N=String(d||"").trim(),T=S=>{if(m){m(S);return}C(S)},k=i.useMemo(()=>a.map(S=>{const D=String(S.workspace||"").trim();return S.canResume||D||!N?S:{...S,workspace:N,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[N,a]),j=i.useMemo(()=>rd(k,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[k,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.workspaceQuery]),B=s.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:[s.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.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:[s.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:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:f?Nx():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:ox(e)}),f&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:zo()})]}),s.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:s.jsx(jt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!f&&s.jsx("button",{onClick:p,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"}),f?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:v.textQuery,onChange:S=>T({...v,textQuery:S.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"}),s.jsx("input",{type:"text",value:v.workspaceQuery,onChange:S=>T({...v,workspaceQuery:S.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"}),s.jsx("input",{type:"text",value:v.modelQuery,onChange:S=>T({...v,modelQuery:S.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"}),s.jsxs("select",{value:v.sortMode,onChange:S=>T({...v,sortMode:S.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:v.resumableOnly,onChange:S=>T({...v,resumableOnly:S.target.checked})}),"Resume-ready only"]})]}),j.map(S=>{const D=e.providerSessionId===S.providerSessionId,$=D||!S.canResume||!!l,E=S.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{$||!x||x(S)},disabled:$,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${D?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${$?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${D?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:S.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:S.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:Ax(S.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:S.preview||"No saved preview yet"}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[S.workspace||"Workspace unknown",E?" · selected workspace":"",Ns(S.summaryMetadata)?` · ${Ns(S.summaryMetadata)}`:"",S.messageCount>0?` · ${S.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:D?"ACTIVE":S.canResume?E?"RESUME IN SELECTED WORKSPACE":l===S.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},S.id)})]}):g.map(S=>s.jsxs("div",{onClick:()=>{b(e.routeId,S.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${y===S.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${y===S.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:S.title||"Untitled Session"}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[S.id.substring(0,12),"..."]}),y===S.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},S.id)),(f&&!o&&j.length===0||!f&&g.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Zm,{size:32})}),s.jsx("div",{className:"text-[13px]",children:f?a.length>0?"No saved history matches these filters.":Cx():"No recent chat sessions found."})]}),f&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:Mx()})})]}),s.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:s.jsx("button",{onClick:w,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Tr,{size:13})," ",f?Ix():"Refresh History"]})})})]})]});return typeof document>"u"?B:Nr.createPortal(B,document.body)}const rl={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 od({toasts:e,onDismiss:t,onClickToast:r}){return s.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=rl[n.type]||rl.info;return s.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:[s.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))`}}),s.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(),t(n.id)},"aria-label":"Dismiss",children:s.jsx(jt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.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})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,l)=>s.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(),t(n.id)},children:o.label},l))})]})]},n.id)})})}const Tx=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function _x(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function Lx(e){return e.sessionId||e.instanceId||e.agentType}function fa(e,t){return t||e||"unknown"}function id(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Lt(r,{fallbackId:r.id}));return t}function ld(e,t={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=t.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:t.connectionStates?t.connectionStates[r]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Yo(e,t={}){return Rx(e,ld(e,t))}function Rx(e,t={}){var p,b,w,x,h;const r=[],n=t.machineName,a=t.connectionState,o=_x(e),l=e.workspace||"",c=sh(e.type,{agentName:e.cliName}),d=at(e)||st(e)?c:lt(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(g=>{var y,f;return{sessionId:g.id,instanceId:g.id,providerSessionId:g.providerSessionId,transport:g.transport,sessionCapabilities:g.capabilities,agentType:g.providerType,agentName:g.providerName||lt(g.providerType),status:g.status,title:g.title,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,messages:((y=g.activeChat)==null?void 0:y.messages)||[],activeModal:((f=g.activeChat)==null?void 0:f.activeModal)||void 0,unread:g.unread,lastSeenAt:g.lastSeenAt,lastUpdated:g.lastUpdated,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,surfaceHidden:g.surfaceHidden,git:g.git,settings:g.settings,messageInput:g.messageInput}}):[],u=Tx(e);if(u){const g=e.sessionId||e.instanceId,y=(p=e.settings)==null?void 0:p.meshCoordinatorFor,f=(b=e.settings)==null?void 0:b.meshNodeFor,A=y?" (Coordinator)":f?" (Mesh Node)":"",C=c+A,v=(w=e.activeChat)==null?void 0:w.activeModal,N=v&&Array.isArray(v.buttons)&&v.buttons.length>0,T=rh(e.activeChat,[{status:e.status,activeModal:(x=e.activeChat)==null?void 0:x.activeModal}],e.agents||[]),k=e.activeChat||{title:"",messages:[]};let j=k.title&&String(k.title).trim()?String(k.title).trim():"";const B=(h=e.activeChat)==null?void 0:h.id,L=e.chats;if(B&&Array.isArray(L)&&L.length>0){const E=L.find(I=>I.id===B||I.id&&String(I.id)===String(B));E!=null&&E.title&&String(E.title).trim()&&(j=String(E.title).trim())}const S=(at(e)||st(e),e.type),D=(at(e)||st(e))&&Hi(j,C,S)?"":j,$=k.messages||[];r.push({routeId:e.id,sessionId:g,providerSessionId:e.providerSessionId,nativeSessionId:g,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:at(e)?e.mode||"terminal":"chat",agentName:C,agentType:S,status:T,title:D,messages:$,resume:e.resume,hostIdeType:!at(e)&&!st(e)?e.type:void 0,workspaceName:o,workspacePath:l,git:e.git,displayPrimary:D||o||(at(e)?e.mode==="chat"?C:`Terminal${A}`:C),displaySecondary:at(e)&&o?C: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:N?v.buttons:void 0,modalMessage:N?v.message:void 0,streamSource:"native",tabKey:fa(g,e.id),machineName:n,connectionState:a,settings:e.settings,messageInput:e.messageInput})}if(u&&(at(e)||st(e)))return r;for(const g of m){const y=g.activeModal&&Array.isArray(g.activeModal.buttons)&&g.activeModal.buttons.length>0,f=nh(g),A=Lx(g),C=`${e.id}:${A}`,v=g.title&&String(g.title).trim()||"",N=Hi(v,g.agentName,g.agentType)?"":v,T=g.messages||[];(g.transport==="cdp-webview"||g.sessionId||g.providerSessionId||T.length>0||y||N||!["idle","panel_hidden","disconnected","not_monitored"].includes(f))&&r.push({routeId:e.id,sessionId:g.sessionId||g.instanceId,providerSessionId:g.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:g.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:g.sessionCapabilities,mode:"chat",agentName:g.agentName,agentType:g.agentType,status:f,title:N,messages:T,hostIdeType:e.type,workspaceName:o,workspacePath:l,git:g.git||e.git,displayPrimary:N||o||g.agentName||d,displaySecondary:`${d} · ${g.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:g.lastMessagePreview,lastMessageRole:g.lastMessageRole,lastMessageAt:g.lastMessageAt,lastMessageHash:g.lastMessageHash,lastUpdated:g.lastUpdated||e.lastUpdated,inboxBucket:g.inboxBucket,completionMarker:g.completionMarker,modalButtons:y?g.activeModal.buttons:void 0,modalMessage:y?g.activeModal.message:void 0,streamSource:"agent-stream",tabKey:fa(g.sessionId||g.instanceId,C),machineName:n,connectionState:a,settings:g.settings,messageInput:g.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:fa(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function cd(e){return String(e.type||e.id||"").trim()}function Px(e){var t;return e.category!=="cli"||!cd(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function Dx(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!Px(a))continue;const o=cd(a);if(!o||t.has(o))continue;t.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 qn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function lo(e,t){const r=new Set(t.map(n=>n.type));return qn(e).filter(n=>r.has(n))}function Ex(e){return e.map(t=>t.type)}function $x(e,t){const r=qn(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function Bx(e,t){return qn(e).filter(r=>r!==t)}function nl(e,t,r){const n=qn(e),a=n.indexOf(t);if(a<0)return n;const o=n.filter(c=>c!==t);if(r==="top")return[t,...o];if(r==="bottom")return[...o,t];const l=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(l,0,t),o}function al({direction:e}){return s.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"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function ol({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,l]=i.useState(""),c=i.useMemo(()=>new Map(t.map(b=>[b.type,b])),[t]),d=i.useMemo(()=>lo(e,t),[e,t]),m=e.length-d.length,u=t.filter(b=>!d.includes(b.type)),p=()=>{o&&(r($x(d,o)),l(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?s.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((b,w)=>{const x=c.get(b);return s.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:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",w+1]}),(x==null?void 0:x.icon)&&s.jsx("span",{"aria-hidden":"true",children:x.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:b}),s.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"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:x?`${x.label} · ${x.statusLabel}`:b})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.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||w===0,title:"Move up",onClick:()=>r(nl(d,b,"up")),children:s.jsx(al,{direction:"up"})}),s.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||w===d.length-1,title:"Move down",onClick:()=>r(nl(d,b,"down")),children:s.jsx(al,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(Bx(d,b)),children:"Remove"})]})]},b)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.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:b=>l(b.target.value),disabled:n||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(b=>s.jsxs("option",{value:b.type,children:[b.label," (",b.type,")"]},b.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:p,children:"Add provider"}),a]}),s.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 Ox(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function dd(e,t){const r=Ox(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const ud=[{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:"🏄"}],md=[{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:"🧩"}],pd=[{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:"🟠"}],Fx=ud,Wx=md,Hx=pd;function es(...e){return nm(am(e))}function Kx({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:es("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,n&&s.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&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function wr({icon:e,title:t,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:l,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(Kx,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:es("mx-auto flex w-full flex-col gap-4",o,l),children:c})})]})}const co="adhdev:themechange";function Ux(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function Ls(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Rs(e){return e==="system"?Ux():e}function hd(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function pn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(co,{detail:{preference:e,theme:t}}))}function zx(){const e=Ls(),t=Rs(e);hd(t),pn(e,t)}function Qs(){const[e,t]=i.useState(Ls),[r,n]=i.useState(()=>Rs(Ls()));i.useEffect(()=>{hd(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),pn("system",m)}};return l.addEventListener("change",c),()=>l.removeEventListener("change",c)},[e]),i.useEffect(()=>{const l=d=>{const m=d.detail||{},u=m.preference,p=m.theme;t(u==="dark"||u==="light"||u==="system"?u:Ls()),n(p==="dark"||p==="light"?p:Rs(Ls()))},c=d=>{if(d.key!=="theme")return;const m=Ls(),u=Rs(m);t(m),n(u)};return window.addEventListener(co,l),window.addEventListener("storage",c),()=>{window.removeEventListener(co,l),window.removeEventListener("storage",c)}},[]);const a=i.useCallback(l=>{const c=Rs(l);t(l),n(c);try{localStorage.setItem("theme",l)}catch{}pn(l,c)},[]),o=i.useCallback(()=>{t(l=>{const c=l==="dark"?"light":l==="light"?"system":"dark",d=Rs(c);n(d);try{localStorage.setItem("theme",c)}catch{}return pn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const il={dark:"Dark",light:"Light",system:"System"};function Gx({collapsed:e}){const{preference:t,cycleTheme:r}=Qs(),n=t==="dark"?s.jsx(tp,{size:16}):t==="light"?s.jsx(ep,{size:16}):s.jsx(sp,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${il[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:il[t]})]})}function xa(e,t){return e?typeof e=="function"?e(t):e:null}function Vx({children:e,brand:t,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:l,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=i.useState(!1),[p,b]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),w=()=>u(!0),x=()=>u(!1),h=()=>{b(A=>{const C=!A;try{localStorage.setItem(d,C?"1":"0")}catch{}return C})},g=i.useMemo(()=>({collapsed:p,mobileMenuOpen:m,openMobileMenu:w,closeMobileMenu:x,toggleCollapsed:h}),[p,m]),y=A=>`nav-item${A.active?" active":""} cursor-pointer ${p?"justify-center py-2.5 px-0":""}${A.className?` ${A.className}`:""}`,f=A=>s.jsxs("div",{className:y(A),id:`nav-${A.id}`,onClick:()=>{A.onSelect(),x()},title:p?A.title??(typeof A.label=="string"?A.label:void 0):A.title,children:[s.jsx("span",{className:"nav-icon",children:A.icon}),!p&&A.label]},A.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${p?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:w,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),m&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:x,onKeyDown:A=>A.key==="Escape"&&x()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${p?"justify-center gap-0":""}`,children:xa(t,g)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:x,children:s.jsx(jt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(f)}),n.map(A=>s.jsxs("div",{className:A.className??"border-t border-border-subtle pt-2 mt-2",children:[!p&&A.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:A.title}):null,A.items.map(f)]},A.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(f),xa(o,g),s.jsx(Gx,{collapsed:p}),xa(l,g)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function wt({title:e,icon:t,description:r,accentColor:n,className:a,children:o}){return s.jsxs("div",{className:es("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)&&s.jsxs("div",{className:"mb-4",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[t&&s.jsx("span",{className:"mr-1.5",children:t}),e]}),r&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o]})}function Pn({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:es("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const qx={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"},Yx={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Es({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:es("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",qx[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Yx[e]}),s.jsx("span",{children:t})]}),r&&s.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Tt({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:es("mb-5",n),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function cr(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:es("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",t)})}const Xx={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"},Jx={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Qx({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:es("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Xx[e],r),children:[s.jsx("span",{className:es("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Jx[e])}),n]})}function ps({label:e,description:t,checked:r,disabled:n,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.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:[s.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))"}}),s.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 Zx({onPrefChange:e}){const[t,r]=hh(),[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 s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:l=>o("globalEnabled",l)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Rt,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:l=>o("browserNotifications",l)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.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"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{Mc().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"&&s.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"&&s.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."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(rp,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:l=>o("completionAlert",l)}),s.jsx(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(np,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:l=>o("approvalAlert",l)}),s.jsx(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hs,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:l=>o("disconnectAlert",l)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function Dn(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function eb(e,t){const r=Dn(e),n=Dn(t);if(!r||!n)return e.localeCompare(t);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 fd(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function jr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||eb(r,t)>=0)return!1;const n=Dn(r),a=Dn(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function tb(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function ba(e,t){return e instanceof Error?e.message:t}function sb({ides:e,emptyMessage:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(l=>l.type==="adhdev-daemon");return o.length===0?s.jsx(Pn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:t||"Install ADHDev on a machine and sign in to connect it here."}):s.jsx("div",{className:"flex flex-col gap-2",children:o.map(l=>s.jsx(nb,{ide:l,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},l.id))})}function ll({title:e,message:t,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 Nr.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,children:s.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:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.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"}),s.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 rb(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Fx,...Wx,...Hx].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function nb({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var $,E;const[o,l]=i.useState("idle"),[c,d]=i.useState(""),[m,u]=i.useState(null),[p,b]=i.useState("idle"),[w,x]=i.useState(""),h=e.version||null,g=(($=e.machine)==null?void 0:$.platform)||((E=e.system)==null?void 0:E.platform)||"",y=Lt(e,{fallbackId:e.id}),f=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",A=t.filter(I=>I.daemonId===e.id&&I.transport==="cdp-page"),C=t.filter(I=>I.daemonId===e.id&&I.transport==="pty"),v=t.filter(I=>I.daemonId===e.id&&I.transport==="acp"),N=e.p2p,T=async()=>{if(r){l("upgrading"),d("Starting upgrade...");try{const I=tb(await r(e.id,"daemon_upgrade",{}));I.alreadyLatest?(l("done"),d(`Already on v${I.version||"latest"}.`)):I.upgraded||I.success?(l("done"),d(`Upgrade to v${I.version||"latest"} started. Daemon is restarting...`)):(l("error"),d(I.error||"Upgrade failed"))}catch(I){l("error"),d(ba(I,"Connection lost during upgrade"))}}},k=async()=>{if(u(null),!!n){b("loading");try{await n(e.id),b("done"),x("Machine disconnected.")}catch(I){b("error"),x(ba(I,"Failed to disconnect"))}}},j=async()=>{if(u(null),!!a){b("loading");try{await a(e.id),b("done"),x("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(I){b("error"),x(ba(I,"Failed to revoke token"))}}},B="0.9.81",L=fd(e,B),S=jr(e,B),D=A.length+C.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:f}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:y}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),h&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",h,!L&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[r&&L&&s.jsx("button",{onClick:T,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"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${S?"↑ Update now":`↑ Update${` to v${B}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:p==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:p==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Qx,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[N&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${N.state==="connecting"||N.state==="new"?"animate-pulse":""}`,style:N.state==="connecting"||N.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",N.state==="connected"?"connected":N.state==="connecting"||N.state==="new"?"connecting...":N.state||"off"]}),N.peers!==void 0&&N.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",N.peers," peer",N.peers!==1?"s":"",")"]})]}),N&&D>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),D>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[A.map(I=>{const M=rb(I.type),F=I.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:M.icon}),s.jsx("span",{children:M.name}),F!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${F?"bg-green-400":"animate-pulse"}`,style:F?void 0:{background:"var(--status-warning)"},title:F?"CDP connected":"CDP connecting..."})]},I.id)}),C.map(I=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:I.cliName||"CLI"})]},I.id)),v.map(I=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:I.cliName||"ACP"})]},I.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||w)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||p==="error"?"text-red-400":o==="done"||p==="done"?"text-green-400":"text-text-muted"}`,children:w||c})]}),m==="disconnect"&&s.jsx(ll,{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:k,onCancel:()=>u(null)}),m==="revoke"&&s.jsx(ll,{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:j,onCancel:()=>u(null)})]})}const ab=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ob(){const{preference:e,setPreference:t}=Qs();return s.jsx("div",{className:"flex gap-2",children:ab.map(r=>s.jsxs("button",{onClick:()=>t(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:[s.jsx("span",{children:r.icon}),r.label]},r.id))})}function ib(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function lb(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function ga(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function cl(e){const{r:t,g:r,b:n}=lb(e);return .2126*ga(t)+.7152*ga(r)+.0722*ga(n)}function dl(e,t){const r=cl(e),n=cl(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function xd(e){const t=ib(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return dl(t,r)>=dl(t,n)?r:n}const uo={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},mo={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},cb=[{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"}}}],bd="adhdev-chat-theme",gd="adhdev-chat-theme-custom";function hn(){if(typeof window>"u")return"ember";try{return localStorage.getItem(bd)||"ember"}catch{return"ember"}}function Wt(e){try{const t=localStorage.getItem(gd);if(t){const r=JSON.parse(t);return{...e==="dark"?uo:mo,...r[e]}}}catch{}return e==="dark"?uo:mo}function Yr(e,t){try{localStorage.setItem(gd,JSON.stringify({dark:e,light:t}))}catch{}}function Dt(e,t){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}, ${t})`}function En(e,t){const r=Math.min(255,parseInt(e.slice(1,3),16)+t),n=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const db={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function kr(e,t){var a;const r=(a=db[e])==null?void 0:a[t];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",En(r,24)),n.style.setProperty("--accent-on-primary",xd(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${En(r,18)})`),n.style.setProperty("--border-accent",Dt(r,.35)),n.style.setProperty("--nav-active-bg",Dt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Dt(r,.06)}`)}function ys(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Dt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Dt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Dt(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",Dt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Dt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",En(e.accentColor,30)),t.style.setProperty("--accent-on-primary",xd(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${En(e.accentColor,40)})`),t.style.setProperty("--border-accent",Dt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Dt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Dt(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${Dt(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.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 ub(e){try{localStorage.setItem(bd,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=vs()?"dark":"light";ys(Wt(t))}else Xo(),kr(e,vs()?"dark":"light")}function mb(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=hn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=vs()?"dark":"light";ys(Wt(t))}else Xo(),kr(e,vs()?"dark":"light")}function vs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ct({label:e,value:t,onChange:r}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,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 dr({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.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}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function pb({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>Wt(r));i.useEffect(()=>{a(Wt(r))},[r]);const o=i.useCallback((l,c)=>{a(d=>{const m={...d,[l]:c},p=Wt(r==="dark"?"light":"dark");return r==="dark"?Yr(m,p):Yr(p,m),ys(m),t(m),m})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.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",s.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"]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(dr,{title:"App Background",children:[s.jsx(Ct,{label:"Background",value:n.bgPrimary,onChange:l=>o("bgPrimary",l)}),s.jsx(Ct,{label:"Surface",value:n.bgSecondary,onChange:l=>o("bgSecondary",l)}),s.jsx(Ct,{label:"Card",value:n.surfacePrimary,onChange:l=>o("surfacePrimary",l)})]}),s.jsxs(dr,{title:"App Text",children:[s.jsx(Ct,{label:"Primary",value:n.textPrimary,onChange:l=>o("textPrimary",l)}),s.jsx(Ct,{label:"Secondary",value:n.textSecondary,onChange:l=>o("textSecondary",l)}),s.jsx(Ct,{label:"Muted",value:n.textMuted,onChange:l=>o("textMuted",l)})]}),s.jsxs(dr,{title:"Borders & Accent",children:[s.jsx(Ct,{label:"Border subtle",value:n.borderSubtle,onChange:l=>o("borderSubtle",l)}),s.jsx(Ct,{label:"Border default",value:n.borderDefault,onChange:l=>o("borderDefault",l)}),s.jsx(Ct,{label:"Accent",value:n.accentColor,onChange:l=>o("accentColor",l)})]})]}),s.jsxs("div",{children:[s.jsxs(dr,{title:"Chat Bubbles",children:[s.jsx(Ct,{label:"User bubble",value:n.userBubble,onChange:l=>o("userBubble",l)}),s.jsx(Ct,{label:"User text",value:n.userText,onChange:l=>o("userText",l)}),s.jsx(Ct,{label:"Agent bubble",value:n.assistantBubble,onChange:l=>o("assistantBubble",l)}),s.jsx(Ct,{label:"Agent text",value:n.assistantText,onChange:l=>o("assistantText",l)})]}),s.jsxs(dr,{title:"Chat Layout",children:[s.jsx(Ct,{label:"Chat BG",value:n.containerBg,onChange:l=>o("containerBg",l)}),s.jsx(Ct,{label:"Send button",value:n.sendButton,onChange:l=>o("sendButton",l)}),s.jsx(Ct,{label:"Input border",value:n.inputBorder,onChange:l=>o("inputBorder",l)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.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)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const l=e?uo:mo,d=Wt(e?"light":"dark");e?Yr(l,d):Yr(d,l),a(l),ys(l),t(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 hb(){const[e,t]=i.useState(hn),[r,n]=i.useState(!0),[a,o]=i.useState(()=>Wt("dark"));i.useEffect(()=>{n(vs());const d=new MutationObserver(()=>{const p=vs();n(p);const b=hn();b==="custom"?ys(Wt(p?"dark":"light")):kr(b,p?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const p=vs();n(p);const b=hn();b==="custom"?ys(Wt(p?"dark":"light")):kr(b,p?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ys(Wt(r?"dark":"light")):(Xo(),kr(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(Wt(r?"dark":"light"))},[r]);const l=d=>{t(d),ub(d)},c=[...cb,{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 s.jsxs("div",{children:[s.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,p=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return s.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:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[s.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?"}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:p},children:"Fix the bug please"}),s.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! ✨"})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[m&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&s.jsx(pb,{dark:r,onColorsChange:d=>o(d)})]})}const Jo="adhdev_mobileDashboardMode_v1",po="adhdev:mobile-dashboard-mode-change";function Qo(){try{return localStorage.getItem(Jo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function fb(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Qo())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==Jo||t()};return window.addEventListener(po,r),window.addEventListener("storage",n),()=>{window.removeEventListener(po,r),window.removeEventListener("storage",n)}}function xb(e){try{localStorage.setItem(Jo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(po,{detail:e}))}function bb(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(Qo()==="chat")},[]),s.jsx(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),xb(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const ya=new Map,ul=new Map;function gb(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function yb(e,t,r,n){return{...e||{},id:t,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 yd(){const{sendCommand:e}=kt(),{injectEntries:t,getIdes:r}=Cr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??ff,l=ul.get(n)||0;if(!(a!=null&&a.force)&&l>0&&Date.now()-l<o)return;const c=ya.get(n);if(c)return c;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=gb(m);if(!u)return;const p=r().find(w=>w.id===n),b=yb(p,n,u.machine,u.timestamp||Date.now());t([b]),ul.set(n,Date.now())})().finally(()=>{ya.delete(n)});return ya.set(n,d),d},[r,t,e])}function vb(e,t,r){return{...e||{},id:t,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 wb(e,t){const{sendData:r}=kt(),{injectEntries:n,getIdes:a}=Cr(),o=Array.from(new Set(e.filter(Boolean))).join("|");i.useEffect(()=>{if(!(t!=null&&t.enabled)||!r)return;const l=o?o.split("|"):[];if(l.length===0)return;const c=l.map(d=>Qt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const p=a().find(w=>w.id===d),b=vb(p,d,u);n([b])}));return()=>{c.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function jb(e,t){const{sendData:r}=kt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);return i.useEffect(()=>{if(!e){a(null),l(!1);return}if(!(t!=null&&t.enabled)||!r){l(!1);return}a(null),l(!0);let c=null;const d=Qt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},m=>{c&&(clearTimeout(c),c=null),a(m.diagnostics),l(!1)});return d.initialSendAccepted?c=setTimeout(()=>{l(!1)},yf):l(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function kb(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function vd(e){const{sendData:t}=kt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=kb(e);if(!a||!e.sessionId||!t){n({});return}const o=Qt.subscribe({sendData:t},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,t]),r}const wd="adhdev_hiddenTabs",jd="adhdev_autoHiddenMeshTabs";function Sb(){try{const e=localStorage.getItem(wd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function us(e){try{localStorage.setItem(wd,JSON.stringify([...e]))}catch{}}function Nb(){try{const e=localStorage.getItem(jd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ml(e){try{localStorage.setItem(jd,JSON.stringify([...e]))}catch{}}function br(e){return Wo(e)}function Yn(e,t){return Os(t).some(r=>e.has(r))}function Cb(e){var t,r,n;return((t=e.settings)==null?void 0:t.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 Ib(e,t,r=new Set){return e.filter(n=>{if(!Cb(n))return!1;const a=br(n);return r.has(a)?!1:!Yn(t,n)})}function Mb(){const[e,t]=i.useState(Sb),[r,n]=i.useState(Nb),a=i.useCallback(b=>{const w=br(b);t(x=>{const h=new Set(x);return h.has(w)?h.delete(w):h.add(w),us(h),h})},[]),o=i.useCallback(b=>{const w=br(b);t(x=>{if(x.has(w))return x;const h=new Set(x);return h.add(w),us(h),h})},[]),l=i.useCallback(b=>{const w=br(b);t(x=>{if(x.has(w))return x;const h=new Set(x);return h.add(w),us(h),h}),n(x=>{if(x.has(w))return x;const h=new Set(x);return h.add(w),ml(h),h})},[]),c=i.useCallback(b=>{const w=br(b);t(x=>{if(!x.has(w))return x;const h=new Set(x);return h.delete(w),us(h),h}),n(x=>{if(x.has(w))return x;const h=new Set(x);return h.add(w),ml(h),h})},[]),d=i.useCallback(()=>{t(b=>{if(b.size===0)return b;const w=new Set;return us(w),w})},[]),m=i.useCallback((b,w)=>{t(x=>{const h=new Set(x);for(const g of w)h.add(g);return us(h),h})},[]),u=i.useCallback((b,w)=>{t(x=>{const h=new Set(x);for(const g of w)h.delete(g);return us(h),h})},[]),p=i.useCallback(b=>Yn(e,b),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:l,showTarget:c,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:p}}function kd(e){return e instanceof Error?e.message:String(e||"")}function Sd(e){const t=kd(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function Nd(e){const t=kd(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Cd({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!at(e)||st(e))return;const o=Js(e);if(o===t)return;const l=e.sessionId;l&&a(c=>({...c,[l]:t}));try{await n(As(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Yt(e),mode:t})}catch(c){const d=Nd(c);l&&!d&&a(m=>{const u={...m};return o===Id(r,l)?delete u[l]:u[l]=o,u}),Sd(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 pl(e,t){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=t[r];return!n||e.mode===n?e:{...e,mode:n}}function Ab(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let r=!1;const n=e.map(a=>{const o=pl(a,t),l=Array.isArray(a.childSessions)?a.childSessions.map(d=>pl(d,t)):a.childSessions,c=l!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:l}:{}}):a});return r?n:e}function Id(e,t){if(!t)return null;for(const r of e){if(r.sessionId===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function Tb(e,t){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,o]of Object.entries(e))Id(t,a)===o&&(delete n[a],r=!0);return r?n:e}function _b({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{Mc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:ed(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return gh(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const l=setTimeout(()=>{r(c=>{const d=Date.now(),m={};for(const[u,p]of Object.entries(c))d-p<5e3&&(m[u]=p);return Object.keys(m).length===Object.keys(c).length?c:m})},5500);return()=>clearTimeout(l)},[t,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 hl(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function ws(e){const t=[...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=hl(t==null?void 0:t.receivedAt)||hl(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function ho(e,t=0){return ws(e)||e.lastUpdated||t||0}function Md(e){return ws(e)||e.lastUpdated||0}function Ad(e,t,r=Md){const n=r(t)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const l=e.displaySecondary.localeCompare(t.displaySecondary);return l!==0?l:e.tabKey.localeCompare(t.tabKey)}function fo(e){var r;const t=vt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function Lb(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!fo(e)&&!e.title.trim()}function Rb(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(fo(r))-Number(fo(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Ad(t,r)})[0]||null}function Ht(e,t){const r=e.filter(l=>l.routeId===t);if(r.length===0)return null;const n=r.find(l=>l.streamSource==="native")||null,a=r.filter(l=>l.streamSource==="agent-stream"),o=Rb(a);return n?o&&Lb(n)?o:n:o||r[0]||null}function Pb(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function Db(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=Pb(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 va(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function Eb(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function fl(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Eb(Ws(r.content)):"";return[e.id||"",e.title||"",e.status||"",t.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 $b(e){const t=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||""),fl(e.activeChat),...t.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||""),fl(r.activeChat)].join(":"))].join("|")}function Bb(e,t){const r=Date.now();return e.map(n=>{const a=t[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function Ob(e,t){const r=new Map;for(const n of e){const a=t.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 Fb(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Wb(e){const t=Fb(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const r=String(t.role||""),n=Ws(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Hb({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Db(e),[e]),o=i.useMemo(()=>id(e),[e]),l=i.useRef([]),c=i.useRef([]),d=i.useRef([]),m=i.useRef(new Map),u=i.useRef(new Map),p=i.useMemo(()=>{const C=new Map,v=[];for(const j of a){const{connectionState:B="new",machineName:L}=ld(j,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),S=$b(j),D=m.current.get(j.id);if(D&&D.ide===j&&D.sourceSignature===S&&D.connectionState===B&&D.machineName===L){C.set(j.id,D),v.push(...D.conversations);continue}const $=Yo(j,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),E={ide:j,sourceSignature:S,connectionState:B,machineName:L,conversations:$};C.set(j.id,E),v.push(...$)}m.current=C;const N=new Map,T=j=>{const B=Wb(j),L=u.current.get(j.tabKey);if(L&&L.signature===B)return N.set(j.tabKey,L),L.timestamp;const S={signature:B,timestamp:Md(j)||(L==null?void 0:L.timestamp)||0};return N.set(j.tabKey,S),S.timestamp},k=[...v].sort((j,B)=>Ad(j,B,T));return u.current=N,k},[a,t,o]),b=i.useMemo(()=>{const C=Bb(p,r);return va(l.current,C)?l.current:(l.current=C,C)},[p,r]),w=i.useMemo(()=>{const C=new Map,v=Array.from(new Set(b.map(N=>N.routeId)));for(const N of v){const T=Ht(b,N);T&&C.set(N,T)}return C},[b]),x=i.useMemo(()=>{const C=new Map;for(const v of b){const N=w.get(v.routeId),T=v.streamSource==="native"&&N?N:v;for(const k of Os({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))C.set(k,T)}return C},[b,w]),h=i.useMemo(()=>Ob(b,w),[b,w]),g=i.useCallback(C=>{if(C)return x.get(C)},[x]),y=i.useCallback(C=>{if(C)return h.get(C)},[h]),f=i.useMemo(()=>{const C=b.filter(v=>!Yn(n,v));return va(c.current,C)?c.current:(c.current=C,C)},[b,n]),A=i.useMemo(()=>{const C=f.map(v=>v.tabKey);return va(d.current,C)?d.current:(d.current=C,C)},[f]);return{chatIdes:a,conversations:b,visibleConversations:f,visibleTabKeys:A,resolveConversationBySessionId:g,resolveConversationByTarget:y}}function Kb({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:r,setSearchParams:n}){const a=i.useMemo(()=>{var c;return e||!t?null:((c=r(t))==null?void 0:c.tabKey)??null},[e,r,t]),o=i.useMemo(()=>{var c;return!e||!t?null:((c=r(t))==null?void 0:c.tabKey)??null},[e,r,t]),l=i.useCallback(()=>{t&&n(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[n,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:l}}function Ub({ides:e,sendDaemonCommand:t,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{ot.setIdes(e)},[e]),i.useEffect(()=>{ot.setResolveAction((a,o,l)=>{t(a,o,l).catch(()=>{})})},[t]),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=Jc.on("status_event",o=>{ot.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=l=>{var h;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 p=Number(c.buttonIndex),b=c.button||((h=m==null?void 0:m.modalButtons)==null?void 0:h[p])||"Approve",w=String(b).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),x=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(w);t(u,"resolve_action",{action:x?"approve":"reject",button:b,...Number.isFinite(p)&&{buttonIndex:p},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(g=>console.error("[SW Action] approval failed:",g))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",a)}},[n,t])}const zb="adhdev_dashboardLayout_v1",Gb="adhdev_dashboardDockview_v1",Vb="adhdev_dashboardDockviewHiddenRestore_v1",ur={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Zo(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function qb(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Td(e){return`${zb}:${e}`}function Yb(e){const t=Td(e);return Zo(t,null)}function Xb(e,t){try{const r=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,n=Td(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function _d(e){return`${Gb}:${e}`}function Jb(e){const t=_d(e);return Zo(t,null)}function Qb(e,t){try{const r=_d(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Ld(e){return`${Vb}:${e}`}function Zb(e){const t=Ld(e);return Zo(t,{})}function eg(e,t){try{const r=Ld(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function tg(){return{groupAssignments:[...ur.groupAssignments],focusedGroup:ur.focusedGroup,groupActiveTabIds:{...ur.groupActiveTabIds},groupTabOrders:{...ur.groupTabOrders},groupSizes:[...ur.groupSizes]}}function sg(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function rg(){const[e]=i.useState(()=>qb(typeof window<"u"?window.innerWidth:1280)),[t,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,l]=i.useState({}),[c,d]=i.useState({}),[m,u]=i.useState([]),[p,b]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,x]=i.useState(!1),h=i.useCallback(()=>{if(w)return;const j=Yb(e)??tg();r(new Map(j.groupAssignments)),a(j.focusedGroup),l(j.groupActiveTabIds),d(j.groupTabOrders),u(j.groupSizes),x(!0)},[w,e]);i.useEffect(()=>{w&&Xb(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:m})},[w,e,t,n,o,c,m]),i.useEffect(()=>{const j=window.matchMedia("(max-width: 767px)"),B=L=>b(L.matches);return j.addEventListener("change",B),()=>j.removeEventListener("change",B)},[]);const g=i.useCallback(j=>{r(j)},[]),y=i.useCallback(j=>{a(j)},[]),f=i.useCallback(j=>{l(j)},[]),A=i.useCallback(j=>{d(j)},[]),C=i.useCallback(j=>{u(j)},[]),v=i.useCallback(j=>{y(j)},[y]),N=i.useCallback((j,B)=>{l(L=>(L[j]??null)===(B??null)?L:{...L,[j]:B})},[]),T=i.useCallback((j,B)=>{d(L=>{const S=L[j];return sg(S,B)?L:{...L,[j]:B}})},[]),k=i.useCallback((j,B)=>{const L=B.get(j)??0;return N(L,j),v(L),L},[v,N]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:g,focusedGroup:n,updateFocusedGroup:y,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:f,setGroupActiveTab:N,groupTabOrders:c,updateGroupTabOrders:A,setGroupTabOrder:T,groupSizes:m,updateGroupSizes:C,isMobile:p,hasHydratedStoredLayout:w,hydrateStoredLayout:h,focusConversationTab:k}}function ng(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Fo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function ag({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:l,setSearchParams:c,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:p,handleRefreshHistory:b}){const w=i.useRef(!1),x=i.useRef(!1),h=i.useRef(null),g=i.useRef(!1);i.useEffect(()=>{if(!e||w.current||t.length===0)return;if(!a){o();return}const y=r(e);y&&(l(y.tabKey,n),w.current=!0,x.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(f=>{const A=new URLSearchParams(f);return A.delete("activeTab"),A},{replace:!0}))},[e,t,r,n,a,o,l,c]),i.useEffect(()=>{if(!(x.current||a)&&t.length!==0){if(!e){o(),x.current=!0;return}if(w.current){x.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(x.current||a)&&(o(),x.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!d){g.current=!1;return}if(!m||g.current||u)return;const y=p.find(f=>f.id===m.routeId);y&&(!y.chats||y.chats.length===0||ng(y.chats,m))&&(g.current=!0,b())},[d,m,u,p,b])}function wa(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Fo(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Rd({sendDaemonCommand:e,activeConv:t,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[l,c]=i.useState(!1),[d,m]=i.useState(!1),u=i.useCallback(async x=>{try{await e("standalone","launch_ide",{ideType:x,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),p=i.useCallback(async(x,h)=>{try{const g=x||(t==null?void 0:t.daemonId)||"",y=await e(g,"switch_chat",{id:h,sessionId:h,...fs(t)}),f=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||f==="switched"||f==="switched-by-title")return;f===!1||f==="not_found"?or(a,"⚠️ Session tab not found — try refreshing history"):typeof f=="string"&&f.startsWith("error:")?or(a,`⚠️ Switch error: ${f}`):or(a,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),or(a,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,a]),b=i.useCallback(async()=>{if(!(!t||l)){c(!0);try{const x=Us(t);await e(x,"new_chat",{...fs(t)}),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(x){console.error("New chat failed",x)}finally{c(!1)}}},[t,l,e,o]),w=i.useCallback(async()=>{var x,h;if(!(!t||d)){m(!0);try{const g=Us(t),y=async()=>e(g,"list_chats",{forceExpand:!0,...fs(t)});let f=await y(),A=(f==null?void 0:f.chats)||((x=f==null?void 0:f.result)==null?void 0:x.chats);wa(A,t)&&(await new Promise(C=>setTimeout(C,450)),f=await y(),A=(f==null?void 0:f.chats)||((h=f==null?void 0:f.result)==null?void 0:h.chats)),f!=null&&f.success&&Array.isArray(A)&&(n(t.routeId,A),wa(A,t)&&!wa(r,t)&&or(a,"⚠️ History dialog did not fully open — try once more"))}catch(g){console.error("Refresh history failed",g)}finally{m(!1)}}},[t,r,d,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:p,handleNewChat:b,handleRefreshHistory:w}}function og(e,t){if(e.size!==t.size)return!1;for(const[r,n]of e)if(t.get(r)!==n)return!1;return!0}function ig(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function xl(e,t){const r=Object.keys(e),n=Object.keys(t);return r.length!==n.length?!1:r.every(a=>t[Number(a)]===e[Number(a)])}function Xr(e,t){const r=new Set(t),n=t.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 bl(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=t[Number(n)];typeof o=="number"&&(r[o]=a)}return r}function lg(e,t,r){if(t.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...t].reverse().find(a=>a<e)??t[0];return r[n]??0}function cg(e,t,r){if(t.length<=1)return[];const n=t.map(l=>e[l]).filter(l=>Number.isFinite(l)),a=n.length===t.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 gl(e,t){const r={};for(const[n,a]of Object.entries(e)){const o=Number(n);r[o>=t?o+1:o]=a}return r}function yl(e){return Array(e).fill(100/e)}function dg({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:l,isMobile:c,visibleConversations:d,visibleTabKeys:m}){const u=i.useRef(null),p=i.useMemo(()=>Xr(e,m),[e,m]),b=p.assignments,w=i.useMemo(()=>c?1:p.groupCount,[p.groupCount,c]),x=w>1,h=i.useCallback((v,N)=>{t(T=>{const k=new Map(Xr(T,m).assignments);return N===0?k.delete(v):k.set(v,N),k}),n(T=>({...T,[N]:v})),r(N)},[t,m,n,r]),g=i.useCallback(v=>{t(N=>{const T=Xr(N,m).assignments,k=new Map;for(const[j,B]of T)B!==v&&(B>v?k.set(j,B-1):k.set(j,B));return k}),l(N=>{if(N.length<=1)return[];const T=[...N];T.splice(v,1);const k=T.reduce((j,B)=>j+B,0);return k>0?T.map(j=>j/k*100):[]}),r(0)},[t,m,l,r]),y=i.useCallback((v,N)=>{N.preventDefault();const T=u.current;if(!T)return;const k=N.clientX,j=T.offsetWidth,B=o.length===w?[...o]:yl(w),L=D=>{const E=(D.clientX-k)/j*100,I=[...B];I[v]=Math.max(15,B[v]+E),I[v+1]=Math.max(15,B[v+1]-E),l(I)},S=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",S),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",L),document.addEventListener("mouseup",S)},[o,w,l]),f=i.useCallback((v,N,T)=>{if(w>=4)return;const k=T==="left"?N:N+1;t(j=>{const B=Xr(j,m).assignments,L=new Map;for(const S of d){const D=B.get(S.tabKey)??0,$=D>=k?D+1:D;$>0&&L.set(S.tabKey,$)}return k>0&&L.set(v,k),L}),l(j=>{const B=j.length===w?[...j]:yl(w),L=B[N]??100/w,S=Math.max(15,L/2),D=Math.max(15,L/2),$=[...B];$[N]=S,$.splice(k,0,D);const E=$.reduce((I,M)=>I+M,0);return $.map(I=>I/E*100)}),n(j=>{const B=gl(j,k);return B[k]=v,B}),a(j=>{const B=gl(j,k);return B[k]=[v],B}),r(k)},[w,t,m,d,l,n,a,r]);i.useEffect(()=>{og(e,b)||t(b)},[e,b,t]),i.useEffect(()=>{const{mapping:v,usedGroups:N}=p;n(T=>{const k=bl(T,v);return xl(T,k)?T:k}),a(T=>{const k=bl(T,v);return xl(T,k)?T:k}),r(T=>{const k=c?0:lg(T,N,v);return T===k?T:k}),l(T=>{const k=c?[]:cg(T,N,p.groupCount);return ig(T,k)?T:k})},[p,c,n,a,r,l]);const A=i.useMemo(()=>{const v=Array.from({length:w},()=>[]);for(const N of d){const T=b.get(N.tabKey)??0,k=Math.min(T,w-1);v[k].push(N)}return v},[d,b,w]),C=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:b,numGroups:w,isSplitMode:x,groupedConvs:A,moveTabToGroup:h,closeGroup:g,handleResizeStart:y,splitTabRelative:f,clearAllSplits:C}}function ja(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function ug(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function Jr(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ei(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=ja(t.channel)||ja(e.updateChannel)||ja(e.releaseChannel)||void 0,n=ug(t.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=Jr(t.targetVersion)||Jr(e.serverVersion)||void 0,o=Jr(t.minVersion)||void 0,l=Jr(t.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,t=null){return ei(e).targetVersion||t}function Pd(e){return ei(e).channel||null}function Dd(e){const t=ei(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function mg({ides:e,sendDaemonCommand:t}){const r="0.9.81",n=i.useMemo(()=>e.filter(p=>p.type!=="adhdev-daemon"?!1:fd(p,Ps(p,r))).sort((p,b)=>Number(jr(b,Ps(b,r)))-Number(jr(p,Ps(p,r)))),[r,e]),a=i.useMemo(()=>n.some(p=>jr(p,Ps(p,r))),[r,n]),o=i.useMemo(()=>n.map(p=>Ps(p,r)).find(p=>typeof p=="string"&&p.trim().length>0)||r,[r,n]),[l,c]=i.useState(!1),[d,m]=i.useState({}),u=i.useCallback(async p=>{var w,x;const b=e.find(h=>h.id===p);if(b){m(h=>({...h,[p]:"upgrading"}));try{const h=await t(p,"daemon_upgrade",Dd(b));(w=h==null?void 0:h.result)!=null&&w.upgraded||(x=h==null?void 0:h.result)!=null&&x.success?m(g=>({...g,[p]:"done"})):m(g=>({...g,[p]:"error"}))}catch{m(h=>({...h,[p]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:l,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const Ed=80;function fn(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function pg(e){return{...e,createdAt:fn(e.createdAt),updatedAt:fn(e.updatedAt,e.createdAt),lastEventAt:fn(e.lastEventAt,e.updatedAt||e.createdAt)}}function hg(e){const t=Wo(e);return t==="unknown:"?e.id:t}function fg(e){return[e.type,Uc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function xg(e,t=Ed){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=hg(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,t))}function bg(e,t){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const l=Un(a,t),c=l.inboxBucket==="needs_attention"?"needs_attention":l.inboxBucket==="task_complete"&&l.unread?"task_complete":null;if(!c)continue;const d=fn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=fg({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(pg({id:m,dedupKey:m,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Pc(a),preview:Gh(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return xg(n)}function gg(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function yg(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Ed}=e,a=i.useMemo(()=>bg(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>gg(a),[a]);return{notifications:a,unreadCount:o}}function vg({notifications:e,sendDaemonCommand:t}){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&&t(l.machineId||l.routeId,"mark_session_seen",{sessionId:l.sessionId,seenAt:c}).catch(()=>{})},[e,t]),n=i.useCallback(o=>{const l=e.find(c=>c.id===o);l!=null&&l.sessionId&&t(l.machineId||l.routeId,"mark_notification_unread",{sessionId:l.sessionId,notificationId:l.id}).catch(()=>{})},[e,t]),a=i.useCallback(o=>{const l=e.find(c=>c.id===o);l!=null&&l.sessionId&&t(l.machineId||l.routeId,"delete_notification",{sessionId:l.sessionId,notificationId:l.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const wg=i.createContext(null);function $d(){return i.useContext(wg)}function Xn(...e){const t=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const l=o.toLowerCase();t.has(l)||(t.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 jg(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const r=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function Jn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=jg(r);if(n)return n}return"C:\\"}for(const r of t){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function kg(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const r=t.includes("\\")?"\\":"/",n=t.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 Sg(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function Qn(e,t,r){const n=await e(t,"file_list_browse",{path:r}),a=Sg(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 Ng(e,t){const r={meshId:t.meshId||"",workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function Bd(e,t={}){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:Ng(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function Cg(e){if(!e||typeof e!="object")return null;const t=e,r=typeof t.instructions=="string"?t.instructions:"",n=typeof t.template=="string"?t.template:"";return!r&&!n?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function ls(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Od(e){return Pr(e)||e.tabKey||e.routeId||null}function Fd(e){const t=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!!(t&&l.includes(t)||r&&l.includes(r)||n&&o.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const o=Ht(e.conversations,n)||e.conversations.find(l=>l.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function rs(e){return String(e||"").trim()}function Wd(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function $n(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ig(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Mg(e,t){const r=rs(e.providerSessionId),n=rs(e.targetSessionId),a=t.find(o=>{const l=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(rs).filter(Boolean);return!!(r&&l.includes(r)||n&&l.includes(n))});return a?a.tabKey:n||r||null}function Ag(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=Wd(t.daemonId);if(n&&n!==e.machineId)return null;const a=rs(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=rs(e.resumeSessionId),l=rs(e.launchedSessionId),c=rs(t.providerSessionId),d=rs(t.targetSessionId);if(o&&o!==c&&o!==d||l&&l!==c&&l!==d)return null;const m=$n(e.workspacePath);if(m){const u=$n(t.workspaceName);if(u&&!Ig(u,m))return null}return Mg(t,r)}function vl(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Tg({ides:e,conversations:t,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=$n(n.workspacePath),m=e.find(p=>{var g,y,f,A;if(!p||p.type==="adhdev-daemon"||Wd(p.daemonId||p.id)!==n.machineId||(Mr(p)?"cli":$s(p)?"acp":"ide")!==n.kind)return!1;const x=String(p.agentType||p.type||"");if(n.providerType&&x!==n.providerType)return!1;if(n.resumeSessionId)return String(p.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const C=String(n.launchedSessionId||"");return[p.providerSessionId,p.sessionId,p.instanceId,p.id].map(N=>String(N||"")).filter(Boolean).includes(C)}if(d){const C=$n(p.workspace||p.runtimeWorkspaceLabel);return C?C===d:!1}return Number(p.lastUpdated||p._lastUpdate||p.timestamp||((A=(f=(y=(g=p.activeChat)==null?void 0:g.messages)==null?void 0:y.at)==null?void 0:f.call(y,-1))==null?void 0:A.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=Fd({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:t});u&&(l(),r(u))},[l,t,e,r,n]),i.useEffect(()=>ot.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=Ag(m,d,t);u&&(l(),r(u))}),[l,t,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 _g({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const l=$d(),c=i.useCallback(async(h,g)=>Qn(e,h,g),[e]),d=i.useCallback(async(h,g)=>{if(!g.trim())return{ok:!1,error:"Choose a workspace path first."};try{const y=await e(h,"workspace_add",{path:g.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(h,g,y)=>{var f;try{const A={ideType:g,enableCdp:!0};(f=y==null?void 0:y.workspacePath)!=null&&f.trim()&&(A.workspace=y.workspacePath.trim());const C=await e(h,"launch_ide",A);return!(C!=null&&C.success)&&(C==null?void 0:C.success)!==void 0?{ok:!1,error:(C==null?void 0:C.error)||"Could not launch IDE"}:(t({machineId:h,kind:"ide",providerType:g,workspacePath:(y==null?void 0:y.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(A){return{ok:!1,error:A instanceof Error?A.message:"Could not launch IDE"}}},[e,t]),u=i.useCallback(async(h,g,y,f)=>{var C,v,N;const A=Date.now();try{const T={cliType:y};(C=f==null?void 0:f.workspacePath)!=null&&C.trim()?T.dir=f.workspacePath.trim():f!=null&&f.workspaceId&&(T.workspaceId=f.workspaceId),(v=f==null?void 0:f.resumeSessionId)!=null&&v.trim()&&(T.resumeSessionId=f.resumeSessionId.trim()),Array.isArray(f==null?void 0:f.cliArgs)&&f.cliArgs.length>0&&(T.cliArgs=f.cliArgs),(N=f==null?void 0:f.initialModel)!=null&&N.trim()&&(T.initialModel=f.initialModel.trim());const k=await e(h,"launch_cli",T),j=(k==null?void 0:k.result)||k,B=(j==null?void 0:j.sessionId)||(j==null?void 0:j.id);return k!=null&&k.success&&B?(t({machineId:h,kind:g,providerType:y,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,launchedSessionId:B,startedAt:A}),{ok:!0}):k!=null&&k.success?(t({machineId:h,kind:g,providerType:y,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,startedAt:A}),{ok:!0}):{ok:!1,error:(k==null?void 0:k.error)||(j==null?void 0:j.error)||`Could not launch ${g.toUpperCase()} session`}}catch(T){return vl(T)?(t({machineId:h,kind:g,providerType:y,workspacePath:(f==null?void 0:f.workspacePath)||null,resumeSessionId:(f==null?void 0:f.resumeSessionId)||null,startedAt:A}),{ok:!0}):{ok:!1,error:T instanceof Error?T.message:`Could not launch ${g.toUpperCase()} session`}}},[r,e,t]),p=i.useCallback(async h=>{var g;if(l!=null&&l.listMeshes)return l.listMeshes(h);if(!h)return[];try{const y=await e(h,"list_meshes",{}),f=(y==null?void 0:y.result)??y;if((f==null?void 0:f.success)===!1)throw new Error((f==null?void 0:f.error)||"Could not load meshes");return(Array.isArray(f==null?void 0:f.meshes)?f.meshes:Array.isArray((g=f==null?void 0:f.result)==null?void 0:g.meshes)?f.result.meshes:[]).map(C=>{var v;return{id:String((C==null?void 0:C.id)||""),name:String((C==null?void 0:C.name)||(C==null?void 0:C.id)||"Untitled mesh"),repoIdentity:(C==null?void 0:C.repoIdentity)||(C==null?void 0:C.repo_identity)||null,workspace:Array.isArray(C==null?void 0:C.nodes)&&C.nodes.length>0?String(((v=C.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(C==null?void 0:C.nodes)?C.nodes.length:void 0,status:(C==null?void 0:C.status)||null}}).filter(C=>C.id)}catch(y){throw console.error("List meshes failed",y),y}},[l,e]),b=i.useCallback(async(h,g,y)=>{if(!g.trim())return{ok:!1,error:"Choose a mesh first."};if(l!=null&&l.launchMeshCoordinator)return l.launchMeshCoordinator(h,g,y);const f=Date.now();try{const A={meshId:g.trim()};y.trim()&&(A.cliType=y.trim());const C=await e(h,"launch_mesh_coordinator",A),v=(C==null?void 0:C.result)??C;if((v==null?void 0:v.success)===!1||(C==null?void 0:C.success)===!1){const T=String((v==null?void 0:v.code)||(C==null?void 0:C.code)||""),k=Cg((v==null?void 0:v.meshCoordinatorSetup)||(v==null?void 0:v.manualSetup)||(C==null?void 0:C.meshCoordinatorSetup)||(C==null?void 0:C.manualSetup));return{ok:!1,error:(v==null?void 0:v.error)||(C==null?void 0:C.error)||"Could not launch mesh coordinator",code:T||void 0,manualSetup:k}}const N=(v==null?void 0:v.sessionId)||(v==null?void 0:v.id);return N?r(N):t({machineId:h,kind:"cli",providerType:(v==null?void 0:v.cliType)||y.trim()||void 0,workspacePath:(v==null?void 0:v.workspace)||null,startedAt:f}),{ok:!0}}catch(A){return vl(A)?(t({machineId:h,kind:"cli",providerType:y.trim()||void 0,startedAt:f}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:"Could not launch mesh coordinator"}}},[l,r,e,t]),w=i.useCallback(async(h,g)=>{if(!h||!g)return[];try{const y=await e(h,"list_saved_sessions",{providerType:g,kind:"cli",limit:30}),f=(y==null?void 0:y.result)??y;return Array.isArray(f==null?void 0:f.sessions)?f.sessions:[]}catch(y){return console.error("List saved sessions failed",y),[]}},[e]),x=i.useCallback(async h=>{await Cd({conversation:n,mode:h,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:p,handleLaunchMeshCoordinator:b,handleListMachineSavedSessions:w,setActiveCliViewMode:x}}function Lg(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 Rg(e,t,r=Date.now()){return!e||!Lg(t)?null:{tabKey:e,nonce:r}}function Pg({isMobile:e,conversations:t,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:l}){const[c,d]=i.useState(null),[m,u]=i.useState(null),p=i.useMemo(()=>{var g,y;if(!e){if(c){const f=t.find(A=>A.tabKey===c);if(f)return f}return r[0]}const h=n[a];if(h){const f=t.find(A=>A.tabKey===h);if(f)return f}return((g=o[a])==null?void 0:g[0])||((y=o[0])==null?void 0:y[0])},[t,c,a,n,o,e,r]),b=i.useCallback(h=>{d(h)},[]),w=i.useCallback(h=>{d(h.tabKey),l(g=>{const y=new URLSearchParams(g),f=qh(h);return f?y.set("activeTab",f):y.delete("activeTab"),y},{replace:!0})},[l]),x=i.useCallback((h,g)=>{const y=Rg(h,g);y&&u(y)},[]);return{activeConv:p,openDesktopConversation:w,requestScrollToBottom:x,scrollToBottomRequest:m,setDesktopActiveTab:b}}function Dg(e){const t=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?t===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 Eg(e){const t=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&t&&t!==r),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function $g({activeConv:e,isMobile:t,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(t){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=In(e,r),p=Eg({tabKey:e.tabKey,historySessionId:Pr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ws(e),liveState:u}),b=p.autoReadKey,w=Dg({autoReadKey:b,shouldMarkSeen:p.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!p.shouldMarkSeen){w.shouldCancelPending&&m(),a.current=b;return}if(!w.shouldSchedule)return;w.shouldCancelPending&&m();const x=()=>{if(document.visibilityState!=="visible"||a.current===b)return;a.current=b,o.current=null,l.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const g=p.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:g,completionMarker:p.completionMarker}).catch(()=>{})};if(o.current=w.nextPendingKey,document.visibilityState==="visible"){l.current=setTimeout(x,1500);const g=()=>{document.visibilityState!=="visible"&&l.current&&(clearTimeout(l.current),l.current=null)};d.current=g,document.addEventListener("visibilitychange",g);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(x,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,r,n]),i.useEffect(()=>()=>{l.current&&clearTimeout(l.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function ka(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function Bg({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:l,setClearedTabs:c,setSearchParams:d}){var M;const[m,u]=i.useState(!1),[p,b]=i.useState([]),[w,x]=i.useState(()=>Nt()),[h,g]=i.useState(!1),[y,f]=i.useState(null),A=i.useRef(null),C=i.useMemo(()=>r||t||e,[e,r,t]),v=!!C&&at(C)&&!st(C),N=i.useMemo(()=>{if(!C||!v)return null;const F=C.daemonId||C.routeId||"",P=Yt(C),R=ka(C);return`${F}:${P}:${C.providerSessionId||""}:${R}`},[C,v]),T=i.useMemo(()=>!C||!v?"":ka(C),[C,v]),{isCreatingChat:k,isRefreshingHistory:j,handleSwitchSession:B,handleNewChat:L,handleRefreshHistory:S}=Rd({sendDaemonCommand:a,activeConv:C,chats:(M=n.find(F=>F.id===(C==null?void 0:C.routeId)))==null?void 0:M.chats,updateRouteChats:o,setToasts:l,setClearedTabs:c}),D=i.useCallback(()=>{u(!0)},[]),$=i.useCallback(()=>{u(!1)},[]),E=i.useCallback(async()=>{if(!(!C||!v||h)){g(!0);try{const F=C.daemonId||C.routeId,P=Yt(C),R=ka(C),K=await a(F,"list_saved_sessions",{agentType:P,providerType:P,kind:"cli",limit:50,...C.providerSessionId?{providerSessionId:C.providerSessionId}:{},...R?{workspace:R}:{}}),V=(K==null?void 0:K.result)??K;b(Array.isArray(V==null?void 0:V.sessions)?V.sessions:[])}catch(F){console.error("Refresh saved sessions failed",F),b([])}finally{g(!1)}}},[C,h,v,a]);i.useEffect(()=>{if(!m){A.current=null;return}if(!v){A.current=null,b([]),g(!1);return}!N||h||A.current!==N&&(A.current=N,E())},[E,m,h,v,N]);const I=i.useCallback(async F=>{if(!C||!v||!F.providerSessionId||!F.workspace)return;const P=C.daemonId||C.routeId,R=Yt(C);try{f(F.providerSessionId);const K=await a(P,"launch_cli",{cliType:R,dir:F.workspace,resumeSessionId:F.providerSessionId,initialModel:Cc(F.summaryMetadata,"model",{preferShortValue:!0})||void 0}),V=(K==null?void 0:K.result)??K,te=typeof(V==null?void 0:V.sessionId)=="string"?V.sessionId:typeof(V==null?void 0:V.id)=="string"?V.id:"";te&&d(ie=>{const J=new URLSearchParams(ie);return J.set("activeTab",te),J},{replace:!0}),$()}catch(K){console.error("Resume saved session failed",K)}finally{f(null)}},[$,C,v,a,d]);return{historyModalOpen:m,openHistoryModal:D,closeHistoryModal:$,historyTargetConv:C,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:k,isHistoryRefreshingHistory:j,handleHistorySwitchSession:B,handleHistoryNewChat:L,handleHistoryRefresh:S,savedHistorySessions:p,savedHistoryFilters:w,setSavedHistoryFilters:x,missingWorkspaceResumePath:T,isSavedHistoryLoading:h,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:E,handleResumeSavedHistorySession:I}}function Og({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}){const[d,m]=i.useState(null),[u,p]=i.useState(null),b=i.useMemo(()=>{if(e||!n)return null;const y=c(n);return y&&!at(y)&&!st(y)?y:null},[e,n,c]),w=i.useMemo(()=>{const y=d==null?void 0:d.routeId;if(!y)return null;const f=d!=null&&d.tabKey?o.find(A=>A.tabKey===d.tabKey):a?o.find(A=>A.tabKey===a):null;return(f==null?void 0:f.routeId)===y?f:Ht(o,y)},[o,d,a]),x=i.useMemo(()=>{if(w)return l.find(y=>y.id===w.routeId)},[l,w]);i.useEffect(()=>{b&&(m({routeId:b.routeId,tabKey:zi(b)}),p(b),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,b]);const h=i.useCallback(y=>{y&&(m({routeId:y.routeId,tabKey:zi(y)}),p(y))},[]),g=i.useCallback(()=>{m(null),p(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:x,remoteDialogActiveConv:u,setRemoteDialogActiveConv:p,openRemoteDialog:h,closeRemoteDialog:g}}function Fg({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:b,setRemoteDialogActiveConv:w,openRemoteDialog:x,closeRemoteDialog:h}=Og({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}),[g,y]=i.useState(!1),[f,A]=i.useState(null),C=i.useCallback(async T=>{const k=T||d;!k||!at(k)&&!st(k)||(A(k),y(!0))},[d]),v=i.useCallback(()=>{y(!1),A(null)},[]),N=i.useCallback(async T=>{const k=f||d;if(!k||!at(k)&&!st(k)){v();return}y(!1);try{const j=Yt(k),B=k.routeId||k.daemonId||"";await m(B,"stop_cli",{cliType:j,targetSessionId:k.sessionId,mode:T})}catch(j){console.error("Stop CLI failed:",j)}finally{A(null)}},[d,v,f,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:p,remoteDialogActiveConv:b,setRemoteDialogActiveConv:w,openRemoteDialog:x,closeRemoteDialog:h,cliStopDialogOpen:g,cliStopTargetConv:f,requestCliStop:C,cancelCliStop:v,confirmCliStop:N}}function Hd({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var A,C;const l=Ys(),c=As(e),d=o?null:Rc(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,p=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),b=Ks(e),w=Vh(e),x=(A=e.settings)==null?void 0:A.meshNodeFor,h=e.meshQueueStats,g=(C=e.settings)==null?void 0:C.meshCoordinatorFor;if(!m&&!u&&!p&&!d&&!x&&!h)return null;const y=i.useCallback(()=>{if(n){n();return}c&&l("/dashboard",{state:{openMachineId:c}})},[c,l,n]),f=i.useCallback(()=>{if(r){r();return}const v=Od(e);v&&l(ls(v))},[e,l,r]);return s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[m&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:f,title:w,children:[s.jsx(Rt,{size:12}),s.jsx("span",{children:w})]}):s.jsxs("span",{className:"conversation-meta-chip",title:w,children:[s.jsx(Rt,{size:12}),s.jsx("span",{children:w})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[s.jsx(Hs,{size:12}),s.jsx("span",{children:b})]}),p&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:b,children:[s.jsx(Hs,{size:12}),s.jsx("span",{children:b})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:d,children:[s.jsx(os,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(os,{size:12}),s.jsx("span",{children:d})]})),x&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(os,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),g&&h&&s.jsxs("span",{className:`conversation-meta-chip ${h.pending>0?"is-active":""}`,style:h.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${h.pending} pending, ${h.assigned} assigned, ${h.completed} completed, ${h.failed} failed`,children:[s.jsx(Vm,{size:12}),s.jsxs("span",{children:[h.pending," Pending"]})]})]})}function Sa(e,t=!0){return(e??!0)&&t}const ti=i.memo(function({activeConv:t,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:l,handleRelaunch:c,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:p,isFocusingAgent:b,actionLogs:w,userName:x,scrollToBottomRequestNonce:h,isInputActive:g=!0,isVisible:y=!0}){const f=n,A=!n,C=Sa(y,f),v=Sa(y,A),N=Sa(y),T=vd(t),k=T.status||T.modalMessage||T.modalButtons?{...t,...T.status?{status:T.status}:{},...T.modalMessage!==void 0?{modalMessage:T.modalMessage}:{},...T.modalButtons!==void 0?{modalButtons:T.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(kc,{activeConv:k,onModalButton:l}),s.jsx(Hd,{conversation:k,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),k.transport!=="pty"&&k.transport!=="acp"&&k.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.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:[s.jsx("span",{className:"text-sm",children:s.jsx(Ir,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.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,k.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:f?"visible":"hidden",pointerEvents:f?"auto":"none"},children:s.jsx(lx,{activeConv:k,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:C,isInputActive:g&&C})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:A?"visible":"hidden",pointerEvents:A?"auto":"none"},children:s.jsx(io,{activeConv:k,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:p,isFocusingAgent:b,actionLogs:w,userName:x,scrollToBottomRequestNonce:h,isInputActive:g&&v,isVisible:v})})]}):s.jsx(io,{activeConv:k,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:p,isFocusingAgent:b,actionLogs:w,userName:x,scrollToBottomRequestNonce:h,isInputActive:g&&N,isVisible:N})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function Wg({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:l,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:p,onOpenHistory:b,onOpenRemote:w,onOpenMeshGraph:x,onStopCli:h,cliViewMode:g,onSetCliViewMode:y,handleSendChat:f,handleFocusAgent:A,handleModalButton:C,handleRelaunch:v}){var L;const N=i.useRef(null),T=at(e)&&!t,k=T&&g==="terminal",j=!!e.daemonId&&typeof((L=e.settings)==null?void 0:L.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 s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${B} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.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:s.jsx(So,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:ut(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(Hd,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>p(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[T&&g&&s.jsx(Ko,{mode:g,onChange:y,compact:!0}),T&&h&&s.jsx("button",{onClick:()=>{h(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:s.jsx(jt,{size:14})}),j&&x&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(ns,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",children:s.jsx(No,{size:14})}),!t&&!T&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:s.jsx(Rt,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(ti,{activeConv:e,clearToken:0,isCliTerminal:k,ideEntry:n,terminalRef:N,handleModalButton:C,handleRelaunch:v,handleSendChat:f,isSendingChat:l,sendFeedbackMessage:c,handleFocusAgent:A,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const Na={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 Hg(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Kd(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),l=e==="unix"?"unix":r;i.useEffect(()=>{t(Hg())},[]);const c=i.useCallback(()=>{navigator.clipboard.writeText(Na[l].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[l]);return s.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:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.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:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.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:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.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"}),s.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"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Na[l].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Na[l].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Ud({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:Rt},{key:"chats",label:"Chats",icon:Zt}];return s.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:s.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 s.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:()=>t(n),type:"button","aria-pressed":l,children:[s.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:s.jsx(o,{size:15})}),s.jsx("span",{children:a})]},n)})})})}function Qr({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Ts({children:e,className:t=""}){return s.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)] ${t}`,children:e})}function mr({icon:e,title:t,subtitle:r,children:n}){return s.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:[s.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}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Kg({conversation:e,onCancel:t,onConfirm:r}){const n=ut(e),a=Cs(e);return s.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:[s.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:t}),s.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:[s.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),s.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."})]}),s.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:t,"aria-label":"Cancel hide chat",children:s.jsx(jt,{size:16})})]}),s.jsx("div",{className:"px-4 py-4",children:s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[s.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),s.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),s.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:[s.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:t,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function Zr({item:e,type:t,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:l}){var B;const c=t==="needs_attention"||t==="task_complete",d=t==="working",m=t==="earlier",u=t==="task_complete",{isReconnecting:p,isConnecting:b}=Xs(e.conversation),w=ut(e.conversation),x=Cs(e.conversation),h=Zc(e.conversation,{requiresAction:t==="needs_attention"}),g=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",f=m?"text-text-secondary":"text-text-primary",A=m?"text-text-muted":"text-text-secondary",C=m?"text-text-secondary opacity-80":"text-text-muted",v=m?"text-text-muted opacity-80":"text-text-muted",N=!d&&!u,T=!!e.conversation.daemonId&&typeof((B=e.conversation.settings)==null?void 0:B.meshCoordinatorFor)=="string"&&e.conversation.settings.meshCoordinatorFor.length>0,k="text-[color:var(--status-warning)]",j=L=>{if(!l)return;L.preventDefault(),L.stopPropagation();const S=l==null?void 0:l(e.conversation);Promise.resolve(S).catch(D=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",D)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${g}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[c||d?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.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(w)}),a&&s.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:L=>{L.preventDefault(),L.stopPropagation(),a()},"aria-label":`Hide ${w}`,title:"Hide conversation",children:[s.jsx(Co,{size:11}),s.jsx("span",{children:"Hide"})]}),T&&o&&s.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:L=>{L.preventDefault(),L.stopPropagation(),o(e.conversation)},"aria-label":`Open mesh graph for ${w}`,title:"Open live repo mesh graph",children:[s.jsx(ns,{size:11}),s.jsx("span",{children:"Graph"})]})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:j,type:"button",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${f}`,children:w}),N&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${v}`,children:jc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${A}`,children:[s.jsx("span",{className:"truncate",children:x}),s.jsx(zs,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),p?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${k} animate-pulse`,children:"Reconnecting…"})]}):b?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):h==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:k,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${C}`,children:e.preview})]}),c&&!u&&s.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),u&&s.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&&s.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 wl({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.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 Ug({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:l,getAvatarText:c,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:p,onHideConversation:b,onOpenMeshGraph:w,onOpenNewSession:x,onOpenMachine:h,onOpenSettings:g,onSectionChange:y,wsStatus:f="connected",isStandalone:A=!1,onCollectChatDebugBundle:C}){const[v,N]=i.useState(null),T=f==="disconnected"||f==="reconnecting"||f==="offline"||f==="auth_failed",k=l.length>0,j=t.length>0||r.length>0||n.length>0||a.length>0,B=e==="machines"?"Machines":"Chats",L=A?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",S=A?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",D=i.useCallback(async I=>{const M=Us(I);if(!M)return;const F=Array.isArray(I.messages)?I.messages:[],P=Oc({activeConv:I,visibleMessages:F,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:F.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),R=await m(M,"get_chat_debug_bundle",{...fs(I),delivery:"daemon_file",frontendSnapshot:P}),K=_n(R),V=Hc(K),te=await Wc(V);te==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ot.showToast(Fc(K,{locatorCopyStatus:te}),te==="failed"?"warning":"success")},[d,m]),$=C||D,E=i.useCallback(()=>{v&&(b==null||b(v),N(null))},[v,b]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${L}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:B}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||r.length>0)&&s.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:[s.jsx(Hn,{size:13}),s.jsx("span",{children:t.length+r.length})]}),s.jsx("button",{onClick:g,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:s.jsx(Wn,{size:18})})]})]})}),s.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] ${S}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:T?s.jsx(mr,{icon:s.jsx(wl,{}),title:f==="offline"?"Network offline":f==="auth_failed"?"Session expired":"Reconnecting",subtitle:f==="offline"?"Waiting for network…":f==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):l.length===0?s.jsx(mr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:A?"Waiting for your daemon":"Connect your machines",subtitle:A?"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:!A&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Kd,{})})}):s.jsx(Ts,{children:l.map((I,M)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${M>0?"border-t border-border-subtle/70":""}`,onClick:()=>h(I.id),type:"button",children:[s.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(I.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:I.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:I.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[I.unread," new"]}):I.total>0?`${I.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:I.subtitle}),I.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[I.total," chat",I.total!==1?"s":"",I.unread>0?` · ${I.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},I.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Qr,{title:"Needs attention",className:"mb-0"}),s.jsx(Ts,{children:t.map((I,M)=>s.jsx("div",{className:M>0?"border-t border-border-subtle/70":"",children:s.jsx(Zr,{item:I,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:b?()=>N(I.conversation):void 0,onOpenMeshGraph:w,onCollectChatDebugBundle:$})},I.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Qr,{title:"Task complete",className:"mb-0 mt-2"}),s.jsx(Ts,{children:r.map((I,M)=>s.jsx("div",{className:M>0?"border-t border-border-subtle/70":"",children:s.jsx(Zr,{item:I,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:b?()=>N(I.conversation):void 0,onOpenMeshGraph:w,onCollectChatDebugBundle:$})},I.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Qr,{title:"Working now",className:"mb-0 mt-2"}),s.jsx(Ts,{children:n.map((I,M)=>s.jsx("div",{className:M>0?"border-t border-border-subtle/70":"",children:s.jsx(Zr,{item:I,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:b?()=>N(I.conversation):void 0,onOpenMeshGraph:w,onCollectChatDebugBundle:$})},I.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(Qr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(Ts,{children:a.map((I,M)=>s.jsx("div",{className:M>0?"border-t border-border-subtle/70":"",children:s.jsx(Zr,{item:I,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:b?()=>N(I.conversation):void 0,onOpenMeshGraph:w,onCollectChatDebugBundle:$})},I.conversation.tabKey))}):j?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):T?s.jsx(mr,{icon:s.jsx(wl,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):k?s.jsx(mr,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Zt,{size:20})}),title:"No conversations yet",subtitle:sd,children:x&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:x,"aria-label":Vt,title:Vt,children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:Vt})]})}):s.jsx(mr,{icon:s.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&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(Ts,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),s.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:p,children:"Restore all"})]})})})]}),e==="chats"&&x&&j&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:x,"aria-label":Vt,title:Vt,children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),v&&s.jsx(Kg,{conversation:v,onCancel:()=>N(null),onConfirm:E}),s.jsx(Ud,{section:e,onSectionChange:y})]})}function zg(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 zd(e){const t=[e.workspace||"Workspace unknown"],r=Ns(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=zg(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Zn({title:e,description:t,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:l="Use this folder",onClose:c,onNavigate:d,onConfirm:m}){const[u,p]=i.useState(r);i.useEffect(()=>{p(r)},[r]);const b=kg(r),w=u.trim();return s.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:s.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:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.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:s.jsx(jt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.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:()=>{!b||a||d(b)},disabled:!b||a,children:[s.jsx(So,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:x=>p(x.target.value),onKeyDown:x=>{x.key!=="Enter"||!w||a||(x.preventDefault(),d(w))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!w||a||d(w)},disabled:!w||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):n.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:n.map(x=>s.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(x.path),children:[s.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:s.jsx(Ss,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:x.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:x.path})]})]},x.path))})}),s.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:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(w||r),disabled:!w&&!r||a,children:l})]})]})})}function si({title:e,description:t,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:l="Launch",busyLabel:c="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:p,showModelInput:b,modelValue:w,onModelChange:x,historyProviderNode:h,onConfirm:g,onCancel:y}){const f=n==null?void 0:n.find(A=>A.key===a);return s.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:s.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:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.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:s.jsx(jt,{size:16})})]}),s.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&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),s.jsx("select",{value:a||"",onChange:A=>o(A.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(A=>s.jsx("option",{value:A.key,children:A.label},A.key))}),(f==null?void 0:f.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:f.description})]}),h,r.map(A=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:A.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:A.value})]},`${A.label}:${A.value}`)),b&&x&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),s.jsx("input",{type:"text",value:w||"",onChange:A=>x(A.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&&p&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),s.jsx("input",{type:"text",value:u||"",onChange:A=>p(A.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})]})]}),s.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:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:d,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:g,disabled:d,children:[s.jsx(Mo,{size:14}),d?c:l]})]})]})})}function jl(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function js(e){const{machine:t,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 t.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${jl(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const l=(r==null?void 0:r.trim())||"",c=l?(t.workspaces||[]).find(d=>d.path===l):null;if(l&&!c&&o.push({key:`custom:${l}`,label:jl(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 Gg(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Vg(e){return[Gg(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function qg(e){return e.lastLaunchedAt?Kn(e.lastLaunchedAt):""}function Gd(e){return{metaText:Vg(e),updatedLabel:qg(e)}}function Ca(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Yg({selectedMachineEntry:e,cliProviders:t,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var tt,ct,mt,pt;const l=Rr(),[c,d]=i.useState(!1),m=(((tt=e.detectedIdes)==null?void 0:tt.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(O=>({id:O.id,path:O.path,label:O.label})),[e]),p=e.defaultWorkspaceId||null,[b,w]=i.useState(p||((ct=u[0])==null?void 0:ct.id)||""),[x,h]=i.useState(""),[g,y]=i.useState(""),[f,A]=i.useState([]),[C,v]=i.useState(!1),[N,T]=i.useState(""),[k,j]=i.useState(!1),[B,L]=i.useState(Ca(m,t.length,r.length)),S=i.useRef(null),[D,$]=i.useState(null),E=i.useRef("__home__"),[I,M]=i.useState("__home__"),[F,P]=i.useState(""),[R,K]=i.useState(""),[V,te]=i.useState(""),[ie,J]=i.useState([]),[me,je]=i.useState(()=>Nt().textQuery),[ke,q]=i.useState(()=>Nt().workspaceQuery),[ge,fe]=i.useState(()=>Nt().modelQuery),[we,xe]=i.useState(()=>Nt().resumableOnly),[Ne,Q]=i.useState(()=>Nt().sortMode),[he,oe]=i.useState(!1),[ue,le]=i.useState(!1),de=i.useRef(null),Z=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&l(e.id,{minFreshMs:3e4}).catch(()=>{})},[l,e]);const ve=b==="__custom__"?x.trim():((mt=u.find(O=>O.id===b))==null?void 0:mt.path)||"",ce=b==="__custom__"&&!!ve&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),pe=b!=="__custom__"&&((pt=u.find(O=>O.id===b))==null?void 0:pt.path)||"",ae=i.useMemo(()=>(e.recentLaunches||[]).map(O=>O.workspace),[e]),Ie=i.useCallback(async O=>{v(!0),T("");try{const be=await a(O);y(be.path),h(be.path),A(be.directories)}catch(be){T(be instanceof Error?be.message:"Could not load folder")}finally{v(!1)}},[a]),Ce=i.useCallback(()=>{var be;w("__custom__"),j(!0);const O=Jn(e.platform,Xn(x.trim(),pe,ae,e.defaultWorkspacePath,(be=u.find(Te=>Te.id===p))==null?void 0:be.path,u.map(Te=>Te.path)));Ie(O)},[x,p,Ie,ae,pe,e.platform,u]),_e=i.useCallback(O=>{if(O!=null&&O.workspaceId){w(O.workspaceId),h("");return}if(O!=null&&O.workspacePath){w("__custom__"),h(O.workspacePath);return}w(""),h("")},[]),H=i.useCallback(O=>{if(w(O),O==="__custom__"){Ce();return}h("")},[Ce]),Me=i.useCallback(O=>{w("__custom__"),h(O)},[]),Ae=i.useCallback((O,be)=>{S.current=be,E.current=O.selectedWorkspaceKey||"__home__",M(O.selectedWorkspaceKey||"__home__"),P(O.initialArgs||""),K(O.initialModel||""),te(""),J([]);const Te=O.providerType?`${e.id}:${O.providerType}`:null;if(yx(Z.current,Te)){const Be=Nt();je(Be.textQuery),q(Be.workspaceQuery),fe(Be.modelQuery),xe(Be.resumableOnly),Q(Be.sortMode)}Z.current=Te,$(O),O.providerType&&o&&(oe(!0),o(O.providerType).then(Be=>J(Be||[])).catch(Be=>console.warn("Failed to load saved sessions",Be)).finally(()=>oe(!1)))},[o,e.id]),He=i.useMemo(()=>rd(ie,{textQuery:me,workspaceQuery:ke,modelQuery:ge,resumableOnly:we,sortMode:Ne}),[ge,we,ie,Ne,me,ke]);i.useEffect(()=>{V&&(He.some(O=>O.providerSessionId===V)||te(""))},[He,V]);const Ge=i.useCallback(()=>{S.current&&(le(!0),S.current().finally(()=>{S.current=null,le(!1),$(null)}))},[]),Xe=i.useCallback(()=>{S.current=null,$(null)},[]),Ye=i.useCallback(O=>{E.current=O,M(O)},[]);return i.useEffect(()=>{var O;de.current!==e.id&&(de.current=e.id,w(p||((O=u[0])==null?void 0:O.id)||"__custom__"),h(""),y(""),A([]),T(""),j(!1),je(Nt().textQuery),q(Nt().workspaceQuery),fe(Nt().modelQuery),xe(Nt().resumableOnly),Q(Nt().sortMode),Z.current=null,L(Ca(m,t.length,r.length)))},[r.length,t.length,p,m,e.id,u]),i.useEffect(()=>{var O;b!=="__custom__"&&(b&&u.some(be=>be.id===b)||w(p||((O=u[0])==null?void 0:O.id)||"__custom__"))},[p,b,u]),i.useEffect(()=>{B==="ide"&&m||B==="cli"&&t.length>0||B==="acp"&&r.length>0||L(Ca(m,t.length,r.length))},[B,r.length,t.length,m]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:p,workspaceChoice:b,customWorkspacePath:x,browseCurrentPath:g,browseDirectories:f,browseBusy:C,browseError:N,browseDialogOpen:k,activeLauncherKind:B,launchConfirm:D,launchConfirmWorkspaceKeyRef:E,launchConfirmWorkspaceKey:I,launchConfirmArgs:F,launchConfirmModel:R,launchConfirmResumeId:V,launchConfirmSavedSessions:ie,launchConfirmTextFilter:me,launchConfirmWorkspaceFilter:ke,launchConfirmModelFilter:ge,launchConfirmResumableOnly:we,launchConfirmSortMode:Ne,filteredLaunchConfirmSavedSessions:He,launchConfirmSessionsLoading:he,launchConfirmBusy:ue,resolvedWorkspacePath:ve,canCreateMissingWorkspace:ce,openBrowseDialog:Ce,loadBrowsePath:Ie,handleWorkspaceChoiceChange:H,chooseCustomWorkspacePath:Me,setCustomWorkspacePath:h,setBrowseDialogOpen:j,setActiveLauncherKind:L,openLaunchConfirm:Ae,handleConfirmLaunch:Ge,closeLaunchConfirm:Xe,setWorkspaceSelectionFromOption:_e,setLaunchConfirmWorkspaceKeyAndSync:Ye,setLaunchConfirmArgs:P,setLaunchConfirmModel:K,setLaunchConfirmResumeId:te,setLaunchConfirmTextFilter:je,setLaunchConfirmWorkspaceFilter:q,setLaunchConfirmModelFilter:fe,setLaunchConfirmResumableOnly:xe,setLaunchConfirmSortMode:Q}}function Xg({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:l,machineAction:c,isStandalone:d,section:m,showBottomNav:u,onBack:p,onSectionChange:b,onOpenConversation:w,onOpenRecent:x,onOpenMachineDetails:h,onMachineUpgrade:g,onLaunchDetectedIde:y,onAddWorkspace:f,onBrowseDirectory:A,onLaunchWorkspaceProvider:C,onListSavedSessions:v}){const N=I=>I==="ide"?"IDE":I==="cli"?"CLI":"ACP",T=r.slice(0,4),k=t.slice(0,3),j=Yg({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:A,onListSavedSessions:v}),B=i.useMemo(()=>T.map(I=>{const{metaText:M,updatedLabel:F}=Gd(I);return{key:`recent-launch:${I.id}`,primary:I.label,secondary:M,updatedLabel:F,onClick:()=>{const{options:P,selectedKey:R}=js({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspacePath:I.workspace});j.openLaunchConfirm({title:I.kind==="ide"?bs("restart-ide",I.label):I.providerSessionId?Go(I.label):bs("start-fresh",I.label),description:I.kind==="ide"?gs("restart-ide"):I.providerSessionId?Vo():gs("start-fresh"),confirmLabel:I.kind==="ide"?Gs("restart-ide"):I.providerSessionId?Rn(!0):Gs("start-fresh"),busyLabel:I.kind==="ide"?Vs("restart-ide"):I.providerSessionId?Uo(!0):Vs("start-fresh"),workspaceOptions:P,selectedWorkspaceKey:R,details:[{label:"Mode",value:N(I.kind)},...I.providerType?[{label:"Provider",value:I.providerType}]:[]]},async()=>{const K=P.find(V=>V.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(K),await x({...I,workspace:(K==null?void 0:K.workspacePath)??null})})}}}),[j,x,T]),L=i.useMemo(()=>k.map(I=>({key:`recent-chat:${I.conversation.tabKey}`,primary:ut(I.conversation),secondary:nx(I.conversation,{timestampLabel:I.timestamp?jc(I.timestamp):null}),unread:I.unread,onClick:()=>w(I.conversation)})),[w,k]),S=j.showAllRecent?B:B.slice(0,4),D=B.length>0,$=L.length>0,E=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${E} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(So,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Lt(e,{fallbackId:e.id})}),s.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}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[$&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.map(I=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${I.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:I.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:I.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.key))})]}),D&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:S.map(I=>s.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:I.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:I.primary}),I.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:I.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.key))}),B.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.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:()=>j.setShowAllRecent(I=>!I),children:j.showAllRecent?"Show fewer":`Show ${B.length-4} more`})})]}),(j.hasIdeOptions||n.length>0||a.length>0)&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:s.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:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),s.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),s.jsx("select",{value:j.workspaceChoice,onChange:I=>j.handleWorkspaceChoiceChange(I.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:j.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[j.workspaceRows.map(I=>s.jsxs("option",{value:I.id,children:[I.id===j.defaultWorkspaceId?"⭐ ":"",zn(I.path,I.label)||I.path]},I.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),j.workspaceChoice==="__custom__"&&s.jsxs("div",{className:"flex flex-col gap-2.5",children:[s.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start gap-3",children:[s.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:s.jsx(Ss,{size:17})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),s.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:j.resolvedWorkspacePath||j.browseCurrentPath||"No folder selected yet."})]})]})}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.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:j.openBrowseDialog,children:"Select workspace…"}),s.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:()=>{j.resolvedWorkspacePath&&f(j.resolvedWorkspacePath)},disabled:!j.resolvedWorkspacePath||j.browseBusy,children:"Save as workspace"})]})]}),j.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[j.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${j.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:()=>j.setActiveLauncherKind("acp"),children:"ACP"})]}),j.activeLauncherKind&&s.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[s.jsx("div",{className:"text-xs font-bold text-text-secondary",children:j.activeLauncherKind==="ide"?"Choose an IDE":j.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:j.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(I=>s.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:M,selectedKey:F}=js({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${I.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:M,selectedWorkspaceKey:F,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:I.name}]},async()=>{const P=M.find(R=>R.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(P),y(I.type,{workspacePath:(P==null?void 0:P.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:I.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},I.type)):(j.activeLauncherKind==="cli"?n:a).map(I=>s.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 M=j.activeLauncherKind==="cli"?"cli":"acp",{options:F,selectedKey:P}=js({machine:{workspaces:j.workspaceRows,defaultWorkspaceId:j.defaultWorkspaceId},currentWorkspaceId:j.workspaceChoice!=="__custom__"?j.workspaceChoice:null,currentWorkspacePath:j.resolvedWorkspacePath});j.openLaunchConfirm({title:`Launch ${I.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${M.toUpperCase()}`,workspaceOptions:F,selectedWorkspaceKey:P,details:[{label:"Mode",value:M.toUpperCase()},{label:"Provider",value:I.displayName}],showArgsInput:!0,showModelInput:M==="acp",initialArgs:"",initialModel:"",providerType:I.type},async()=>{const R=F.find(K=>K.key===j.launchConfirmWorkspaceKeyRef.current);j.setWorkspaceSelectionFromOption(R),C(M,I.type,{workspaceId:(R==null?void 0:R.workspaceId)??null,workspacePath:(R==null?void 0:R.workspacePath)??null,args:j.launchConfirmArgs,model:j.launchConfirmModel,resumeSessionId:j.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[I.icon?`${I.icon} `:"",I.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:j.resolvedWorkspacePath||"Use selected workspace"})]},I.type))})]}),c.message&&s.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,j.canCreateMissingWorkspace&&s.jsx("div",{className:"mt-2",children:s.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:()=>f(j.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.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:g,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",l]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.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:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),j.browseDialogOpen&&s.jsx(Zn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:j.browseCurrentPath,directories:j.browseDirectories,busy:j.browseBusy,error:j.browseError,confirmLabel:"Use this folder",onClose:()=>j.setBrowseDialogOpen(!1),onNavigate:I=>{j.loadBrowsePath(I)},onConfirm:I=>{j.chooseCustomWorkspacePath(I),j.setBrowseDialogOpen(!1)}}),j.launchConfirm&&s.jsx(si,{title:j.launchConfirm.title,description:j.launchConfirm.description,details:j.launchConfirm.details,workspaceOptions:j.launchConfirm.workspaceOptions,selectedWorkspaceKey:j.launchConfirmWorkspaceKey,onWorkspaceChange:j.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:j.launchConfirm.providerType?Rn(!!j.launchConfirmResumeId):j.launchConfirm.confirmLabel,busyLabel:j.launchConfirm.providerType?void 0:j.launchConfirm.busyLabel,busy:j.launchConfirmBusy,showArgsInput:j.launchConfirm.showArgsInput,argsValue:j.launchConfirmArgs,onArgsChange:j.setLaunchConfirmArgs,showModelInput:j.launchConfirm.showModelInput,modelValue:j.launchConfirmModel,onModelChange:j.setLaunchConfirmModel,historyProviderNode:j.launchConfirm.providerType&&(j.launchConfirmSessionsLoading||j.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),j.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:zo()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:j.launchConfirmTextFilter,onChange:I=>j.setLaunchConfirmTextFilter(I.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:j.launchConfirmWorkspaceFilter,onChange:I=>j.setLaunchConfirmWorkspaceFilter(I.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:j.launchConfirmModelFilter,onChange:I=>j.setLaunchConfirmModelFilter(I.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:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),s.jsxs("select",{value:j.launchConfirmSortMode,onChange:I=>j.setLaunchConfirmSortMode(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:j.launchConfirmResumableOnly,onChange:I=>j.setLaunchConfirmResumableOnly(I.target.checked),disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:j.launchConfirmResumeId,onChange:I=>j.setLaunchConfirmResumeId(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:j.launchConfirmBusy||j.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:jx()}),j.filteredLaunchConfirmSavedSessions.map(I=>s.jsxs("option",{value:I.providerSessionId,disabled:!I.canResume,children:[I.title||I.providerSessionId," ",I.canResume?"":"(workspace missing)"]},I.providerSessionId))]}),!j.launchConfirmSessionsLoading&&j.launchConfirmSavedSessions.length>0&&j.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),j.launchConfirmResumeId&&(()=>{const I=j.filteredLaunchConfirmSavedSessions.find(F=>F.providerSessionId===j.launchConfirmResumeId);if(!I)return null;const M=zd(I);return s.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:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:M.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:M.providerSessionId}),s.jsx("div",{className:"mt-1",children:M.metaLine}),M.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:M.updatedLabel}),M.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:M.preview})]})})()]}),onConfirm:j.handleConfirmLaunch,onCancel:j.closeLaunchConfirm}),u&&s.jsx(Ud,{section:m,onSectionChange:b})]})}function xn(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Jg(e,t=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=t.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:xn(e)}function Qg(e){var r;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":"Offline"}function Zg(e,t){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})):t.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var l;const a=Mr(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)||(Mr(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 ey(e,t){const r=new Map;for(const n of t){const a=As(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((p,b)=>b.timestamp-p.timestamp)[0]||null,l=(o==null?void 0:o.conversation)||null,c=so(n),d=a.filter(p=>p.unread||p.requiresAction).length,m=Qg(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Lt(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?ax(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 ty(e){return e==="chat"}function en(e,t){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}`,t)}catch{}}function sy({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:l,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:b,onRequestedMobileSectionConsumed:w,setSelectedTabKey:x,setScreen:h,setSelectedMachineId:g,setSection:y,setMachineBackTarget:f,resetMachineAction:A}){const C=i.useRef(null),v=i.useCallback(N=>{if(!(N!=null&&N.sessionId))return;const T=In(N,l),k=Math.max(Date.now(),ws(N),T.lastUpdated||0);en("mark_read:start",{tabKey:N.tabKey,sessionId:N.sessionId,displayPrimary:ut(N),inboxBucket:T.inboxBucket,unread:T.unread,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,activityAt:ws(N),readAt:k}),c(As(N)||N.routeId,"mark_session_seen",{sessionId:N.sessionId,providerSessionId:N.providerSessionId,seenAt:k,completionMarker:T.completionMarker}).then(j=>{en("mark_read:result",{tabKey:N.tabKey,sessionId:N.sessionId,result:j})}).catch(j=>{en("mark_read:error",{tabKey:N.tabKey,sessionId:N.sessionId,error:j instanceof Error?j.message:String(j)})})},[l,c]);return i.useEffect(()=>{var T;if(!n){ty(o)&&h("inbox"),x(((T=e[0])==null?void 0:T.tabKey)||null),C.current=null;return}if(o!=="chat"){C.current=null;return}const N=`${n.tabKey}:${n.sessionId||""}`;C.current!==N&&(C.current=N,v(n))},[e,v,o,n,h,x]),i.useEffect(()=>{if(!d)return;const N=e.find(T=>T.tabKey===d);N&&(x(N.tabKey),h("chat"),m==null||m())},[e,m,d,h,x]),i.useEffect(()=>{if(!u)return;const N=t.find(T=>T.id===u);N&&(g(N.id),A(),y("machines"),f("inbox"),h("machine"),p==null||p())},[t,p,u,A,f,h,y,g]),i.useEffect(()=>{b&&(y(b),h("inbox"),w==null||w())},[w,b,h,y]),i.useEffect(()=>{const N=r.filter(T=>T.inboxBucket==="task_complete"||T.unread);N.length!==0&&en("inbox_state",{screen:o,selectedTabKey:a,items:N.map(T=>{const k=In(T.conversation,l);return{liveState:k,tabKey:T.conversation.tabKey,sessionId:T.conversation.sessionId,displayPrimary:ut(T.conversation),serverBucket:k.inboxBucket,computedBucket:T.inboxBucket,serverUnread:k.unread,computedUnread:T.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,activityAt:ws(T.conversation)}})})},[r,l,o,a]),{markConversationRead:v}}function ry(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function kl(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ny(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function ay({sendDaemonCommand:e,navigate:t,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)},[]),p=i.useCallback(async(f,A,C)=>{var v;try{o("loading"),c(`Launching ${A}…`);const N={ideType:A,enableCdp:!0};(v=C==null?void 0:C.workspacePath)!=null&&v.trim()&&(N.workspace=C.workspacePath.trim()),await e(f,"launch_ide",N),o("done"),c(`${A} launch requested`)}catch(N){o("error"),c(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),b=i.useCallback(async(f,A,C)=>{if(A.trim())try{o("loading"),c(C!=null&&C.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(f,"workspace_add",{path:A.trim(),createIfMissing:(C==null?void 0:C.createIfMissing)===!0});if(v!=null&&v.success){o("done"),c(C!=null&&C.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),c((v==null?void 0:v.error)||"Could not save workspace")}catch(v){o("error"),c(v instanceof Error?v.message:"Could not save workspace")}},[e]),w=i.useCallback(async f=>{var A,C,v,N,T,k;try{o("loading"),c("Starting daemon upgrade…");const j=await e(f,"daemon_upgrade",{});if((A=j==null?void 0:j.result)!=null&&A.alreadyLatest){o("done"),c(`Already on v${((C=j==null?void 0:j.result)==null?void 0:C.version)||"latest"}.`);return}if((v=j==null?void 0:j.result)!=null&&v.upgraded||(N=j==null?void 0:j.result)!=null&&N.success){o("done"),c(`Upgrade to v${((T=j==null?void 0:j.result)==null?void 0:T.version)||"latest"} started. Daemon is restarting…`);return}o("error"),c(((k=j==null?void 0:j.result)==null?void 0:k.error)||"Upgrade failed")}catch(j){o("error"),c(j instanceof Error?j.message:"Upgrade failed")}},[e]),x=i.useCallback(async(f,A,C,v)=>{var k,j,B;const N=Date.now(),T={machineId:f,kind:A,providerType:C,workspaceId:(v==null?void 0:v.workspaceId)||null,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:N};try{o("loading"),c(`Launching ${C}…`),m(T);const L={cliType:C};(k=v==null?void 0:v.workspacePath)!=null&&k.trim()?L.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(L.workspaceId=v.workspaceId),v!=null&&v.resumeSessionId&&(L.resumeSessionId=v.resumeSessionId),(j=v==null?void 0:v.args)!=null&&j.trim()&&(L.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(B=v==null?void 0:v.model)!=null&&B.trim()&&(L.initialModel=v.model.trim());const S=await e(f,"launch_cli",L),D=(S==null?void 0:S.result)||S,$=(D==null?void 0:D.sessionId)||(D==null?void 0:D.id);if(S!=null&&S.success&&$){m(null),o("done"),c(`${C} launched`),t(ls($));return}if(S!=null&&S.success){o("loading"),c(`${C} launch requested — waiting for session…`);return}m(null),o("error"),c((S==null?void 0:S.error)||(D==null?void 0:D.error)||`Could not launch ${A.toUpperCase()} workspace`)}catch(L){if(ny(L)){o("loading"),c(`${C} launch requested — waiting for session…`);return}m(null),o("error"),c(L instanceof Error?L.message:`Could not launch ${A.toUpperCase()} workspace`)}},[t,e]),h=i.useCallback(async(f,A)=>{try{const C=await e(f,"list_saved_sessions",{providerType:A,kind:"cli",limit:30}),v=(C==null?void 0:C.result)??C;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(C){return console.error("Failed to list saved sessions on mobile:",C),[]}},[e]),g=i.useCallback(async(f,A)=>Qn(e,f,A),[e]);i.useEffect(()=>{if(!d)return;const f=kl(d.workspacePath),A=r.find(v=>{var L,S,D,$;if(!v||v.type==="adhdev-daemon"||ry(v.daemonId||v.id)!==d.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==d.kind||String(v.agentType||v.type||"")!==d.providerType)return!1;const j=String(v.providerSessionId||"");if(d.resumeSessionId&&j)return j===d.resumeSessionId;if(f){const E=kl(v.workspace||v.runtimeWorkspaceLabel);return E?E===f:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||(($=(D=(S=(L=v.activeChat)==null?void 0:L.messages)==null?void 0:S.at)==null?void 0:D.call(S,-1))==null?void 0:$.timestamp)||0)>=d.startedAt-5e3});if(!A)return;const C=Fd({entrySessionId:A.sessionId,entryInstanceId:A.instanceId,entryRouteId:A.id,conversations:n});C&&(m(null),o("done"),c(`${d.providerType} launched`),t(ls(C)))},[n,r,t,d]),i.useEffect(()=>{if(!d)return;const f=window.setTimeout(()=>{m(A=>!A||A.startedAt!==d.startedAt?A:(o("error"),c("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(f)},[d]);const y=i.useCallback(async(f,A)=>{if(A.kind==="ide"&&A.providerType){await p(f,A.providerType,{workspacePath:A.workspace||null});return}(A.kind==="cli"||A.kind==="acp")&&A.providerType&&await x(f,A.kind,A.providerType,{workspacePath:A.workspace||null,resumeSessionId:A.providerSessionId||null})},[p,x]);return{machineAction:{state:a,message:l},resetMachineAction:u,handleLaunchDetectedIde:p,handleAddWorkspace:b,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:x,handleListSavedSessions:h,handleBrowseDirectory:g,handleOpenRecent:y}}function oy({conversations:e,selectedConversation:t,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]),p=i.useCallback(y=>{const f=e.find(A=>A.routeId===y.routeId&&A.streamSource==="native");f&&(o(f.tabKey),l("chat"),n(f))},[e,n,l,o]),b=i.useCallback(()=>{n(t),l("inbox")},[n,t,l]),w=i.useCallback((y,f="inbox")=>{c(y),a(),d("machines"),m(f),l("machine")},[a,m,l,d,c]),x=i.useCallback(y=>{const f=As(y);f&&w(f,"chat")},[w]),h=i.useCallback(()=>{a(),l(r)},[r,a,l]),g=i.useCallback(y=>{d(y),l("inbox")},[l,d]);return{openConversation:u,openNativeConversation:p,backFromConversation:b,openMachine:w,openConversationMachine:x,backFromMachine:h,changeMachineSection:g}}function Is(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function iy(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function ly({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:b,onRequestedMobileSectionConsumed:w,onOpenHistory:x,onOpenRemote:h,onStopCli:g,wsStatus:y,isConnected:f,onShowAllHiddenConversations:A,onHideConversation:C,onOpenMeshGraph:v,onOpenNewSession:N,liveSessionInboxState:T,setCliViewModeOverrides:k}){const[j,B]=i.useState(()=>{var ae;return((ae=e[0])==null?void 0:ae.tabKey)||null}),[L,S]=i.useState(()=>e[0]?"chat":"inbox"),[D,$]=i.useState("chats"),[E,I]=i.useState(null),[M,F]=i.useState("inbox"),P=i.useRef([]),R=Ys(),K="0.9.81",V=i.useMemo(()=>e.find(ae=>ae.tabKey===j)||e[0]||null,[e,j]),te=i.useMemo(()=>V?r.find(ae=>ae.id===V.routeId):void 0,[r,V]),ie=i.useMemo(()=>!V||st(V)||!at(V)?null:Js(V),[V]),J=i.useMemo(()=>r.filter(ae=>ae.type==="adhdev-daemon").sort(Po),[r]),me=i.useMemo(()=>J.find(ae=>ae.id===E)||null,[J,E]),je=Vn({sendDaemonCommand:a,activeConv:V||void 0,setActionLogs:o,isStandalone:l}),ke=ay({sendDaemonCommand:a,navigate:R,ides:r,conversations:e}),q=i.useMemo(()=>e.map(ae=>{const Ie=L==="chat"&&(V==null?void 0:V.tabKey)===ae.tabKey,Ce=Un(ae,T,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ie}),_e=ws(ae),H=Qc(ae);return{conversation:ae,timestamp:_e,preview:H,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[e,T,L,V]),{markConversationRead:ge}=sy({conversations:e,machineEntries:J,items:q,selectedConversation:V,selectedTabKey:j,screen:L,liveSessionInboxState:T,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:p,requestedMobileSection:b,onRequestedMobileSectionConsumed:w,setSelectedTabKey:B,setScreen:S,setSelectedMachineId:I,setSection:$,setMachineBackTarget:F,resetMachineAction:ke.resetMachineAction}),fe=oy({conversations:e,selectedConversation:V,machineBackTarget:M,markConversationRead:ge,resetMachineAction:ke.resetMachineAction,setSelectedTabKey:B,setScreen:S,setSelectedMachineId:I,setSection:$,setMachineBackTarget:F}),we=i.useMemo(()=>xn(q.filter(ae=>ae.requiresAction)),[q]),xe=i.useMemo(()=>xn(q.filter(ae=>ae.unread&&!ae.requiresAction)),[q]),Ne=i.useMemo(()=>Jg(q.filter(ae=>!ae.unread&&!ae.requiresAction&&ae.isWorking),P.current),[q]);i.useEffect(()=>{P.current=Ne.map(ae=>ae.conversation.tabKey)},[Ne]);const Q=i.useMemo(()=>xn(q.filter(ae=>!ae.unread&&!ae.requiresAction&&!ae.isWorking)),[q]),he=i.useMemo(()=>me?q.filter(ae=>As(ae.conversation)===me.id):[],[q,me]),oe=i.useMemo(()=>Zg(me,r),[r,me]),ue=(me==null?void 0:me.version)||null,le=!!me&&!!ue&&!0&&ue!==K,de=i.useMemo(()=>(me==null?void 0:me.availableProviders)||[],[me]),Z=i.useMemo(()=>de.filter(ae=>Is(ae,"cli")).map(ae=>({type:ae.type,displayName:ae.displayName||ae.type,icon:ae.icon})),[de]),ve=i.useMemo(()=>de.filter(ae=>Is(ae,"acp")).map(ae=>({type:ae.type,displayName:ae.displayName||ae.type,icon:ae.icon})),[de]),ce=i.useMemo(()=>ey(J,q),[q,J]),pe=i.useCallback(async ae=>{me&&await ke.handleOpenRecent(me.id,ae)},[ke,me]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&V?s.jsx(Wg,{selectedConversation:V,isAcp:st(V),isStandalone:l,selectedIdeEntry:te,actionLogs:n,userName:c,isSendingChat:je.isSendingChat,sendFeedbackMessage:je.sendFeedbackMessage,isFocusingAgent:je.isFocusingAgent,handleModalButton:je.handleModalButton,handleRelaunch:je.handleRelaunch,onBack:fe.backFromConversation,onOpenNativeConversation:fe.openNativeConversation,onOpenMachine:fe.openConversationMachine,onOpenHistory:x,onOpenRemote:h,onOpenMeshGraph:v,onStopCli:g,cliViewMode:ie,onSetCliViewMode:async ae=>{await Cd({conversation:V,mode:ae,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:k})},handleSendChat:je.handleSendChat,handleFocusAgent:je.handleFocusAgent}):L==="machine"&&me?s.jsx(Xg,{selectedMachineEntry:me,selectedMachineConversations:he,selectedMachineRecentLaunches:oe,cliProviders:Z,acpProviders:ve,selectedMachineNeedsUpgrade:le,appVersion:K,machineAction:ke.machineAction,isStandalone:l,section:D,showBottomNav:M==="inbox",onBack:fe.backFromMachine,onSectionChange:fe.changeMachineSection,onOpenConversation:fe.openConversation,onOpenRecent:pe,onOpenMachineDetails:()=>R(`/machines/${me.id}`),onMachineUpgrade:()=>ke.handleMachineUpgrade(me.id),onLaunchDetectedIde:(ae,Ie)=>ke.handleLaunchDetectedIde(me.id,ae,Ie),onAddWorkspace:(ae,Ie)=>ke.handleAddWorkspace(me.id,ae,Ie),onBrowseDirectory:ae=>ke.handleBrowseDirectory(me.id,ae),onLaunchWorkspaceProvider:(ae,Ie,Ce)=>ke.handleLaunchWorkspaceProvider(me.id,ae,Ie,Ce),onListSavedSessions:ae=>ke.handleListSavedSessions(me.id,ae)}):s.jsx(Ug,{section:D,attentionItems:we,unreadItems:xe,workingItems:Ne,completedItems:Q,hiddenConversations:t,machineCards:ce,getAvatarText:iy,actionLogs:n,sendDaemonCommand:a,onOpenConversation:fe.openConversation,onShowAllHidden:A,onHideConversation:C,onOpenMeshGraph:v,onOpenNewSession:N,onOpenMachine:fe.openMachine,onOpenSettings:()=>R("/settings"),onSectionChange:$,wsStatus:y,isConnected:f,isStandalone:l})})}function Ia(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function cy({conversations:e,numGroups:t,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const l=i.useRef(0),[c,d]=i.useState(!1),[m,u]=i.useState(null),p=i.useCallback(()=>{l.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",p),window.addEventListener("drop",p),()=>{window.removeEventListener("dragend",p),window.removeEventListener("drop",p)}),[p]);const b=i.useCallback(g=>{g.dataTransfer.types.includes("text/tab-key")&&(l.current+=1,d(!0))},[]),w=i.useCallback(g=>{if(!g.dataTransfer.types.includes("text/tab-key"))return;if(g.preventDefault(),!Ia(t,r)){u("merge");return}const y=g.currentTarget.getBoundingClientRect(),f=g.clientX-y.left,A=y.width/3;f<A?u("split-left"):f>A*2?u("split-right"):u("merge")},[t,r]),x=i.useCallback(()=>{l.current-=1,!(l.current>0)&&(l.current=0,d(!1),u(null))},[]),h=i.useCallback(g=>{l.current=0,d(!1);const y=g.dataTransfer.getData("text/tab-key"),f=y?e.some(C=>C.tabKey===y):!1,A=m;if(u(null),o(),!!y){if(g.preventDefault(),A==="split-left"&&Ia(t,r)){r==null||r(y,"split-left");return}if(A==="split-right"&&Ia(t,r)){r==null||r(y,"split-right");return}if(f){a(y);return}n==null||n(y)}},[e,m,t,r,n,a,o]);return{dragOver:c,dropAction:m,resetDragState:p,handleDragEnter:b,handleDragOver:w,handleDragLeave:x,handleDrop:h}}function dy(e,t){const r=new Set(t.map(o=>o.tabKey)),n=e.filter(o=>r.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...a]}function uy({conversations:e,initialActiveTabId:t,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,l]=i.useState(t??null),[c,d]=i.useState(r??[]),[m,u]=i.useState(null),p=i.useRef(null),b=i.useRef(null),w=i.useRef(n),x=i.useRef(a);i.useEffect(()=>{w.current=n},[n]),i.useEffect(()=>{x.current=a},[a]),i.useEffect(()=>{t&&t!==o&&l(t)},[t,o]),i.useEffect(()=>{d(T=>{const k=dy(T,e);return k.length===T.length&&k.every((j,B)=>j===T[B])?T:k})},[e]);const h=i.useMemo(()=>{const T=m??c;if(T.length===0)return e;const k=new Map(T.map((j,B)=>[j,B]));return[...e].sort((j,B)=>{const L=k.get(j.tabKey)??999,S=k.get(B.tabKey)??999;return L-S})},[e,m,c]);i.useEffect(()=>{var k,j;if(h.length===0){o!==null&&(l(null),(k=w.current)==null||k.call(w,null));return}if(o&&h.some(B=>B.tabKey===o))return;const T=h[0].tabKey;T!==o&&(l(T),(j=w.current)==null||j.call(w,T))},[h,o]);const g=i.useMemo(()=>h.find(T=>T.tabKey===o),[h,o]),y=i.useCallback(T=>{var k;l(T),(k=w.current)==null||k.call(w,T)},[]),f=i.useCallback((T,k,j)=>{d(B=>{var $;const L=B.filter(E=>E!==T),S=L.indexOf(k);if(S<0)return B;const D=j==="left"?S:S+1;return L.splice(D,0,T),($=x.current)==null||$.call(x,L),L}),u(null)},[]),A=i.useCallback((T,k,j)=>{const L=(c.length>0?c:e.map($=>$.tabKey)).filter($=>$!==T),S=L.indexOf(k);if(S<0)return;const D=j==="left"?S:S+1;L.splice(D,0,T),p.current=L,u(L)},[c,e]),C=i.useCallback(()=>{var k;const T=p.current;T&&(d(T),(k=x.current)==null||k.call(x,T))},[]),v=i.useCallback(()=>{p.current=null,u(null)},[]),N=i.useCallback(T=>{d(k=>{var B;const j=k.filter(L=>L!==T);return j.push(T),(B=x.current)==null||B.call(x,j),j})},[]);return{activeTabId:o,activeConv:g,sortedConversations:h,previewOrderRef:p,draggingTabRef:b,selectTab:y,handleTabReorder:f,updatePreviewOrder:A,commitPreviewOrder:C,clearPreviewOrder:v,moveTabToEnd:N,setDraggingTabKey:T=>{b.current=T}}}function my({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.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:t?1:.45},children:s.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"})}),s.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:s.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"})}),s.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:t?1:.45},children:s.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:t,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){if(a)return s.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?sd: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&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),c&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Vt,"aria-label":Vt,children:[s.jsx(pc,{size:14}),s.jsx("span",{children:Vt})]})}),l&&s.jsx(Kd,{}),l&&s.jsx("div",{className:"mt-8",children:s.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 →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Vd="adhdev-tab-shortcuts";function qd(){try{return JSON.parse(localStorage.getItem(Vd)||"{}")}catch{return{}}}function Yd({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,l]=i.useState(()=>qd()),[c,d]=i.useState(null),m=i.useCallback(p=>{const b=[];return p.metaKey&&b.push(a?"⌘":"Meta"),p.ctrlKey&&b.push("Ctrl"),p.altKey&&b.push(a?"⌥":"Alt"),p.shiftKey&&b.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(b.push(p.key.length===1?p.key.toUpperCase():p.key),b.join("+"))},[a]),u=i.useCallback(p=>{l(p);try{localStorage.setItem(Vd,JSON.stringify(p))}catch{}},[]);return i.useEffect(()=>{if(!e||!c)return;const p=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){d(null);return}const w=m(b);if(!w)return;const x={...o};for(const[h,g]of Object.entries(x))g===w&&delete x[h];x[c]=w,u(x),d(null)};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[e,c,o,u,m]),i.useEffect(()=>{if(!e)return;const p=b=>{if(!(!b.ctrlKey&&!b.metaKey&&!b.altKey)){for(const[w,x]of Object.entries(o))if(t.includes(w)&&m(b)===x){b.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const Ma=e=>{e.preventDefault()},py=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:l,draggingTabRef:c,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:p,onReorderTab:b,onCommitPreviewOrder:w,onClearPreviewOrder:x,onDragStateReset:h,onDragTabKeyChange:g,onReceiveTab:y,onOpenContextMenu:f,longPressTimer:A,isGroupActive:C}){const v=Xs(t),N=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",T=v.isReconnecting,k=i.useCallback(M=>{c.current=t.tabKey,g(t.tabKey),M.dataTransfer.setData("text/tab-key",t.tabKey),M.dataTransfer.effectAllowed="move"},[t.tabKey,c,g]),j=i.useCallback(()=>{c.current=null,g(null),w(),x(),h()},[c,g,w,x,h]),B=i.useCallback(M=>{const F=c.current;if(!(!F||F===t.tabKey)&&M.dataTransfer.types.includes("text/tab-key")){M.preventDefault(),M.stopPropagation();const P=M.currentTarget.getBoundingClientRect(),R=M.clientX<P.left+P.width/2?"left":"right";p(F,t.tabKey,R)}},[t.tabKey,c,p]),L=i.useCallback(M=>{M.preventDefault(),M.stopPropagation();const F=M.dataTransfer.getData("text/tab-key");if(F&&F!==t.tabKey){const P=M.currentTarget.getBoundingClientRect(),R=M.clientX<P.left+P.width/2?"left":"right";l.includes(F)?b(F,t.tabKey,R):y&&y(F)}x()},[t.tabKey,l,b,y,x]),S=i.useCallback(M=>{M.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),D=i.useCallback(M=>{M.preventDefault(),f(M.clientX,M.clientY,t.tabKey)},[t.tabKey,f]),$=i.useCallback(M=>{const F=M.touches[0];A.current=setTimeout(()=>{f(F.clientX,F.clientY,t.tabKey)},600)},[t.tabKey,A,f]),E=i.useCallback(()=>{A.current&&clearTimeout(A.current)},[A]),I=["adhdev-dockview-tab",N,r&&"is-active",C&&"is-group-active",T&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:I,draggable:!0,onDragStart:k,onDragEnd:j,onDragOver:B,onDrop:L,onClick:S,onContextMenu:D,onTouchStart:$,onTouchEnd:E,onTouchMove:E,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):T?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:ut(t),children:ut(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[T?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:xs(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[xs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:xs(t)}),s.jsx(zs,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.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,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function hy({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:b,onDragTabKeyChange:w,onReceiveTab:x,onHideTab:h,isGroupActive:g,allowTabShortcuts:y=!0}){const[f,A]=i.useState(null),C=i.useRef(null),v=i.useRef(null),N=i.useMemo(()=>e.map(D=>D.tabKey),[e]);_r("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(f==null?void 0:f.tabKey)||null});const{isMac:T,tabShortcuts:k,shortcutListening:j,setShortcutListening:B,saveShortcuts:L}=Yd({enabled:y,sortedTabKeys:e.map(D=>D.tabKey),onFocus:o,onSelectTab:l});i.useEffect(()=>{if(!f)return;const D=$=>{const E=document.querySelector("[data-pane-context-menu]");E&&E.contains($.target)||A(null)};return window.addEventListener("mousedown",D,!0),()=>window.removeEventListener("mousedown",D,!0)},[f]),i.useEffect(()=>{const D=v.current;if(!D)return;const $=E=>{Math.abs(E.deltaY)<=Math.abs(E.deltaX)||(E.preventDefault(),D.scrollLeft+=E.deltaY)};return D.addEventListener("wheel",$,{passive:!1}),()=>D.removeEventListener("wheel",$)},[]);const S=i.useCallback((D,$,E)=>{A({x:D,y:$,tabKey:E})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(D=>s.jsx(py,{conv:D,isActive:t===D.tabKey,isDraggedTab:a.current===D.tabKey,isTaskCompleteUnread:n.has(D.tabKey),shortcut:y?k[D.tabKey]:void 0,conversationKeys:N,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:p,onDragStateReset:b,onDragTabKeyChange:w,onReceiveTab:x,onOpenContextMenu:S,longPressTimer:C,isGroupActive:g},D.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),f&&s.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:f.x,top:f.y},children:[y&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Ma,onClick:D=>{D.stopPropagation(),B(f.tabKey),A(null)},children:["⌨ ",k[f.tabKey]?`Change shortcut (${k[f.tabKey]})`:"Set shortcut"]}),k[f.tabKey]&&s.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:Ma,onClick:()=>{const D={...k};delete D[f.tabKey],L(D),A(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[y&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.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:Ma,onClick:()=>{h(f.tabKey),A(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&j&&s.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:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:D=>D.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",T?"⌘+1":"Ctrl+1",", ",T?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function fy({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,userName:d,groupIndex:m,onFocus:u,isSplitMode:p,numGroups:b,onMoveTab:w,onReceiveTab:x,style:h,onActiveTabChange:g,initialActiveTabId:y,initialTabOrder:f,onTabOrderChange:A,onHideTab:C,isFocused:v,allowTabShortcuts:N=!0,onOpenNewSession:T,liveSessionInboxState:k}){const{sendCommand:j}=kt(),B=i.useRef(null),{activeTabId:L,activeConv:S,sortedConversations:D,draggingTabRef:$,selectTab:E,handleTabReorder:I,updatePreviewOrder:M,commitPreviewOrder:F,clearPreviewOrder:P,moveTabToEnd:R,setDraggingTabKey:K}=uy({conversations:e,initialActiveTabId:y,initialTabOrder:f,onActiveTabChange:g,onTabOrderChange:A}),V=Vn({sendDaemonCommand:a,activeConv:S,setActionLogs:o,isStandalone:l}),{dragOver:te,dropAction:ie,resetDragState:J,handleDragEnter:me,handleDragOver:je,handleDragLeave:ke,handleDrop:q}=cy({conversations:e,numGroups:b,onMoveTab:w,onReceiveTab:x,onOwnTabDrop:R,onClearPreviewOrder:P}),ge=S&&!st(S)&&Js(S)==="terminal",fe=i.useMemo(()=>S?t.find(Q=>Q.id===S.routeId):void 0,[t,S]),we=i.useMemo(()=>S?n.filter(Q=>Q.routeId===S.tabKey):[],[n,S]),xe=i.useMemo(()=>new Set(D.filter(Q=>Gp(Q,k,{isOpenConversation:Q.tabKey===L})).map(Q=>Q.tabKey)),[L,k,D]);_r("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:L,dragOver:te});const Ne=i.useCallback(Q=>{Q.streamSource==="agent-stream"&&Q.agentType&&j(Q.routeId,Bc(),{agentType:Q.agentType,...Q.sessionId&&{targetSessionId:Q.sessionId}}).catch(()=>{})},[j]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...h,outline:te?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(hy,{conversations:D,activeTabId:L,groupIndex:m,numGroups:b,unreadTabKeys:xe,draggingTabRef:$,onFocus:u,onSelectTab:E,onConversationActivated:Ne,onPreviewReorder:M,onReorderTab:I,onCommitPreviewOrder:F,onClearPreviewOrder:P,onDragStateReset:J,onDragTabKeyChange:K,onMoveTab:w,onReceiveTab:x,onHideTab:C,isGroupActive:v??!1,allowTabShortcuts:N}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:me,onDragOver:je,onDragLeave:ke,onDrop:q,children:[te&&s.jsx(my,{dropAction:ie,canSplit:!!(b<4&&w)}),S?s.jsx(ti,{activeConv:S,clearToken:r[S.tabKey]||0,isCliTerminal:!!ge,ideEntry:fe,terminalRef:B,handleModalButton:V.handleModalButton,handleRelaunch:V.handleRelaunch,handleSendChat:V.handleSendChat,isSendingChat:V.isSendingChat,sendFeedbackMessage:V.sendFeedbackMessage,handleFocusAgent:V.handleFocusAgent,isFocusingAgent:V.isFocusingAgent,actionLogs:we,userName:d,isInputActive:!p||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(ri,{conversationsCount:e.length,isSplitMode:p,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:T})})]})]})}function xy({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:p,userName:b,focusedGroup:w,focusGroup:x,moveTabToGroup:h,splitTabRelative:g,closeGroup:y,handleResizeStart:f,groupActiveTabIds:A,setGroupActiveTab:C,groupTabOrders:v,setGroupTabOrder:N,toggleHiddenTab:T,onOpenNewSession:k,allowTabShortcuts:j=!0,liveSessionInboxState:B}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,S)=>{const D=t&&n.length===r?`${n[S]}%`:void 0;return s.jsxs(St.Fragment,{children:[t&&S>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:$=>f(S-1,$),onDoubleClick:()=>y(S),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(fy,{style:t?{flexBasis:D??`${100/r}%`,flexGrow:D?0:1,flexShrink:D?0:1}:void 0,conversations:L,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:p,userName:b,groupIndex:S,isFocused:t&&w===S,onFocus:()=>x(S),isSplitMode:t,numGroups:r,onMoveTab:($,E)=>{E==="left"&&S>0?h($,S-1):E==="right"&&S<r-1?h($,S+1):E==="split-left"&&r<4?g($,S,"left"):E==="split-right"&&r<4&&g($,S,"right")},onReceiveTab:$=>h($,S),onActiveTabChange:$=>C(S,$),initialActiveTabId:A[S],initialTabOrder:v[S],onTabOrderChange:$=>N(S,$),onHideTab:T,onOpenNewSession:k,allowTabShortcuts:j,liveSessionInboxState:B})]},S)})})}function Xd({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[l,c]=i.useState(null);i.useEffect(()=>e?ht.onScreenshot("ide-page",(u,p)=>{if(u!==e)return;const b=new FileReader;b.onload=()=>o(b.result),b.readAsDataURL(p)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=ht.onStatus)==null?void 0:u.call(ht,(p,b)=>{p===e&&b!=null&&b.screenshotUsage&&c(b.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const m=e?ht.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&t?m.startScreenshots(t):m.stopScreenshots(t),()=>{m.stopScreenshots(t)}},[n,r,t,e]);const d=i.useCallback(async(m,u)=>{const p=e?ht.get(e):null;return!p||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):p.sendInput(m,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:l,handleRemoteAction:d}}const Jd="adhdev-dashboard-action-shortcuts",by=1200,gy=[["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 yy(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function it(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+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 t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Qd(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 xo(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Bn(e){const t=Object.fromEntries(Qd(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Jd)||"{}"),n={...t,...r};for(const[a,o]of gy)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function Zd(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function vy({enabled:e=!0,onTrigger:t}){const r=yy(),[n,a]=i.useState(()=>Bn(r)),[o,l]=i.useState(null),[c,d]=i.useState([]),m=i.useRef({parts:[],timer:null}),u=i.useCallback(h=>{const g=[];return h.metaKey&&g.push(r?"⌘":"Meta"),h.ctrlKey&&g.push("Ctrl"),h.altKey&&g.push(r?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&g.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(g.push(Zd(h.key)),g.join("+"))},[r]),p=i.useCallback(h=>{a(h);try{localStorage.setItem(Jd,JSON.stringify(h))}catch{}},[]);i.useEffect(()=>{const h=Bn(r),g=Object.entries(n),y=Object.entries(h);g.length===y.length&&g.every(([f,A])=>h[f]===A)||p(h)},[n,r,p]);const b=i.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),w=i.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},by))},[]);i.useEffect(()=>{if(!o)return;const h=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){l(null),d([]);return}const y=u(g);if(!y)return;const A=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(y);if(c.length===0&&A){d([y]);return}const v=[...c,y].slice(0,2).join(" "),N={...n};for(const[T,k]of Object.entries(N))k===v&&delete N[T];N[o]=v,p(N),l(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[n,u,p,o,c]),i.useEffect(()=>{if(!e||o)return;const h=g=>{if(g.defaultPrevented)return;const y=u(g);if(!y)return;const f=g.metaKey||g.ctrlKey||g.altKey;if(xo(g.target))return;const A=m.current.parts,C=f?[y]:[...A.slice(-1),y].slice(-2),v=C.join(" "),N=C[C.length-1],T=Object.entries(n).filter(([,S])=>!!S),k=T.find(([,S])=>S===v);if(k){g.preventDefault(),b(),t(k[0]);return}if(T.some(([,S])=>S.startsWith(`${v} `))){g.preventDefault(),m.current.parts=C,w();return}const B=T.find(([,S])=>S===N);if(B){g.preventDefault(),b(),t(B[0]);return}if(T.some(([,S])=>S.startsWith(`${N} `))){g.preventDefault(),m.current.parts=[N],w();return}b()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[n,w,e,u,t,b,o]),i.useEffect(()=>()=>b(),[b]);const x=i.useMemo(()=>Qd(r),[r]);return{isMac:r,actionDefinitions:x,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:l,setShortcutListeningDraft:d,saveShortcuts:p}}function wy({isTabInPopout:e,isTabFloating:t,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(t&&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})):t?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 eu(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Sl({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!eu(n):!0}function jy({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:eu(r)}const tu=1e3,ky=4;function Nl(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Cl(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function Sy({detachDelayMs:e=tu,stillnessThresholdPx:t=ky,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 p=()=>{m!=null&&(a(m),m=null)},b=()=>{p(),c=null},w=()=>{p(),o=null,l=null,c=null,d=null,u=!1},x=()=>{!o||!c||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!c||!d||u)&&Nl(d,l)&&(Cl(c,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=y=>{if(!(!o||u)){if(!Nl(y,l)){d={clientX:y.clientX,clientY:y.clientY},b();return}(!c||Cl(c,y,t))&&(p(),c={clientX:y.clientX,clientY:y.clientY}),d={clientX:y.clientX,clientY:y.clientY},x()}},g=y=>{!o||u||(y&&(d={clientX:y.clientX,clientY:y.clientY}),b())};return{startDrag:y=>{p(),o=y.panelId,l=y.selfPanelBounds??null,c=null,d={clientX:y.clientX,clientY:y.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:g,markNoDropTarget:g,markDockTarget:g,endDrag:w,isDragging:()=>o!=null,hasDetached:()=>u,dispose:w}}function Ny(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function tn(e){return e.isActive}function Il(e){return e.isVisible}const su=i.createContext(null);function ea(){const e=i.useContext(su);if(!e)throw new Error("DashboardDockviewContext missing");return e}function bn(e){return ut(e)||e.tabKey}function Cy(e){return`remote:${e}`}function Ot(e){return e.startsWith("remote:")}function Ml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Iy(e){e.preventDefault()}function Aa(e){var n;const t=e==null?void 0:e.defaultView;if(!t)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=t.requestAnimationFrame)==null||n.call(t,()=>{try{t.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function Ta(e,t){e.classList.remove(Ya.className,Xa.className),e.classList.add(t==="light"?Ya.className:Xa.className)}function Al(e){return e?Array.from(new Set(e.groups.map(t=>{var r,n;return(n=(r=t.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(t=>!!t&&t!==window))):[]}function My(e){const[,t]=i.useState(0);i.useEffect(()=>{const r=()=>t(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 Ay(e,t,r){var l;const n=[t];let a;for(const c of n){let d;for(const m of c){const u=e.addPanel({id:m.tabKey,component:"conversation",title:bn(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=t[0])==null?void 0:l.tabKey)??null}function Tl(e,t){const r=new Set(t.map(a=>a.tabKey)),n=new Map;for(const a of t)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])Ot(a.id)||r.has(a.id)||e.removePanel(a);for(const a of t){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!==bn(a)&&o.api.setTitle(bn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:bn(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 _l(e,t,r){var d,m;const n=r?Cy(r):null;for(const u of[...e.panels])Ot(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Ht(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),l=td(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=>!Ot(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 Ty({params:e,api:t}){var w;const r=ea(),n=i.useRef(null),[a,o]=i.useState(()=>tn(t)),[l,c]=i.useState(()=>Il(t)),d=r.conversationsByTabKey.get(e.tabKey),m=Vn({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(tn(t)),c(Il(t));const x=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!tn(t)&&!h.isActive){o(!1);return}o(tn(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of x)h.dispose()}},[t]);const u=i.useMemo(()=>d?r.ides.find(x=>x.id===d.routeId):void 0,[r.ides,d]),p=i.useMemo(()=>d?r.actionLogs.filter(x=>x.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(ri,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const b=!st(d)&&Js(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(ti,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:b,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:p,userName:r.userName,scrollToBottomRequestNonce:((w=r.scrollToBottomRequest)==null?void 0:w.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:l})})}function _y({params:e}){var d;const t=ea(),r=i.useMemo(()=>Ht([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>t.ides.find(m=>m.id===e.routeId),[t.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}=Xd({doId:a,targetSessionId:r?$c(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?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(wc,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:l,transportType:r.transport,onAction:c})}):s.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 Ly(){const e=ea();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(ri,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Ry(e){var w,x;My(e);const t=ea(),r=i.useCallback(h=>{"button"in h&&h.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const h=Ht([...t.conversationsByTabKey.values()],e.params.routeId),g=((w=e.api.group.activePanel)==null?void 0:w.id)===e.api.id,y=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${g?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(h==null?void 0:h.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:h!=null&&h.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:h.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const n=t.conversationsByTabKey.get(e.params.tabKey);if(!n)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((x=e.api.group.activePanel)==null?void 0:x.id)===e.api.id,o=e.api.isGroupActive,l=Un(n,t.liveSessionInboxState,{isOpenConversation:a}),c=l.isReconnecting,d=l.isConnecting,m=l.isGenerating,u=l.isWaiting,p=l.unread,b=t.tabShortcuts[n.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${c?" is-reconnecting":""}`,title:ut(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:h=>{var g;h.preventDefault(),r(h),t.openTabContextMenu({x:h.clientX,y:h.clientY,tabKey:n.tabKey,sourceDocument:((g=h.target)==null?void 0:g.ownerDocument)??document})},children:[p&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?s.jsx("div",{className:"tab-spinner"}):u?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):c?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?s.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:ut(n)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:c?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:xs(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:xs(n)}):s.jsx("span",{children:xs(n)})})]}),b&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:b,children:b})]})}function Py({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:p,registerActionHandlers:b,onActiveTabChange:w,onOpenNewSession:x,onRequestScrollToBottom:h,requestedActiveTabKey:g,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:f,scrollToBottomRequest:A,liveSessionInboxState:C,layoutProfile:v}){var Te,Be,qe;const{theme:N}=Qs(),{sendCommand:T}=kt(),k=i.useRef(null),j=i.useRef(null),B=i.useRef(null),L=i.useRef(!1),S=i.useRef(!1),D=i.useRef(!1),$=i.useRef(null),E=i.useRef([]),[I,M]=i.useState(null),[F,P]=i.useState(0),R=i.useRef(typeof window>"u"?{}:Zb(v)),K=i.useMemo(()=>new Map(e.map(z=>[z.tabKey,z])),[e]),V=i.useMemo(()=>{const z=k.current;return z?z.groups.some(U=>{try{const X=U.model.location.type;return X!=="floating"&&X!=="popout"?!1:U.panels.some(re=>K.has(re.id))}catch{return!1}}):!1},[K,F,e]),te=i.useCallback(()=>{var z;(z=k.current)==null||z.focus()},[]),ie=i.useCallback((z,U)=>{h==null||h(z,U)},[h]),J=i.useCallback(z=>{const U=document,X=z.document;for(const ne of U.querySelectorAll('link[rel="stylesheet"]')){const Se=X.createElement("link");Se.rel="stylesheet",Se.href=ne.href,ne.crossOrigin&&(Se.crossOrigin=ne.crossOrigin),X.head.appendChild(Se)}for(const ne of U.querySelectorAll("style")){const Se=X.createElement("style");Se.textContent=ne.textContent,X.head.appendChild(Se)}const re=[];for(const ne of U.styleSheets)try{for(const Se of ne.cssRules)Se instanceof CSSStyleRule&&(Se.selectorText===":root"||Se.selectorText==="html")&&re.push(Se.cssText)}catch{}if(re.length>0){const ne=X.createElement("style");ne.textContent=re.join(`
|
|
54
|
+
`),X.head.appendChild(ne)}const W=U.documentElement.getAttribute("data-theme");W&&X.documentElement.setAttribute("data-theme",W),X.documentElement.style.colorScheme=W==="light"?"light":"dark",X.body.className=U.body.className;const G=U.documentElement.getAttribute("style");G&&X.documentElement.setAttribute("style",G);const se=X.getElementById("dv-popout-window");se instanceof HTMLElement&&(se.classList.add("adhdev-dockview"),Ta(se,N))},[N]),me=i.useCallback(()=>{var U;const z=k.current;if(z)for(const X of z.groups)try{const re=(U=X.element)==null?void 0:U.ownerDocument;if(!re||re===document)continue;const W=re.getElementById("dv-popout-window");W instanceof HTMLElement&&(W.classList.add("adhdev-dockview"),Ta(W,N));const G=document.documentElement.getAttribute("data-theme");G&&re.documentElement.setAttribute("data-theme",G),re.documentElement.style.colorScheme=G==="light"?"light":"dark",re.body.className=document.body.className;const se=document.documentElement.getAttribute("style");se?re.documentElement.setAttribute("style",se):re.documentElement.removeAttribute("style")}catch{}},[N]),je=i.useCallback(z=>{const U=k.current;if(!U)return;const X=U.getPanel(z);X&&U.addPopoutGroup(X,{popoutUrl:"/popout.html",onDidOpen:({window:re})=>{J(re),he();const W=K.get(z);re.document.title=W?`${ut(W)} — ADHDev`:"ADHDev — Popout"}})},[K,J]),ke=i.useCallback(z=>{const U=k.current,X=U==null?void 0:U.getPanel(z);if(!U||!X)return;const re=U.groups.filter(W=>{var G;try{return((G=W.element)==null?void 0:G.ownerDocument)===document}catch{return!0}});re.length>0?X.api.moveTo({group:re[0],position:"center"}):X.api.moveTo({position:"center"}),X.api.setActive()},[]),q=i.useCallback(z=>{var re;const U=k.current;if(!U)return!1;const X=U.getPanel(z);if(!X)return!1;try{return((re=X.group.element)==null?void 0:re.ownerDocument)!==document}catch{return!1}},[]),ge=i.useCallback(z=>{q(z)&&ke(z),u(z)},[q,ke,u]),fe=i.useCallback(z=>{const U=k.current,X=U==null?void 0:U.getPanel(z);!U||!X||U.addFloatingGroup(X,{width:600,height:500})},[]),we=i.useCallback(z=>{var X;const U=(X=k.current)==null?void 0:X.getPanel(z);if(!U)return!1;try{return U.group.model.location.type==="floating"}catch{return!1}},[]),xe=i.useCallback(()=>{var U,X;const z=(X=(U=k.current)==null?void 0:U.activePanel)==null?void 0:X.id;return!z||Ot(z)?null:K.has(z)?z:null},[K]),Ne=i.useCallback(z=>{const U=k.current,X=U==null?void 0:U.getPanel(z);if(!U||!X)return;const re=U.groups.filter(W=>{try{return W.model.location.type==="grid"}catch{return!0}});re.length>0?X.api.moveTo({group:re[0],position:"center"}):X.api.moveTo({position:"center"}),X.api.setActive()},[]),Q=i.useCallback(()=>{var G;const z=k.current;if(!z)return;const X=z.groups.filter(se=>{var ne;try{return((ne=se.element)==null?void 0:ne.ownerDocument)===document&&se.model.location.type==="grid"}catch{return!1}})[0]||null,re=[...z.panels];for(const se of re){const ne=(G=se.group.element)==null?void 0:G.ownerDocument,Se=se.group.model.location.type;ne===document&&Se==="grid"||(X&&X.id!==se.group.id?se.api.moveTo({group:X,position:"center"}):se.api.moveTo({position:"center"}))}const W=z.activePanel;W&&(W.group.model.openPanel(W),W.api.setActive()),Aa(document)},[]),he=i.useCallback(()=>{var U,X;const z=k.current;if(z)for(const re of z.groups){const W=(U=re.element)==null?void 0:U.ownerDocument;if(!W||W===document)continue;const G=W.getElementById("dv-popout-window");if(!(G instanceof HTMLElement))continue;let se=null,ne=W.title||"ADHDev",Se="Popout workspace";const Ee=re.activePanel;if(Ee)if(se=Ee.id,Ot(Ee.id)){const Le=((X=Ee.params)==null?void 0:X.routeId)||Ee.id.slice(7),Ze=Ht([...K.values()],Le);ne=td(Ze),Se=Ze!=null&&Ze.machineName?`Remote view · ${Ze.machineName}`:"Remote view"}else{const Le=K.get(Ee.id);ne=Le?ut(Le):Ee.title||Ee.id,Se=Le?xs(Le):"Dockview panel"}W.title=`${ne} — ADHDev`;const Oe=Array.from(W.querySelectorAll("#adhdev-popout-header"));for(const Le of Oe)Le.remove();const Re=W.createElement("div");Re.id="adhdev-popout-header",W.body.appendChild(Re),Re.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(";")),Re.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;">${Ml(ne)}</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;">${Ml(Se)}</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
|
+
`,G.style.top="52px",G.style.height="calc(100% - 52px)";const Fe=Re.querySelector("[data-adhdev-popout-focus]");Fe&&(Fe.onclick=()=>{window.focus()});const Ue=Re.querySelector("[data-adhdev-popout-dock]");Ue&&(Ue.disabled=!se,Ue.style.opacity=se?"1":"0.5",Ue.style.cursor=se?"pointer":"default",Ue.onclick=()=>{var Le;se&&ke(se),(Le=W.defaultView)==null||Le.focus()})}},[K,ke]),oe=i.useCallback(z=>{var re;const U=k.current,X=U==null?void 0:U.getPanel(z);if(!(!U||!X)){X.group.model.openPanel(X),X.api.setActive(),ie(z,"dockview-shortcut");try{const W=X.group.model.location;W.type==="popout"?W.getWindow().focus():Aa((re=X.group.element)==null?void 0:re.ownerDocument)}catch{}}},[ie]),ue=i.useCallback(z=>{const U=k.current,X=U==null?void 0:U.activePanel,re=(U==null?void 0:U.activeGroup)||(X==null?void 0:X.group);if(!U||!X||!re)return;const W=re.panels||[];if(W.length<=1)return;const G=W.findIndex(Se=>Se.id===X.id);if(G<0)return;const se=(G+z+W.length)%W.length,ne=W[se];ne&&(ne.group.model.openPanel(ne),ne.api.setActive(),Ot(ne.id)||ie(ne.id,"dockview-shortcut"))},[ie]),le=i.useCallback(z=>{var Fe;const U=k.current,X=(U==null?void 0:U.activeGroup)||((Fe=U==null?void 0:U.activePanel)==null?void 0:Fe.group);if(!U||!X)return;const re=U.groups||[],W=re.find(Ue=>Ue.id===X.id);if(!W)return;const G=W.element.getBoundingClientRect(),se=G.left+G.width/2,ne=G.top+G.height/2,Se=(Ue,Le,Ze,et)=>Math.max(0,Math.min(Le,et)-Math.max(Ue,Ze)),Ee=Ue=>{const Le=Ue.element.getBoundingClientRect(),Ze=Le.left+Le.width/2,et=Le.top+Le.height/2;let gt=0,yt=0,dt=0,xt=!1;if(z==="left"?(xt=Ze<se,gt=Math.max(0,G.left-Le.right),yt=Math.abs(et-ne),dt=Se(G.top,G.bottom,Le.top,Le.bottom)):z==="right"?(xt=Ze>se,gt=Math.max(0,Le.left-G.right),yt=Math.abs(et-ne),dt=Se(G.top,G.bottom,Le.top,Le.bottom)):z==="above"?(xt=et<ne,gt=Math.max(0,G.top-Le.bottom),yt=Math.abs(Ze-se),dt=Se(G.left,G.right,Le.left,Le.right)):(xt=et>ne,gt=Math.max(0,Le.top-G.bottom),yt=Math.abs(Ze-se),dt=Se(G.left,G.right,Le.left,Le.right)),!xt)return Number.POSITIVE_INFINITY;const Ve=dt>0?0:120;return gt*3+yt+Ve};let Oe=null,Re=Number.POSITIVE_INFINITY;for(const Ue of re){if(Ue.id===W.id)continue;const Le=Ee(Ue);Number.isFinite(Le)&&(Le>=Re||(Re=Le,Oe=Ue))}return Oe||void 0},[]),de=i.useCallback(z=>{var re;const U=le(z);if(!U)return;const X=U.activePanel||U.panels[0];X&&(U.model.openPanel(X),X.api.setActive(),Ot(X.id)||ie(X.id,"dockview-focus"),Aa((re=U.element)==null?void 0:re.ownerDocument))},[le,ie]),Z=i.useCallback((z,U)=>{const X=k.current,re=X==null?void 0:X.activePanel,W=(X==null?void 0:X.activeGroup)||(re==null?void 0:re.group);if(!X||!re||!W)return;let G=le(z);!G&&(U!=null&&U.createGroupIfMissing)&&(G=X.addGroup({referenceGroup:W,direction:z})),G&&(re.api.moveTo({group:G,position:"center"}),re.group.model.openPanel(re),re.api.setActive(),Ot(re.id)||ie(re.id,U!=null&&U.createGroupIfMissing?"dockview-split":"dockview-move"))},[le,ie]),{isMac:ve,tabShortcuts:ce,shortcutListening:pe,setShortcutListening:ae,saveShortcuts:Ie}=Yd({sortedTabKeys:e.map(z=>z.tabKey),onFocus:te,onSelectTab:oe}),Ce=i.useCallback(()=>{var X;const z=k.current;if(!z)return;const U=z.activePanel;if(U){if(Ot(U.id)){const re=((X=U.params)==null?void 0:X.routeId)||U.id.slice(7),W=Ht(e,re);W!=null&&W.tabKey&&ae(W.tabKey);return}K.has(U.id)&&ae(U.id)}},[K,oe,ae,e]),_e=i.useCallback(z=>{const U=[];return z.metaKey&&U.push(ve?"⌘":"Meta"),z.ctrlKey&&U.push("Ctrl"),z.altKey&&U.push(ve?"⌥":"Alt"),z.shiftKey&&z.key.length!==1&&U.push(ve?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(z.key)?null:(U.push(Zd(z.key)),U.join("+"))},[ve]),H=i.useCallback(z=>{var U,X;switch(z){case"splitActiveTabRight":Z("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Z("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const re=xe();re&&fe(re);return}case"popoutActiveTab":{const re=xe();re&&je(re);return}case"dockActiveTab":{const re=xe();if(!re)return;q(re)?ke(re):we(re)&&Ne(re);return}case"focusLeftPane":de("left");return;case"focusRightPane":de("right");return;case"focusUpPane":de("above");return;case"focusDownPane":de("below");return;case"moveActiveTabToLeftPane":Z("left");return;case"moveActiveTabToRightPane":Z("right");return;case"moveActiveTabToUpPane":Z("above");return;case"moveActiveTabToDownPane":Z("below");return;case"selectPreviousGroupTab":ue(-1);return;case"selectNextGroupTab":ue(1);return;case"setActiveTabShortcut":Ce();return;case"hideCurrentTab":{const re=(X=(U=k.current)==null?void 0:U.activePanel)==null?void 0:X.id;re&&!Ot(re)&&ge(re);return}default:return}},[ue,Ne,de,fe,xe,ge,we,q,ke,Z,je,Ce]);i.useEffect(()=>{if(!I)return;const z=I.sourceDocument,U=z.defaultView??window,X=re=>{const W=z.querySelector("[data-dockview-tab-context-menu]");W&&W.contains(re.target)||M(null)};return U.addEventListener("mousedown",X,!0),U!==window&&window.addEventListener("mousedown",()=>M(null),!0),()=>{U.removeEventListener("mousedown",X,!0),U!==window&&window.removeEventListener("mousedown",()=>M(null),!0)}},[I]);const Me=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:K,hasDetachedConversationPanels:V,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:x,liveSessionInboxState:C,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ge,userName:m,scrollToBottomRequest:A,tabShortcuts:ce,openTabContextMenu:({x:z,y:U,tabKey:X,sourceDocument:re})=>M({x:z,y:U,tabKey:X,sourceDocument:re??document}),popoutTab:je,moveTabBackToMain:ke,isTabInPopout:q,floatTab:fe,isTabFloating:we}),[n,t,K,V,r,l,c,x,C,a,o,ge,m,A,ce,je,ke,q,fe,we]),Ae=I?wy({isTabInPopout:q(I.tabKey),isTabFloating:we(I.tabKey),tabShortcut:ce[I.tabKey],actionShortcuts:p}):[],He=i.useCallback(z=>{var re;const U=k.current;if((((re=U==null?void 0:U.activePanel)==null?void 0:re.id)??null)===z.id){z.group.model.openPanel(z);return}z.group.model.openPanel(z),z.api.setActive()},[]),Ge=i.useCallback((z,U="requested-tab")=>{if(!z)return!1;const X=k.current;if(!X)return!1;const re=X.getPanel(z);return re?(He(re),ie(z,U),f==null||f(),!0):!1},[He,f,ie]),Xe=i.useCallback(()=>{if(D.current)return!1;const z=Ge($.current,"stored-layout-restore");return z&&(D.current=!0),z},[Ge]),Ye=i.useCallback(()=>{var U;const z=k.current;z&&Qb(v,{activeTabId:((U=z.activePanel)==null?void 0:U.id)??null,layout:z.toJSON()})},[v]),tt=i.useCallback(()=>{eg(v,R.current)},[v]),ct=i.useCallback(z=>{var re,W,G,se;const U=k.current;if(!U)return{kind:"grid"};const X=U.toJSON();for(const ne of X.floatingGroups||[])if((W=(re=ne.data)==null?void 0:re.views)!=null&&W.includes(z)&&ne.position)return{kind:"floating",position:ne.position};for(const ne of X.popoutGroups||[])if((se=(G=ne.data)==null?void 0:G.views)!=null&&se.includes(z))return{kind:"popout",position:ne.position,popoutUrl:ne.url};return{kind:"grid"}},[]),mt=i.useCallback(z=>{const U=k.current;if(!U)return;const X=U.getPanel(z),re=R.current[z];if(!X||!re||re.kind==="grid")return;if(X.group.model.location.type===re.kind){delete R.current[z],tt();return}if(re.kind==="floating"){U.addFloatingGroup(X,{x:re.position.left??24,y:re.position.top??24,width:re.position.width,height:re.position.height}),delete R.current[z],tt();return}delete R.current[z],tt()},[tt]);i.useEffect(()=>(b==null||b({setShortcutForActiveTab:Ce,restoreHiddenTabToSavedLocation:mt,activateConversationTab:oe,resetAllPanelsToMain:Q,activatePreviousTabInGroup:()=>ue(-1),activateNextTabInGroup:()=>ue(1),floatActiveTab:()=>{const z=xe();z&&fe(z)},popoutActiveTab:()=>{const z=xe();z&&je(z)},dockActiveTab:()=>{const z=xe();z&&(q(z)?ke(z):we(z)&&Ne(z))},splitActiveTabRight:()=>Z("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Z("below",{createGroupIfMissing:!0}),focusLeftPane:()=>de("left"),focusRightPane:()=>de("right"),focusUpPane:()=>de("above"),focusDownPane:()=>de("below"),moveActiveTabToLeftPane:()=>Z("left"),moveActiveTabToRightPane:()=>Z("right"),moveActiveTabToUpPane:()=>Z("above"),moveActiveTabToDownPane:()=>Z("below")}),()=>b==null?void 0:b(null)),[ue,Ne,fe,de,xe,we,q,Z,ke,je,b,Q,mt,oe,Ce]),i.useEffect(()=>()=>{var z;(z=B.current)==null||z.call(B),B.current=null},[]);const pt=i.useCallback(z=>{var X,re;k.current=z.api,(X=B.current)==null||X.call(B),B.current=null;const U=Jb(v);if($.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&z.api.fromJSON(U.layout,{reuseExistingPanels:!1}),S.current=Sl({hasStoredLayout:!!(U!=null&&U.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),S.current||(Tl(z.api,e),_l(z.api,e,y)),z.api.totalPanels===0&&e.length>0){const W=Ay(z.api,e,g);if(W){const G=z.api.getPanel(W);G&&He(G)}}else!S.current&&!Ge(g)&&Xe();if(L.current=!0,z.api.onDidActivePanelChange(W=>{var se;if($.current=(W==null?void 0:W.id)??null,D.current=!0,he(),W&&Ot(W.id)){const ne=((se=W.params)==null?void 0:se.routeId)||W.id.slice(7),Se=Ht(e,ne);w((Se==null?void 0:Se.tabKey)??null),Ye();return}if(w((W==null?void 0:W.id)??null),Ye(),!W)return;const G=K.get(W.id);(G==null?void 0:G.streamSource)==="agent-stream"&&G.agentType&&T(G.routeId,Bc(),{agentType:G.agentType,...G.sessionId&&{targetSessionId:G.sessionId}}).catch(()=>{})}),z.api.onDidLayoutChange(()=>{Ye(),he(),P(W=>W+1)}),Ny()){const W=Re=>({clientX:Re.clientX,clientY:Re.clientY}),G=Re=>{const Fe=Re==null?void 0:Re.getBoundingClientRect();return Fe?{left:Fe.left,right:Fe.right,top:Fe.top,bottom:Fe.bottom}:null},se=Re=>{var Ue;const Fe=(Ue=j.current)==null?void 0:Ue.getBoundingClientRect();return Fe?Re.clientX<Fe.left||Re.clientX>Fe.right||Re.clientY<Fe.top||Re.clientY>Fe.bottom:!1},ne=Sy({detachDelayMs:tu,onDetach:({panelId:Re,clientX:Fe,clientY:Ue})=>{var dt,xt;const Le=z.api.getPanel(Re);if(!Le)return;try{if(Le.group.model.location.type!=="grid")return}catch{return}const Ze=(dt=j.current)==null?void 0:dt.getBoundingClientRect(),et=(xt=Le.group.element)==null?void 0:xt.getBoundingClientRect(),gt=Math.round(Math.min(Math.max((et==null?void 0:et.width)??600,360),720)),yt=Math.round(Math.min(Math.max((et==null?void 0:et.height)??500,260),640));z.api.addFloatingGroup(Le,{x:Ze?Math.max(0,Fe-Ze.left-32):void 0,y:Ze?Math.max(0,Ue-Ze.top-18):void 0,width:gt,height:yt}),Le.api.setActive(),Ye(),he(),P(Ve=>Ve+1)}}),Se=[z.api.onWillDragPanel(Re=>{if(!(Re.nativeEvent.defaultPrevented||Re.nativeEvent.shiftKey)){try{if(Re.panel.group.model.location.type!=="grid")return}catch{return}ne.startDrag({panelId:Re.panel.id,selfPanelBounds:G(Re.panel.group.element),...W(Re.nativeEvent)})}}),z.api.onWillShowOverlay(Re=>{if(ne.hasDetached()){Re.preventDefault();return}ne.markDockTarget(W(Re.nativeEvent))}),z.api.onWillDrop(Re=>{if(ne.hasDetached()){Re.preventDefault(),ne.endDrag();return}ne.markDockTarget(W(Re.nativeEvent))}),z.api.onDidDrop(()=>ne.endDrag()),z.api.onUnhandledDragOverEvent(Re=>{ne.isDragging()&&ne.markSelfPanel(W(Re.nativeEvent))})],Ee=Re=>{if(!ne.isDragging())return;const Fe=W(Re);se(Fe)&&ne.markNonSelfPanel(Fe)},Oe=()=>ne.endDrag();window.addEventListener("dragover",Ee,!0),window.addEventListener("drop",Oe,!0),window.addEventListener("dragend",Oe,!0),B.current=()=>{ne.dispose();for(const Re of Se)Re.dispose();window.removeEventListener("dragover",Ee,!0),window.removeEventListener("drop",Oe,!0),window.removeEventListener("dragend",Oe,!0)}}z.api.onDidAddGroup(W=>{requestAnimationFrame(()=>{var G,se;try{const ne=(G=W.element)==null?void 0:G.ownerDocument;if(!ne||ne===document)return;(se=ne.getElementById("dv-popout-window"))==null||se.classList.add("adhdev-dockview");const Se=document.documentElement.getAttribute("data-theme");Se&&ne.documentElement.setAttribute("data-theme",Se),ne.body.className=document.body.className;const Ee=document.documentElement.getAttribute("style");Ee&&ne.documentElement.setAttribute("style",Ee)}catch{}he(),P(ne=>ne+1)})}),w(((re=z.api.activePanel)==null?void 0:re.id)??null)},[He,Ge,K,r,d,v,w,Ye,g,y,T,he,e]);i.useLayoutEffect(()=>{const z=k.current;if(!z||!L.current||S.current&&Sl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;S.current&&(S.current=!1);const U=E.current,X=new Set(U),re=e.map(Oe=>Oe.tabKey),W=new Set(re),G=jy({previousVisibleConversationCount:U.length,visibleConversationCount:e.length,ides:r});let se=!1;for(const Oe of U)W.has(Oe)||G||(R.current[Oe]=ct(Oe),se=!0);se&&tt(),G||(Tl(z,e),_l(z,e,y));const ne=re.filter(Oe=>!X.has(Oe));let Se=!1;for(const Oe of ne){const Re=z.getPanel(Oe),Fe=R.current[Oe];if(!Re||!Fe||Fe.kind==="grid")continue;if(Re.group.model.location.type===Fe.kind){delete R.current[Oe],Se=!0;continue}if(Fe.kind==="floating"){z.addFloatingGroup(Re,{x:Fe.position.left??24,y:Fe.position.top??24,width:Fe.position.width,height:Fe.position.height}),delete R.current[Oe],Se=!0;continue}}if(Se&&tt(),E.current=re,g&&Ge(g))return;!z.activePanel&&z.panels[0]&&He(z.panels[0]),!!(z.activePanel&&z.getPanel(z.activePanel.id))||Xe()},[He,Ge,Xe,r,d,tt,ct,g,y,e]),i.useEffect(()=>{L.current&&Ge(g)},[Ge,g]),i.useEffect(()=>{const z=X=>{const re=X.target;if(!re)return;const W=re.querySelector("[data-tab-key]")||re.closest("[data-tab-key]");if(W){const G=W.getAttribute("data-tab-key");if(G&&X.dataTransfer){const se=re.closest(".dv-tab")||W.closest(".dv-tab")||W;X.dataTransfer.effectAllowed="move",X.dataTransfer.setData("text/tab-key",G),se instanceof HTMLElement&&X.dataTransfer.setDragImage(se,Math.max(12,Math.round(se.clientWidth/2)),Math.max(10,Math.round(se.clientHeight/2)))}}};window.addEventListener("dragstart",z);const U=Al(k.current);for(const X of U)X.addEventListener("dragstart",z);return()=>{window.removeEventListener("dragstart",z);for(const X of U)X.removeEventListener("dragstart",z)}},[F]),i.useEffect(()=>{var U;const z=(U=j.current)==null?void 0:U.querySelector(".adhdev-dockview");z instanceof HTMLElement&&Ta(z,N),me(),he()},[he,me,N]),i.useEffect(()=>{he()},[he]),i.useEffect(()=>{const z=U=>{if(U.defaultPrevented||pe)return;const X=_e(U);if(!X)return;const re=U.metaKey||U.ctrlKey||U.altKey;xo(U.target)&&!re||Bn(ve).setActiveTabShortcut!==X||(U.preventDefault(),U.stopPropagation(),Ce())};return window.addEventListener("keydown",z,!0),()=>window.removeEventListener("keydown",z,!0)},[_e,ve,pe,Ce]),i.useEffect(()=>{const z=j.current;if(!z)return;const U=X=>{var ne,Se;if(!X.isTrusted)return;const re=(Se=(ne=X.target)==null?void 0:ne.closest)==null?void 0:Se.call(ne,".dv-scrollable");if(!re)return;X.preventDefault(),X.stopPropagation();const W=Math.abs(X.deltaX),G=Math.abs(X.deltaY),se=W>G?X.deltaX:X.deltaY;re.dispatchEvent(new WheelEvent("wheel",{deltaY:se,deltaMode:X.deltaMode,bubbles:!1,cancelable:!0}))};return z.addEventListener("wheel",U,{passive:!1,capture:!0}),()=>z.removeEventListener("wheel",U,{capture:!0})},[]),i.useEffect(()=>{const z=Al(k.current);if(z.length===0)return;const U=z.map(X=>{let re=[],W=null;const G=()=>{W!=null&&X.clearTimeout(W),W=null,re=[]},se=()=>{W!=null&&X.clearTimeout(W),W=X.setTimeout(()=>{W=null,re=[]},1200)},ne=Ee=>{if(!Ee.ctrlKey&&!Ee.metaKey&&!Ee.altKey)return;const Oe=_e(Ee);if(!Oe)return;const Re=qd();for(const[Fe,Ue]of Object.entries(Re))if(e.some(Le=>Le.tabKey===Fe)&&Ue===Oe){Ee.preventDefault(),oe(Fe);return}},Se=Ee=>{if(Ee.defaultPrevented||pe)return;const Oe=_e(Ee);if(!Oe)return;const Re=Ee.metaKey||Ee.ctrlKey||Ee.altKey;if(xo(Ee.target))return;const Fe=Bn(ve),Ue=Object.entries(Fe).filter(([Ve,Kt])=>!!Kt&&(Ve==="splitActiveTabRight"||Ve==="splitActiveTabDown"||Ve==="floatActiveTab"||Ve==="popoutActiveTab"||Ve==="dockActiveTab"||Ve==="focusLeftPane"||Ve==="focusRightPane"||Ve==="focusUpPane"||Ve==="focusDownPane"||Ve==="moveActiveTabToLeftPane"||Ve==="moveActiveTabToRightPane"||Ve==="moveActiveTabToUpPane"||Ve==="moveActiveTabToDownPane"||Ve==="selectPreviousGroupTab"||Ve==="selectNextGroupTab"||Ve==="setActiveTabShortcut"||Ve==="hideCurrentTab")),Le=Re?[Oe]:[...re.slice(-1),Oe].slice(-2),Ze=Le.join(" "),et=Le[Le.length-1],gt=Ue.find(([,Ve])=>Ve===Ze);if(gt){Ee.preventDefault(),G(),H(gt[0]);return}if(Ue.some(([,Ve])=>Ve.startsWith(`${Ze} `))){Ee.preventDefault(),re=Le,se();return}const dt=Ue.find(([,Ve])=>Ve===et);if(dt){Ee.preventDefault(),G(),H(dt[0]);return}if(Ue.some(([,Ve])=>Ve.startsWith(`${et} `))){Ee.preventDefault(),re=[et],se();return}G()};return X.addEventListener("keydown",ne),X.addEventListener("keydown",Se),()=>{G(),X.removeEventListener("keydown",ne),X.removeEventListener("keydown",Se)}});return()=>{for(const X of U)X()}},[_e,ve,F,oe,pe,H,e]);const O=N==="light"?Ya:Xa,be=((qe=(Be=(Te=k.current)==null?void 0:Te.activePanel)==null?void 0:Be.group.element)==null?void 0:qe.ownerDocument)??document;return s.jsxs(su.Provider,{value:Me,children:[s.jsx("div",{ref:j,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(om,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:Ty,remote:_y},defaultTabComponent:Ry,watermarkComponent:Ly,onReady:pt,singleTabMode:"default",tabAnimation:"smooth",theme:O,popoutUrl:"/popout.html"})}),I&&Nr.createPortal(s.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:I.x,top:I.y},children:Ae.map(z=>{if(z.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},z.id);let U=s.jsx(cp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{};switch(z.id){case"dockInWindow":case"dockBackToGrid":U=s.jsx(up,{size:13,className:"shrink-0 opacity-70"}),X=()=>{Ne(I.tabKey),M(null)};break;case"moveBackToMain":U=s.jsx(lp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{ke(I.tabKey),M(null)};break;case"floatAsPanel":U=s.jsx(dp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{fe(I.tabKey),M(null)};break;case"openInNewWindow":U=s.jsx(ip,{size:13,className:"shrink-0 opacity-70"}),X=()=>{je(I.tabKey),M(null)};break;case"setShortcut":X=re=>{re.stopPropagation(),ae(I.tabKey),M(null)};break;case"removeShortcut":U=s.jsx(jt,{size:13,className:"shrink-0 opacity-70"}),X=()=>{const re={...ce};delete re[I.tabKey],Ie(re),M(null)};break;case"hideTab":U=s.jsx(Co,{size:13,className:"shrink-0 opacity-70"}),X=()=>{ge(I.tabKey),M(null)};break}return s.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 ${z.tone==="muted"?"text-text-muted":""}`,onMouseDown:Iy,onClick:X,children:[U,s.jsx("span",{className:"flex-1 min-w-0",children:z.label}),z.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:z.shortcut}):null]},z.id)})}),I.sourceDocument.body),pe&&Nr.createPortal(s.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:()=>ae(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:z=>z.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",ve?"⌘+1":"Ctrl+1",", ",ve?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),be.body)]})}const ru="adhdev-recent-launch-args-v1",Dy=8;function nu(e){return String(e||"").trim().replace(/\s+/g," ")}function ni(e,t){return`${e.trim()}::${t.trim()}`}function ai(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(ru)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function au(e){if(!(typeof window>"u"))try{window.localStorage.setItem(ru,JSON.stringify(e))}catch{}}function bo(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=ai().byKey[ni(r,n)])==null?void 0:o.items)||[]}function ou(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=nu(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(p=>p!==o)].slice(0,Dy);l.byKey[c]={items:m},au(l)}function Ey(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=nu(r);if(!n||!a||!o)return;const l=ai(),c=ni(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(p=>p!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],au(l)}function iu(e){return!e.hasLoadedInitialResults&&!e.isLoading}function gn({title:e,description:t,action:r,children:n,className:a="",contentClassName:o=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),r?s.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?s.jsx("div",{className:t||r?`mt-3 ${o}`.trim():o,children:n}):null]})}function $y({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:r=0}){return e?"Refreshing saved history…":t?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 lu({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?zd(o):null,u=$y({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(gn,{title:"Saved history",description:zo(),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:l,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:Sx()})]}),children:[m?s.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:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:m.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),s.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function cu({setup:e,providerName:t,className:r=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.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 By({workspaceMode:e,activeKind:t,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:l}){return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),s.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=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===c.id?"btn-primary":"btn-secondary"}`,onClick:()=>l(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function _a(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Is(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Is(a,"acp"))?"acp":null}function sn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Oy({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ve,Kt;const u=Rr(),p=i.useMemo(()=>[...e].sort(Po),[e]),[b,w]=i.useState(((Ve=p[0])==null?void 0:Ve.id)||""),x=i.useMemo(()=>p.find(ee=>ee.id===b)||p[0],[b,p]),h=i.useMemo(()=>((x==null?void 0:x.workspaces)||[]).map(ee=>({id:ee.id,path:ee.path,label:ee.label})),[x]),g=(x==null?void 0:x.defaultWorkspaceId)||null,[y,f]=i.useState("workspace"),[A,C]=i.useState(""),[v,N]=i.useState(""),[T,k]=i.useState([]),[j,B]=i.useState(""),[L,S]=i.useState(!1),[D,$]=i.useState(null),[E,I]=i.useState(""),[M,F]=i.useState(_a(p[0])),[P,R]=i.useState(""),[K,V]=i.useState(""),[te,ie]=i.useState([]),[J,me]=i.useState(""),[je,ke]=i.useState([]),[q,ge]=i.useState(!1),[fe,we]=i.useState(!1),[xe,Ne]=i.useState(""),[Q,he]=i.useState(!1),[oe,ue]=i.useState(()=>Nt()),[le,de]=i.useState(null),[Z,ve]=i.useState(!1),[ce,pe]=i.useState(""),[ae,Ie]=i.useState(null),[Ce,_e]=i.useState(!1),[H,Me]=i.useState(""),[Ae,He]=i.useState([]),[Ge,Xe]=i.useState(!1),[Ye,tt]=i.useState(""),[ct,mt]=i.useState(!1),pt=i.useRef(null),O=i.useRef(0);i.useEffect(()=>{var ee;!b&&((ee=p[0])!=null&&ee.id)&&w(p[0].id)},[b,p]),i.useEffect(()=>{!x||!(!x.workspaces||!x.availableProviders||!x.detectedIdes||!x.recentLaunches)||u(x.id,{minFreshMs:3e4}).catch(()=>{})},[u,x]);const be=i.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(ee=>Is(ee,"cli")),[x]),Te=i.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(ee=>Is(ee,"acp")),[x]),Be=i.useMemo(()=>((x==null?void 0:x.detectedIdes)||[]).map(ee=>({id:ee.type,label:ee.name||ee.type,meta:ee.running?"Detected locally":"Available to open"})),[x]),qe=i.useMemo(()=>M==="cli"?be.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"CLI provider"})):M==="acp"?Te.map(ee=>({id:ee.type,label:ee.displayName||ee.type,meta:"ACP provider"})):Be,[Te,M,be,Be]),z=i.useMemo(()=>T.find(ee=>ee.id===j)||null,[T,j]),U=i.useMemo(()=>be.find(ee=>ee.type===P)||null,[be,P]),X=i.useMemo(()=>Bd(U==null?void 0:U.meshCoordinator,{meshId:(z==null?void 0:z.id)||"",workspace:(z==null?void 0:z.workspace)||""}),[U,z]),re=ae||X,W=i.useCallback(async ee=>{S(!0),I("");try{const $e=await c(ee);k($e),B(_=>{var Y;return $e.some(ye=>ye.id===_)?_:((Y=$e[0])==null?void 0:Y.id)||""}),$(ee)}catch($e){k([]),B(""),$(ee),I($e instanceof Error?$e.message:"Could not load meshes")}finally{S(!1)}},[c]);i.useEffect(()=>{var $e;if(!x)return;if(pt.current!==x.id){pt.current=x.id,f("workspace"),C(g||(($e=h[0])==null?void 0:$e.id)||"__home__"),N(""),k([]),B(""),$(null),I(""),F(_a(x)),R(""),V(""),me(""),ke([]),we(!1),Ne(""),ue(Nt()),pe(""),Ie(null);return}C(_=>{var Y;return _==="__custom__"||_==="__home__"||h.some(ye=>ye.id===_)?_:g||((Y=h[0])==null?void 0:Y.id)||"__home__"}),F(_=>_==="ide"&&Be.length>0||_==="cli"&&be.length>0||_==="acp"&&Te.length>0?_:_a(x))},[Te.length,be.length,g,Be.length,x,h]),i.useEffect(()=>{!x||y!=="mesh"||D===x.id||L||W(x.id)},[W,D,L,x,y]),i.useEffect(()=>{y==="mesh"&&M!=="cli"&&be.length>0&&F("cli")},[M,be.length,y]),i.useEffect(()=>{var ee;M&&(qe.some($e=>$e.id===P)||R(((ee=qe[0])==null?void 0:ee.id)||""))},[M,qe,P]),i.useEffect(()=>{Ie(null)},[x==null?void 0:x.id,j,P,y]);const G=i.useCallback(async(ee,$e)=>{const _=O.current+1;return O.current=_,ge(!0),Ne(""),m(ee,$e).then(Y=>{O.current===_&&ke(Y)}).catch(Y=>{O.current===_&&(ke([]),Ne(Y instanceof Error?Y.message:"Could not load saved sessions"))}).finally(()=>{O.current===_&&(ge(!1),we(!0))})},[m]),se=i.useCallback((ee,$e)=>{ie(bo(ee,$e))},[]);i.useEffect(()=>{O.current+=1,me(""),ue(Nt()),!x||!P||M==="ide"?ie([]):se(x.id,P),we(!1),ke([]),Ne(""),ge(!1)},[M,se,G,x,P]),i.useEffect(()=>{if(!J)return;const ee=je.find($e=>$e.providerSessionId===J);ee!=null&&ee.canResume||me("")},[je,J]);const ne=A==="__custom__"?v.trim():A==="__home__"?"":((Kt=h.find(ee=>ee.id===A))==null?void 0:Kt.path)||"",Se=i.useMemo(()=>x?t.filter(ee=>ee.id!==x.id&&ee.daemonId===x.id).map(ee=>ee.workspace):[],[t,x]),Ee=i.useMemo(()=>((x==null?void 0:x.recentLaunches)||[]).map(ee=>ee.workspace),[x]),Oe=i.useCallback(ee=>{const $e=String(ee.workspace||"").trim();if(!$e)return;const _=h.find(Y=>sn(Y.path)===sn($e));if(_){C(_.id),N("");return}C("__custom__"),N($e)},[h]),Re=i.useCallback(ee=>{const $e=String(ee.workspace||"").trim();if(!$e)return{workspaceId:null,workspacePath:null};const _=h.find(Y=>sn(Y.path)===sn($e));return _?{workspaceId:_.id,workspacePath:null}:{workspaceId:null,workspacePath:$e}},[h]),Fe=i.useMemo(()=>je.find(ee=>ee.providerSessionId===J)||null,[je,J]),Ue=i.useMemo(()=>{var $e;if(M!=="cli"||!x||!P)return null;const ee=(($e=be.find(_=>_.type===P))==null?void 0:$e.displayName)||P;return{routeId:x.id,daemonId:x.id,providerSessionId:J||void 0,transport:"pty",mode:"chat",agentName:ee,agentType:P,status:"idle",title:ee,messages:[],ideType:P,workspaceName:ne,workspacePath:ne,displayPrimary:ee,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${x.id}:${P}`,machineName:Lt(x,{fallbackId:x.id})}},[M,be,ne,x,J,P]),Le=i.useCallback(()=>{var $e;if(!x)return;C("__custom__"),_e(!0),tt("");const ee=Jn(x.platform,Xn(v.trim(),ne,Se,Ee,x.defaultWorkspacePath,($e=h.find(_=>_.id===g))==null?void 0:$e.path,h.map(_=>_.path)));Xe(!0),n(x.id,ee).then(_=>{Me(_.path),N(_.path),He(_.directories)}).catch(_=>{tt(_ instanceof Error?_.message:"Could not load folder")}).finally(()=>Xe(!1))},[v,g,Ee,Se,n,ne,x,h]),Ze=i.useCallback(ee=>{x&&(Xe(!0),tt(""),n(x.id,ee).then($e=>{Me($e.path),N($e.path),He($e.directories)}).catch($e=>{tt($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>Xe(!1)))},[n,x]),et=i.useCallback(async()=>{if(!x||!ne)return;mt(!0),pe("");const ee=await a(x.id,ne);if(mt(!1),!ee.ok){pe(ee.error||"Could not save workspace");return}pe("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,ne,x]),gt=i.useCallback(async()=>{if(!x)return;if(y==="mesh"){if(!j||!P)return;ve(!0),pe(""),Ie(null);const _=await d(x.id,j,P);if(ve(!1),!_.ok){if(_.code==="mesh_coordinator_manual_mcp_setup_required"&&_.manualSetup){Ie(_.manualSetup),pe("Manual MCP setup required before this provider can act as mesh coordinator.");return}pe(_.error||"Could not start mesh coordinator");return}r();return}if(!M||!P)return;ve(!0),pe("");const ee=K.trim()?K.trim().split(/\s+/).filter(Boolean):[],$e=M==="ide"?await o(x.id,P,{workspacePath:ne||null}):await l(x.id,M,P,{workspaceId:A!=="__home__"&&A!=="__custom__"?A:null,workspacePath:A==="__custom__"&&ne||null,resumeSessionId:M==="cli"&&J?J:null,cliArgs:ee});if(ve(!1),!$e.ok){pe($e.error||"Could not start session");return}M!=="ide"&&K.trim()&&(ou(x.id,P,K),se(x.id,P)),r()},[M,K,se,r,o,d,l,ne,x,j,J,P,A,y]),yt=y==="mesh"?"Start mesh coordinator":M?nd(M,M==="cli"&&!!J):"Start",dt=y==="mesh"?"Starting coordinator…":M?ad(M,M==="cli"&&!!J):"Starting…",xt=p.length>5;return x?s.jsxs(s.Fragment,{children:[s.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:s.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:[s.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:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),s.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."})]}),s.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:s.jsx(jt,{size:16})})]}),s.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:[s.jsx(gn,{title:"Machine",children:xt?s.jsx("select",{"aria-label":"Machine",value:x.id,onChange:ee=>w(ee.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Z,children:p.map(ee=>s.jsx("option",{value:ee.id,children:Lt(ee,{fallbackId:ee.id})},ee.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:p.map(ee=>{const $e=Lt(ee,{fallbackId:ee.id}),_=x.id===ee.id;return s.jsxs("button",{type:"button","aria-label":`Select machine ${$e}`,"aria-pressed":_,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${_?"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:()=>w(ee.id),disabled:Z,title:$e,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${ee.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:$e})]},ee.id)})})}),s.jsxs(gn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:y==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:Z,children:"Browse…"}):void 0,children:[s.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(ee=>s.jsxs("button",{type:"button",role:"radio","aria-checked":y===ee.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${y===ee.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:()=>{f(ee.id),pe(""),ee.id==="mesh"&&x&&D!==x.id&&!L&&W(x.id)},disabled:Z,children:[s.jsx("div",{className:"text-sm font-semibold",children:ee.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:ee.desc})]},ee.id))}),y==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:A,onChange:ee=>{const $e=ee.target.value;C($e),$e==="__custom__"?Le():pe("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Z,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),h.map(ee=>s.jsxs("option",{value:ee.id,children:[ee.id===g?"⭐ ":"",zn(ee.path,ee.label)||ee.path]},ee.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:A==="__home__"?"Launch without a workspace.":ne||"Select a workspace folder."}),A==="__custom__"&&ne&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Le,disabled:Z,children:[s.jsx(Ss,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:Z||ct,children:ct?"Saving…":"Save workspace"})]})]}):s.jsxs("div",{className:"space-y-3",children:[L&&s.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!L&&E&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:E}),!L&&!E&&T.length===0&&s.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."}),T.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:T.map(ee=>s.jsxs("button",{type:"button",role:"radio","aria-checked":j===ee.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${j===ee.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>B(ee.id),disabled:Z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ee.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[ee.repoIdentity||"Repo mesh",typeof ee.nodesCount=="number"?` · ${ee.nodesCount} node${ee.nodesCount===1?"":"s"}`:""]}),ee.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",ee.workspace]})]},ee.id))}),z&&s.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),s.jsx(By,{workspaceMode:y,activeKind:M,cliEnabled:be.length>0,ideEnabled:Be.length>0,acpEnabled:Te.length>0,busy:Z,onSelect:F}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:M==="ide"?"Choose IDE":M==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[qe.map(ee=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===ee.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>R(ee.id),disabled:Z,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ee.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ee.meta})]},ee.id)),qe.length===0&&s.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"&&re&&s.jsx(cu,{setup:re,providerName:(U==null?void 0:U.displayName)||(U==null?void 0:U.name)||P}),y!=="mesh"&&M!=="ide"&&s.jsxs(gn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:K,onChange:ee=>V(ee.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Z}),te.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:te.map(ee=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>V(ee),disabled:Z,title:ee,children:ee},ee))})]}),y!=="mesh"&&M==="cli"&&s.jsx(lu,{busy:Z,savedSessionsLoading:q,savedSessionsError:xe,selectedSession:Fe,onRefresh:()=>{!x||!P||G(x.id,P)},onOpenHistory:()=>{!x||!P||(he(!0),iu({hasLoadedInitialResults:fe,isLoading:q})&&G(x.id,P))},onClearSelection:()=>me("")}),ce&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${ce.includes("saved")||ce.includes("requested")||ce.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:ce})]}),s.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:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:Z,children:"Cancel"}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:gt,disabled:Z||(y==="mesh"?!j||!P||M!=="cli"||L:!M||!P||A==="__custom__"&&!ne),children:[s.jsx(Mo,{size:14}),Z?dt:yt]})]})]})}),Ce&&s.jsx(Zn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:H,directories:Ae,busy:Ge,error:Ye,onClose:()=>_e(!1),onNavigate:Ze,onConfirm:ee=>{N(ee),Me(ee),C("__custom__"),_e(!1)}}),Q&&Ue&&s.jsx(qo,{activeConv:Ue,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:je,isSavedSessionsLoading:q,isResumingSavedSessionId:le,savedHistoryFilters:oe,missingWorkspaceResumePath:ne||null,onSavedHistoryFiltersChange:ue,onClose:()=>he(!1),onNewChat:()=>{me(""),he(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!x||!P||G(x.id,P)},onResumeSavedSession:ee=>{if(!x||!P||le||!ee.canResume)return;const $e=Re(ee);me(ee.providerSessionId),Oe(ee),de(ee.providerSessionId),he(!1),ve(!0),pe(""),l(x.id,"cli",P,{workspaceId:$e.workspaceId,workspacePath:$e.workspacePath,resumeSessionId:ee.providerSessionId}).then(_=>{if(!_.ok){pe(_.error||"Could not resume session");return}r()}).finally(()=>{ve(!1),de(_=>_===ee.providerSessionId?null:_)})}})]}):null}function du(e){return e.ahead<=0&&e.behind<=0?null:e.ahead>0&&e.behind>0?`ahead ${e.ahead} / behind ${e.behind}`:e.behind>0?`behind ${e.behind}`:`ahead ${e.ahead}`}function oi(e){if(e.type==="submoduleNode")return e.outOfSync||e.error?{label:"submodule drift",tone:"danger"}:e.dirty?{label:"submodule dirty",tone:"warn"}:null;const t=e.branchConvergence;if((t==null?void 0:t.status)==="not_mergeable")return{label:e.hasConflicts?"conflicts present":"dirty workspace",tone:"danger"};if((t==null?void 0:t.status)==="blocked_review"){if(t.reason==="upstream_unverified")return{label:"upstream unverified",tone:"warn"};const r=du(e);return r?{label:r,tone:"danger"}:!e.upstream&&e.branch&&e.branch!==t.defaultBranch?{label:"push branch",tone:"warn"}:{label:"blocked review",tone:"danger"}}return(t==null?void 0:t.status)==="pushed_feature_branch_needs_merge"?{label:"needs merge",tone:"warn"}:(t==null?void 0:t.status)==="cleanup_candidate"?{label:"refine worktree",tone:"info"}:e.isOrphan?{label:"needs follow-up",tone:"warn"}:e.health==="offline"?{label:"offline",tone:"danger"}:null}function ii(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function uu(e){var t;return!ii(e)||e.type==="defaultBranchNode"?!1:!!((t=e.branchConvergence)!=null&&t.needsConvergence||e.isOrphan||e.hasConflicts||e.outOfSync||e.error||e.health==="offline"||e.health==="degraded"||e.health==="wrong_branch"||e.dirty)}function rn(e){return[...new Set(e.filter(t=>!!t))]}function Fy(e){const t=e.nodes.find(l=>l.type==="defaultBranchNode")??null,r=(t==null?void 0:t.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=e.nodes.filter(l=>l.type!=="submoduleNode");return t||n.length>0?rn([t==null?void 0:t.id,...n.map(l=>l.id)]):a.length>0?rn(a.map(l=>l.id)):o.length>0?rn(o.map(l=>l.id)):rn(e.nodes.map(l=>l.id))}function mu(e){const t=[...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}::${t}::${r}`}function Wy(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${mu(e)}::${n}x${a}`}const Hy={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"},Ky={default:"border-slate-300 bg-white/95 text-slate-700",good:"border-emerald-300 bg-emerald-50 text-emerald-700",warn:"border-amber-300 bg-amber-50 text-amber-700",danger:"border-rose-300 bg-rose-50 text-rose-700",info:"border-sky-300 bg-sky-50 text-sky-700"},Uy={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"},zy={default:"border-slate-300 bg-white text-slate-700 hover:bg-slate-50",info:"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"};function Zs(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[rgba(148,163,184,0.22)] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"flex h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 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",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"text-slate-500",rowValueClass:"max-w-[65%] break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-500",panelFieldValueClass:"break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>Ky[t],actionButton:t=>zy[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative w-full min-w-0 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))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",dialogShellClass:"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)]",dialogHeaderClass:"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",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"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",dialogBodyClass:"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",dialogEmptyClass:"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",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"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",rowLabelClass:"text-slate-400",rowValueClass:"max-w-[65%] break-all text-right text-slate-100",panelShellClass:"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",panelEmptyClass:"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",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"text-slate-400",panelFieldValueClass:"break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>Hy[t],actionButton:t=>Uy[t]}}const It={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,columnGap:540,edgeLabelBuffer:180,defaultToContentGap:136,worktreeStackGap:82,parentToSubmoduleGap:48,submoduleStackGap:36,submoduleIndentX:72,placeholderTopOffset:0};function nn(e,t,r){const n=(e||"").trim();return n?Math.max(1,Math.min(r,Math.ceil(n.length/t))):0}function Gy(e){let t=1;return e.type==="submoduleNode"&&(t+=1),e.branch&&e.type!=="submoduleNode"&&(t+=1),e.submoduleCommit&&e.type==="submoduleNode"&&(t+=1),e.dirty&&(t+=1),e.outOfSync&&(t+=1),e.hasConflicts&&(t+=1),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&(t+=1),e.isOrphan&&(t+=1),t}function li(e){return e.type==="submoduleNode"?It.submoduleCardWidth:It.worktreeCardWidth}function pu(e){var r;if(e.type==="defaultBranchNode")return e.nextStepHint||"Default branch anchor";if(e.type==="submoduleNode"){const n=[e.machineLabel?`parent ${e.machineLabel}`:null];return e.outOfSync?n.push("out of sync"):e.dirty?n.push("local changes"):n.push("synced"),n.filter(Boolean).join(" · ")}const t=[];if(e.upstream&&t.push(e.upstream),e.upstream&&e.upstreamStatus!=="fresh")t.push("upstream unverified");else{const n=du(e);n&&t.push(n)}return e.activeSessionCount>0&&t.push(`${e.activeSessionCount} session${e.activeSessionCount===1?"":"s"}`),e.dirtyFiles>0&&t.push(`${e.dirtyFiles} dirty`),e.hasConflicts&&t.push("conflicts"),t.length===0?(r=e.branchConvergence)!=null&&r.needsConvergence?"Needs follow-up":"Clean and even with upstream":t.join(" · ")}function yn(e){const t=li(e),r=e.type==="submoduleNode"?24:30,n=Math.ceil(Gy(e)/(e.type==="submoduleNode"?2:3)),a=nn(e.label,r,2),o=nn(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,r,2),l=nn(pu(e),r+4,3),c=oi(e),d=uu(e)?ii(e):null,m=nn(d,Math.max(24,Math.floor(t/8)),4),u=52+a*18+o*14+(c?30:0)+n*24+Math.max(22,l*18)+(m>0?22+m*16:0),p=e.type==="submoduleNode"?It.minSubmoduleCardHeight:It.minWorktreeCardHeight;return Math.min(It.maxEstimatedCardHeight,Math.max(p,Math.ceil(u)))}function La(e,t){return e.type==="defaultBranchNode"&&t.type!=="defaultBranchNode"?-1:t.type==="defaultBranchNode"&&e.type!=="defaultBranchNode"||e.type==="submoduleNode"&&t.type!=="submoduleNode"?1:t.type==="submoduleNode"&&e.type!=="submoduleNode"?-1:e.branch&&t.branch&&e.branch!==t.branch?e.branch.localeCompare(t.branch):e.branch&&!t.branch?-1:!e.branch&&t.branch?1:e.label.localeCompare(t.label)}function Vy(e){return e?Math.min(260,Math.max(72,e.length*7+26)):0}function qy(e){const t=e.edges.reduce((r,n)=>Math.max(r,Vy(n.label)),0);return Math.max(It.columnGap,It.worktreeCardWidth+t+It.edgeLabelBuffer)}function an(e,t,r,n=!0){return{id:e.id,type:"meshNode",position:{x:t,y:r},graphNode:e,selected:!1,draggable:!1,selectable:n}}function on(e,t,r){return{id:e.id,x:t,y:r,width:li(e),height:yn(e)}}function Yy(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:null,locality:"unknown",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,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${e.id}__placeholder`,machineLabel:"",workspace:t.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}}function Xy(e){const t=[...e.nodes].sort(La),r=t.find(g=>g.type==="defaultBranchNode")??null,n=new Map;for(const g of t){if(g.type!=="submoduleNode"||!g.parentNodeId)continue;const y=n.get(g.parentNodeId)??[];y.push(g),n.set(g.parentNodeId,y)}const a=t.filter(g=>g.id!==(r==null?void 0:r.id)&&g.type!=="submoduleNode"),o=new Map,l=[];for(const g of a){if(g.isOrphan||!g.branch){l.push(g);continue}const y=o.get(g.branch)??[];y.push(g),o.set(g.branch,y)}const c=[...o.entries()].sort(([g],[y])=>r!=null&&r.branch&&g===r.branch&&y!==r.branch?-1:r!=null&&r.branch&&y===r.branch&&g!==r.branch?1:g.localeCompare(y));l.length>0&&c.push(["__orphans__",[...l].sort(La)]),c.length===0&&c.push(["__nodes__",[]]);const d=[],m=[],u=c.length,p=qy(e),b=Math.max(1,u-1)*p,w=r?0:96,x=r?yn(r):0,h=r?w+x+It.defaultToContentGap:0;if(r){const g=b/2;d.push(an(r,g,w)),m.push(on(r,g,w))}return c.forEach(([g,y],f)=>{const A=f*p,C=y.length>0?y:a.length>0?a:[];let v=h;if(C.forEach(N=>{const T=yn(N);d.push(an(N,A,v)),m.push(on(N,A,v));const k=[...n.get(N.id)??[]].sort(La);if(k.length>0){let j=v+T+It.parentToSubmoduleGap;k.forEach(B=>{const L=A+It.submoduleIndentX,S=yn(B);d.push(an(B,L,j)),m.push(on(B,L,j)),j+=S+It.submoduleStackGap}),v=j+It.worktreeStackGap-It.submoduleStackGap;return}v+=T+It.worktreeStackGap}),g==="__nodes__"&&a.length===0&&r){const N=Yy(r,e),T=h+It.placeholderTopOffset;d.push(an(N,A,T,!1)),m.push(on(N,A,T))}}),{nodes:d,bounds:m,columnGap:p}}function Jy(e){var t,r;return[e.id,e.type,e.label,e.branch??"",e.upstream??"",e.upstreamStatus??"",e.daemonId??"",e.machineId??"",e.machineLabel??"",e.locality,e.health,e.ahead,e.behind,e.dirty?1:0,e.dirtyFiles,e.hasConflicts?1:0,e.activeSessionCount,e.isOrphan?1:0,e.outOfSync?1:0,e.snapshotCompleteness,((t=e.branchConvergence)==null?void 0:t.status)??"",(r=e.branchConvergence)!=null&&r.needsConvergence?1:0,e.nextStepHint??"",e.error??"",e.parentNodeId??"",e.submodulePath??"",e.submoduleCommit??""].join("|")}function hu(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function Qy(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(Jy),...e.edges.map(hu)].join("::")}function Zy(e){return[e.meshId,e.nodes.length,e.edges.length,...e.nodes.map(t=>{var r,n;return[t.id,t.type,t.label,t.branch??"",t.machineLabel??"",t.locality,t.health,t.dirty?1:0,t.dirtyFiles,t.hasConflicts?1:0,t.activeSessionCount,t.isOrphan?1:0,t.outOfSync?1:0,t.snapshotCompleteness,((r=t.branchConvergence)==null?void 0:r.status)??"",(n=t.branchConvergence)!=null&&n.needsConvergence?1:0,t.nextStepHint??"",t.parentNodeId??"",t.submodulePath??"",t.submoduleCommit??""].join("|")}),...e.edges.map(hu)].join("::")}const fu=i.createContext(Zs("dark"));function e0(e,t,r){const n=t?"border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":r?"border-white/10 shadow-[0_18px_48px_rgba(3,7,18,0.22)]":"border-slate-300/90 shadow-[0_18px_48px_rgba(148,163,184,0.20)]",a=oi(e);if((a==null?void 0:a.tone)==="danger")return`${n} ${r?"bg-rose-500/12":"bg-rose-50/95"}`;if((a==null?void 0:a.tone)==="warn")return`${n} ${r?"bg-amber-500/10":"bg-amber-50/95"}`;if((a==null?void 0:a.tone)==="info")return`${n} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${n} ${r?"bg-emerald-500/8":"bg-emerald-50/95"}`;case"dirty":return`${n} ${r?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${n} ${r?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${n} ${r?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${n} ${r?"bg-slate-500/12":"bg-slate-100/95"}`;default:return`${n} ${r?"bg-slate-950/78":"bg-white/96"}`}}function Ut(e,t){switch(e){case"health":return t?"border-white/10 bg-slate-950/60 text-slate-200":"border-slate-300 bg-white/95 text-slate-700";case"dirty":return t?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700";case"conflict":return t?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700";case"orphan":return t?"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200":"border-fuchsia-300 bg-fuchsia-50 text-fuchsia-700";case"submodule":return t?"border-violet-400/25 bg-violet-500/10 text-violet-200":"border-violet-300 bg-violet-50 text-violet-700";case"meta":default:return t?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}}function t0(e,t){switch(e){case"danger":return t?"border-rose-400/35 bg-rose-500/14 text-rose-50":"border-rose-300 bg-rose-50 text-rose-700";case"warn":return t?"border-amber-400/35 bg-amber-500/14 text-amber-50":"border-amber-300 bg-amber-50 text-amber-700";case"info":return t?"border-violet-400/35 bg-violet-500/14 text-violet-50":"border-violet-300 bg-violet-50 text-violet-700";case"good":default:return t?"border-emerald-400/35 bg-emerald-500/12 text-emerald-50":"border-emerald-300 bg-emerald-50 text-emerald-700"}}function s0(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 r0(e){return e.replace(/_/g," ")}function Ra(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function n0(e){return e.locality==="remote"?"meta":"health"}function a0({data:e,selected:t}){const r=i.useContext(fu),n=e.graphNode,a=n.type==="defaultBranchNode",o=n.type==="submoduleNode",l=uu(n),c=a?"default branch anchor":o?n.submodulePath||"submodule checkout":[n.machineLabel,Ra(n.locality)].filter(Boolean).join(" · ")||n.workspace,d=n.submoduleCommit?n.submoduleCommit.slice(0,7):null,m=oi(n),u=pu(n),p=ii(n);return s.jsxs("div",{className:`${o?"w-[228px]":"w-[256px]"} rounded-2xl border px-4 py-3.5 backdrop-blur-sm transition-all ${e0(n,t,r.isDark)}`,style:{width:li(n)},title:[n.machineLabel?`Machine: ${n.machineLabel}`:null,n.machineId?`Machine id: ${n.machineId}`:null,n.daemonId?`Daemon: ${n.daemonId}`:null,`Locality: ${Ra(n.locality)}`,n.workspace?`Workspace: ${n.workspace}`:null].filter(Boolean).join(`
|
|
65
|
+
`),children:[s.jsx(Si,{type:"target",position:Ni.Top,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${r.textPrimary}`,children:n.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:c})]}),s.jsx("span",{className:"mt-0.5 h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:s0(n.health)},"aria-hidden":!0})]}),m&&s.jsx("div",{className:`mt-3 inline-flex max-w-full items-center rounded-full border px-2.5 py-1 text-[10px] font-semibold uppercase tracking-[0.16em] ${t0(m.tone,r.isDark)}`,children:s.jsx("span",{className:"truncate",children:m.label})}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-1.5 text-[10px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Ut("health",r.isDark)}`,children:r0(n.health)}),o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ut("submodule",r.isDark)}`,children:"submodule"}),!a&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ut(n0(n),r.isDark)}`,children:Ra(n.locality)}),n.branch&&!o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ut("meta",r.isDark)}`,children:n.branch}),d&&o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ut("meta",r.isDark)}`,children:d}),n.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ut("dirty",r.isDark)}`,children:o?"local changes":`${n.dirtyFiles} dirty`}),n.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ut("conflict",r.isDark)}`,children:"out of sync"}),n.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ut("conflict",r.isDark)}`,children:"conflicts"}),!o&&n.upstream&&n.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ut("orphan",r.isDark)}`,children:"upstream unverified"}),n.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Ut("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,children:u}),l&&p&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,children:p}),s.jsx(Si,{type:"source",position:Ni.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const o0={meshNode:a0};function i0(e,t=Zs("dark")){const n=Xy(e).nodes.map(o=>({id:o.id,type:o.type,position:o.position,data:{graphNode:o.graphNode},selected:o.selected,draggable:o.draggable,selectable:o.selectable})),a=e.edges.map(o=>({id:o.id,source:o.source,target:o.target,label:o.label,type:o.type==="worktreeLink"||o.type==="submoduleLink"?"smoothstep":"bezier",animated:o.type==="orphanLink",markerEnd:o.direction==="directed"?{type:mm.ArrowClosed,width:o.type==="submoduleLink"?16:18,height:o.type==="submoduleLink"?16:18,color:Ll(o)}:void 0,style:{stroke:Ll(o),strokeWidth:o.type==="orphanLink"?2.25:o.type==="submoduleLink"?1.7:o.type==="worktreeLink"?1.8:2,strokeDasharray:o.type==="orphanLink"?"5 4":o.type==="submoduleLink"?"4 3":void 0},labelStyle:{fill:t.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:t.edgeLabelBackgroundColor,fillOpacity:1,stroke:t.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}));return{nodes:n,edges:a}}function Ll(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 l0(e){const t=e.data.graphNode;if(t.locality==="local")return"#38bdf8";switch(t.health){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":case"offline":return"#fb7185";case"wrong_branch":return"#a78bfa";default:return"#94a3b8"}}function c0({data:e,viewportKey:t}){const r=pm(),n=hm(),a=i.useRef(null),o=i.useMemo(()=>mu(e),[e]),l=i.useMemo(()=>Fy(e),[e]);return i.useEffect(()=>{if(!r||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const m=l.length>0&&l.length<e.nodes.length;n.fitView({nodes:m?l.map(u=>({id:u})):void 0,padding:m?.24:.2,maxZoom:m?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,l,o,r,n,t]),null}function d0({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=Qs(),a=i.useMemo(()=>Zs(n),[n]),o=i.useMemo(()=>Qy(e),[e]),l=i.useMemo(()=>Zy(e),[e]),c=i.useMemo(()=>i0(e,a),[l,a]),d=i.useRef(null),[m,u]=i.useState({width:0,height:0}),p=i.useMemo(()=>Wy(e,m.width,m.height),[o,e,m.height,m.width]),b=i.useMemo(()=>c.nodes.map(w=>({...w,selected:w.id===t})),[c.nodes,t]);return i.useEffect(()=>{const w=d.current;if(!w)return;const x=()=>{const g=Math.max(0,Math.round(w.clientWidth)),y=Math.max(0,Math.round(w.clientHeight));u(f=>f.width===g&&f.height===y?f:{width:g,height:y})};x();const h=typeof ResizeObserver=="function"?new ResizeObserver(()=>x()):null;return h==null||h.observe(w),window.addEventListener("resize",x),()=>{h==null||h.disconnect(),window.removeEventListener("resize",x)}},[]),s.jsx(fu.Provider,{value:a,children:s.jsxs("div",{ref:d,className:a.graphShellClass,children:[s.jsxs("div",{className:`absolute inset-x-3 top-3 z-10 flex flex-wrap items-center justify-between gap-2 text-[11px] ${a.textSecondary}`,children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),s.jsxs("span",{className:a.graphStatChipClass,children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&s.jsxs("span",{className:a.isDark?"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100":"rounded-full border border-orange-300 bg-orange-50 px-3 py-1 text-orange-700",children:[e.stats.orphanNodes," need attention"]})]}),s.jsx("div",{className:a.graphHintChipClass,children:"Focused on the main path first · drag or scroll to pan"})]}),s.jsx("div",{className:"h-[460px] w-full min-w-0 min-h-[460px] sm:h-[560px] xl:h-[680px]",children:s.jsxs(im,{nodes:b,edges:c.edges,nodeTypes:o0,minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(w,x)=>r==null?void 0:r(x.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(c0,{data:e,viewportKey:p}),s.jsx(lm,{className:a.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),s.jsx(cm,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:l0,nodeStrokeWidth:3,className:a.isDark?"overflow-hidden rounded-xl border border-white/10 bg-slate-950/85":"overflow-hidden rounded-xl border border-slate-200 bg-white/95"}),s.jsx(dm,{variant:um.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})}function ft(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Pe(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function _t(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function $t(...e){for(const t of e)if(typeof t=="boolean")return t}function Pa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function ci(e){switch(e){case"fresh":return 30;case"no_upstream":return 4;case"unchecked":case void 0:return 0;case"stale":return-10;case"unavailable":return-15;default:return 0}}function u0(e,t){const r=typeof e=="string"?e.trim().replace(/[\\/]+$/,""):"",n=typeof t=="string"?t.trim():"";if(n){if(/^(?:[A-Za-z]:[\\/]|\/)/.test(n))return n;if(r)return`${r}/${n.replace(/^[\\/]+/,"")}`}}function m0(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=ft(n),o=Pe(a.path),l=Pe(a.commit),c=Pe(a.repoPath,a.repo_root)??u0(t,o);return!o||!l||!c?null:{path:o,commit:l,repoPath:c,dirty:$t(a.dirty)??!1,outOfSync:$t(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:_t(a.lastCheckedAt,a.last_checked_at)??Date.now(),...Pe(a.error)?{error:Pe(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function p0(e){return $t(e.isGitRepo)!==void 0||!!Pe(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||_t(e.ahead,e.behind,e.staged,e.modified,e.untracked,e.deleted,e.renamed,e.lastCheckedAt,e.last_checked_at)!==void 0||Array.isArray(e.submodules)&&e.submodules.length>0}function vn(e,t,r){const n=$t(e.isGitRepo);if(!Object.keys(e).length||!p0(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(x=>typeof x=="string"):[],l=_t(e.conflicts)??o.length,c=$t(e.hasConflicts)??l>0,d=Pe(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=m0(e.submodules,d),u=Pe(e.upstreamStatus,e.upstream_status),p=_t(e.upstreamFetchedAt,e.upstream_fetched_at),b=Pe(e.upstreamFetchError,e.upstream_fetch_error),w=Pe(e.error);return{workspace:Pe(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:Pe(e.branch)??null,headCommit:Pe(e.headCommit)??null,headMessage:Pe(e.headMessage)??null,upstream:Pe(e.upstream)??null,upstreamStatus:u??"unchecked",...p!==void 0?{upstreamFetchedAt:p}:{},...b?{upstreamFetchError:b}:{},ahead:_t(e.ahead)??0,behind:_t(e.behind)??0,staged:_t(e.staged)??0,modified:_t(e.modified)??0,untracked:_t(e.untracked)??0,deleted:_t(e.deleted)??0,renamed:_t(e.renamed)??0,hasConflicts:c,conflictFiles:o,stashCount:_t(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??_t(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...w?{error:w}:{}}}function h0(e){if(!e)return Number.NEGATIVE_INFINITY;let t=0;return e.isGitRepo===!0&&(t+=50),e.isGitRepo===!1&&(t-=10),e.branch&&(t+=20),e.headCommit&&(t+=20),e.upstream&&(t+=10),t+=ci(e.upstreamStatus),typeof e.ahead=="number"&&(t+=2),typeof e.behind=="number"&&(t+=2),Array.isArray(e.submodules)&&e.submodules.length>0&&(t+=4+e.submodules.length),e.error&&(t-=20),t}function f0(e){const t=ft(e.lastGit??e.last_git),r=ft(t.result),n=ft(t.status),a=ft(r.status),o=ft(e.lastProbe??e.last_probe),l=ft(o.git),c=ft(l.result),d=ft(l.status),m=ft(c.status);let u=null;for(const p of[n,a,d,m]){const b=vn(p,e,{lastCheckedAt:Date.now()});if(!b)continue;const w=h0(b);(!u||w>u.score)&&(u={git:b,score:w})}return u==null?void 0:u.git}function x0(e){const t=Array.isArray(e==null?void 0:e.submodules)?e.submodules:[];let r=!1,n=!1;for(const a of t)a!=null&&a.outOfSync&&(n=!0),a!=null&&a.dirty&&(r=!0);return{dirty:r,outOfSync:n}}function b0(e){return e?(e.staged??0)>0||(e.modified??0)>0||(e.untracked??0)>0||(e.deleted??0)>0||(e.renamed??0)>0||e.hasConflicts===!0:!1}function On(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=x0(e);return t.outOfSync?"degraded":t.dirty||b0(e)?"dirty":"online"}function g0(e,t){const r=t?On(t):void 0;return!e||e==="unknown"?r:e}function y0(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:null;if(t){const a=t.map(o=>{const l=ft(o),c=Pe(l.sessionId,l.session_id,l.id);return c?{sessionId:c,...Pe(l.providerType,l.provider)?{providerType:Pe(l.providerType,l.provider)}:{},...Pe(l.state,l.status)?{state:Pe(l.state,l.status)}:{},...Pe(l.lifecycle)?{lifecycle:Pe(l.lifecycle)}:{},...Pe(l.surfaceKind,l.surface_kind)?{surfaceKind:Pe(l.surfaceKind,l.surface_kind)}:{},...Pe(l.recoveryState,l.recovery_state)?{recoveryState:Pe(l.recoveryState,l.recovery_state)}:{},...Pe(l.workspace)?{workspace:Pe(l.workspace)}:{},...Pe(l.title)?{title:Pe(l.title)}:{},...Pe(l.lastActivityAt,l.last_activity_at)?{lastActivityAt:Pe(l.lastActivityAt,l.last_activity_at)}:{},...$t(l.isCached,l.is_cached)!==void 0?{isCached:$t(l.isCached,l.is_cached)}:{}}:null}).filter(o=>o!==null);if(a.length>0)return a}const r=ft(e.activeSession??e.active_session),n=Pe(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...Pe(r.providerType,r.provider)?{providerType:Pe(r.providerType,r.provider)}:{},...Pe(r.state,r.status)?{state:Pe(r.state,r.status)}:{}}]}function v0(e){const t=ft(e.connection);return Object.keys(t).length>0?t:void 0}function w0(e){const t=e==null?void 0:e.source,r=e==null?void 0:e.transport;return{...e,perspective:(e==null?void 0:e.perspective)??"selected_coordinator",source:t&&t!=="not_reported"?t:"mesh_peer_status",state:"connected",transport:r&&r!=="unknown"?r:"direct",reported:!0,reason:"Live peer git snapshot reported by the selected coordinator."}}function di(e){var r;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((r=t.submodules)==null?void 0:r.length)??0)>0))}function Rl(e){var n,a,o,l,c,d;let t=0;const r=e.git;return di(e)&&(t+=80,(r==null?void 0:r.isGitRepo)===!0&&(t+=20),(r==null?void 0:r.isGitRepo)===!1&&(t+=5),r!=null&&r.branch&&(t+=20),r!=null&&r.upstream&&(t+=12),r!=null&&r.headCommit&&(t+=12),t+=ci(r==null?void 0:r.upstreamStatus),typeof(r==null?void 0:r.lastCheckedAt)=="number"&&(t+=6),t+=(((n=r==null?void 0:r.submodules)==null?void 0:n.length)??0)*6),(a=e.branchConvergence)!=null&&a.status&&(t+=12),(((o=e.connection)==null?void 0:o.state)==="connected"||((l=e.connection)==null?void 0:l.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((d=e.connection)==null?void 0:d.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function j0(e,t){var x,h,g,y;const r=Rl(e),a=Rl(t)>r?t:e,o=a===t?e:t,l=a.git??o.git,c=(((x=a.providers)==null?void 0:x.length)??0)>0?a.providers:o.providers,d=(((h=a.activeSessions)==null?void 0:h.length)??0)>0?a.activeSessions:o.activeSessions,m=(((g=a.activeSessionDetails)==null?void 0:g.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,u=(((y=a.providerPriority)==null?void 0:y.length)??0)>0?a.providerPriority:o.providerPriority,p=a.connection??o.connection,b={...o,...a,machineLabel:a.machineLabel||o.machineLabel,workspace:a.workspace||o.workspace,...a.repoRoot||o.repoRoot?{repoRoot:a.repoRoot||o.repoRoot}:{},...a.daemonId||o.daemonId?{daemonId:a.daemonId||o.daemonId}:{},...a.machineId||o.machineId?{machineId:a.machineId||o.machineId}:{},...a.machineStatus||o.machineStatus?{machineStatus:a.machineStatus||o.machineStatus}:{},health:l&&(!a.health||a.health==="unknown")?On(l):a.health,providers:c??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...p?{connection:p}:{},...l?{git:l}:{}},w=ft(a.branchConvergence);return Object.keys(w).length>0?Object.assign(b,{branchConvergence:w}):delete b.branchConvergence,l&&(delete b.gitProbePending,delete b.error),b}function k0(e){const t=ft(e),r=Pe(t.nodeId,t.id);if(!r)return null;const n=ft(t.cachedStatus),a=f0(t),o=a?void 0:vn(ft(t.git),t)??vn(t,t),l=a??o,c=l?void 0:vn(ft(n.git),t),d=l??c,m=Pe(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=Pe(t.health),p=a?On(d):g0(u,l)||(d?On(d):void 0)||Pe(n.health)||m||Pe(t.status)||"unknown",w=(a?void 0:Pe(t.error))??(l?void 0:Pe(n.error)),x=y0(t),h=Pa(t.activeSessions),g=(x==null?void 0:x.map(k=>k.sessionId))??[],y=Pa(t.providerPriority),f=$t(t.gitProbePending,t.git_probe_pending),A=l?void 0:f,C=v0(t),v=ft(t.branchConvergence??t.branch_convergence),N=C==null?void 0:C.state,T=a&&(!(C!=null&&C.reported)||N==="unknown")?w0(C):C;return{nodeId:r,machineLabel:Pe(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:Pe(t.workspace,d==null?void 0:d.workspace)||"",...Pe(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Pe(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Pe(t.daemonId,t.daemon_id)?{daemonId:Pe(t.daemonId,t.daemon_id)}:{},...Pe(t.machineId,t.machine_id)?{machineId:Pe(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...$t(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:$t(t.isLocalWorktree,t.is_local_worktree)}:{},...Pe(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Pe(t.worktreeBranch,t.worktree_branch)}:{},health:p,...d?{git:d}:{},...A!==void 0?{gitProbePending:A}:{},providers:Pa(t.providers),activeSessions:h.length>0?h:g,...x&&x.length>0?{activeSessionDetails:x}:{},...y.length>0?{providerPriority:y}:{},...$t(t.launchReady)!==void 0?{launchReady:$t(t.launchReady)}:a?{launchReady:!0}:{},...Pe(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:Pe(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...Pe(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:Pe(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...T?{connection:T}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...w?{error:w}:{}}}function xu(e){const t=new Map,r=[];for(const n of e){const a=t.get(n.nodeId);if(!a){t.set(n.nodeId,n),r.push(n);continue}const o=j0(a,n);t.set(n.nodeId,o);const l=r.findIndex(c=>c.nodeId===n.nodeId);l>=0&&(r[l]=o)}return r}function bu(e){return{...e,nodes:xu(e.nodes??[])}}function S0(e){var r;const t=e==null?void 0:e.git;return{nodeId:(e==null?void 0:e.nodeId)??null,chosenSource:t?"live_git":e!=null&&e.gitProbePending?"pending_git":"no_git",hasLiveGit:di(e??{git:void 0}),branch:(t==null?void 0:t.branch)??null,upstream:(t==null?void 0:t.upstream)??null,headCommit:(t==null?void 0:t.headCommit)??null,submoduleCount:((r=t==null?void 0:t.submodules)==null?void 0:r.length)??0,pendingGit:(e==null?void 0:e.gitProbePending)===!0,connection:e!=null&&e.connection?{state:e.connection.state,transport:e.connection.transport,source:e.connection.source}:null}}function N0(e){const t=Pe(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>k0(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=xu(n),o=Pe(e.meshName,e.mesh_name,e.name),l=Pe(e.repoIdentity,e.repo_identity),c=Pe(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!l||!c?null:{...e,meshId:t,meshName:o,repoIdentity:l,refreshedAt:c,nodes:a}}function C0(e){var o;let t=0;const r=ft(e.sourceOfTruth),n=ft(r.directPeerTruth);Pe(r.currentStatus)==="live_git_and_session_probes"&&(t+=100),r.coordinatorOwnsLiveTruth===!0&&(t+=25),n.satisfied===!0&&(t+=15);for(const l of e.nodes){const c=l.git;if(!c){l.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=ci(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((o=c.submodules)==null?void 0:o.length)??0)*2}return t}function Pl(e){let t=null;for(const r of e){const n=N0(ft(r));if(!n)continue;const a=C0(n);(!t||a>t.score)&&(t={status:n,score:a})}return(t==null?void 0:t.status)??null}function gu(e){const r=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,n=Pl([r==null?void 0:r.status,r]);return n||Pl([e==null?void 0:e.status,e])}const I0=5*60*1e3;function yu(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function vu(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function M0(e){var t,r,n;return((t=e.connection)==null?void 0:t.state)==="self"||e.isLocalWorktree===!0?"local":((r=e.connection)==null?void 0:r.transport)==="direct"||((n=e.connection)==null?void 0:n.transport)==="relay"||yu(e)||vu(e)?"remote":"unknown"}function A0(e){return di(e)}function wu(e){var t;return A0(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function T0(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function ju(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function ku(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function ui(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function _0(e){return ui(e)?"degraded":ku(e)?"dirty":"online"}function L0(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Dl(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 Da(e){return e.length===0?"unknown":e.reduce((t,r)=>Dl(r)>Dl(t)?r:t)}function R0(e){var o,l,c,d,m;const t=new Map,r=new Map;for(const u of e){const p=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();p&&(r.set(p,(r.get(p)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(p,(t.get(p)??0)+1))}const n=[...t.entries()].sort((u,p)=>{if(p[1]!==u[1])return p[1]-u[1];const b=["main","master","develop","dev"],w=b.indexOf(u[0]),x=b.indexOf(p[0]);return w!==-1||x!==-1?w===-1?1:x===-1?-1:w-x:u[0].localeCompare(p[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,p)=>p[1]-u[1])[0])==null?void 0:m[0])??null}function P0(e,t){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&&t&&n.branch!==t&&!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 El(e){switch(e){case"merged_to_main":return 0;case"pushed_feature_branch_needs_merge":return 1;case"cleanup_candidate":return 2;case"blocked_review":return 3;case"not_mergeable":default:return 4}}function D0(e){return e.reduce((t,r)=>El(r.status)>El(t.status)?r:t)}function E0(e){const t=e.branchConvergenceSummary;if(Array.isArray(t==null?void 0:t.followUps))return t.followUps;const r=e.followUps;return Array.isArray(r)?r:(t==null?void 0:t.needsFollowUp)===!1||(t==null?void 0:t.unresolvedCount)===0?[]:null}function $0(e){var a,o,l;const t=e.sourceOfTruth,r=[],n=(a=t==null?void 0:t.fallback)==null?void 0:a.warning;return typeof n=="string"&&n.trim()&&r.push(n.trim()),(t==null?void 0:t.currentStatus)==="bootstrap_inventory_fallback"&&((o=t.directPeerTruth)==null?void 0:o.required)===!0&&((l=t.directPeerTruth)==null?void 0:l.satisfied)!==!0&&!r.some(c=>c.includes("direct mesh truth"))&&r.push("Direct mesh truth is not confirmed yet; this graph is drawn from setup inventory only."),r}function B0(e,t){return e.type!=="submoduleNode"&&e.branch===t&&e.ahead===0&&e.behind===0&&!e.dirty&&!e.hasConflicts&&(!e.upstreamStatus||e.upstreamStatus==="fresh")&&e.snapshotCompleteness==="complete"}function O0(e,t){var r,n;return{status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch_aggregate",nextStep:null,branch:e,defaultBranch:e,upstream:((r=t.find(a=>a.upstream))==null?void 0:r.upstream)??null,upstreamStatus:((n=t.find(a=>a.upstreamStatus))==null?void 0:n.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function F0(e,t){if(wu(e))return null;const r=e.branchConvergence;if(!r||typeof r!="object")return null;const n=r.status;if(!n||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(n))return null;const a=e.git,o=ju(a)||ku(a),l=!!(a!=null&&a.hasConflicts)||ui(a),c=(a==null?void 0:a.ahead)??0,d=(a==null?void 0:a.behind)??0,m=(a==null?void 0:a.branch)??null,u=(a==null?void 0:a.upstream)??null,p=(a==null?void 0:a.upstreamStatus)??null,b=r.defaultBranch??t??null;return{status:n,needsConvergence:r.needsConvergence??n!=="merged_to_main",reason:r.reason??"provided_by_coordinator",nextStep:r.nextStep??null,branch:r.branch??m,defaultBranch:b,upstream:r.upstream??u,upstreamStatus:r.upstreamStatus??p,ahead:r.ahead??c,behind:r.behind??d,dirty:r.dirty??o,hasConflicts:r.hasConflicts??l}}function W0(e,t){const r=F0(e,t);return r?{...r,defaultBranch:r.defaultBranch??t}:null}function H0(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function K0(e){var d,m,u;const{nodeStatus:t,expectedSubmodulePaths:r,refreshedAtMs:n}=e,a=[],o=t.machineLabel||t.nodeId,l=t.git;if(!l){if(wu(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const p=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((m=t.connection)==null?void 0:m.state)==="self";return a.push(p?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}const c=new Set((l.submodules??[]).map(p=>p.path));if(r.size>0){const p=[...r].filter(b=>!c.has(b));p.length>0&&a.push(`${o} is missing submodule visibility for ${p.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&n!==null&&typeof l.lastCheckedAt=="number"&&n-l.lastCheckedAt>I0&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(p=>p.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(p=>p.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function U0(e){var L;const t=bu(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??R0(t.nodes),a=T0(t.refreshedAt),o=new Set(t.nodes.flatMap(S=>{var D;return(((D=S.git)==null?void 0:D.submodules)??[]).map($=>$.path)})),l=[],c=[],d=$0(t),m=new Map;for(const S of t.nodes){const D=S.git,$=(D==null?void 0:D.branch)??null,E=_0(D),I=ju(D)||E==="dirty",M=P0(S,n),F=W0(S,n),P=K0({nodeStatus:S,expectedSubmodulePaths:o,refreshedAtMs:a}),R={id:S.nodeId,type:M.length>0?"orphanNode":"worktreeNode",label:S.machineLabel||S.nodeId.slice(0,8),workspace:S.workspace,branch:$,upstream:(D==null?void 0:D.upstream)??null,upstreamStatus:(D==null?void 0:D.upstreamStatus)??null,daemonId:yu(S),machineId:vu(S),machineLabel:S.machineLabel||null,locality:M0(S),health:Da([S.health,E]),ahead:(D==null?void 0:D.ahead)??0,behind:(D==null?void 0:D.behind)??0,dirty:I,dirtyFiles:L0(D),hasConflicts:(D==null?void 0:D.hasConflicts)??!1,activeSessionCount:((L=S.activeSessions)==null?void 0:L.length)??0,activeSessions:S.activeSessions??[],providers:S.providers??[],isOrphan:M.length>0,orphanReasons:M,error:S.error,nextStepHint:P.snapshotWarnings[0]??M[0]??(F==null?void 0:F.nextStep)??void 0,parentNodeId:null,submodulePath:null,submoduleCommit:(D==null?void 0:D.headCommit)??null,outOfSync:ui(D),snapshotCompleteness:P.snapshotCompleteness,snapshotWarnings:P.snapshotWarnings,branchConvergence:F,source:S};if(l.push(R),$){const K=m.get($)??[];K.push(R.id),m.set($,K)}for(const K of(D==null?void 0:D.submodules)??[]){const V=`${R.id}::submodule::${K.path}`,te=K.path.split("/").filter(Boolean).pop()||K.path;l.push({id:V,type:"submoduleNode",label:te,workspace:K.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:R.daemonId,machineId:R.machineId,machineLabel:R.machineLabel,locality:R.locality,health:H0(K),ahead:0,behind:0,dirty:K.dirty,dirtyFiles:K.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:K.error,nextStepHint:K.error||(K.outOfSync?`${K.path} is out of sync with the parent checkout`:K.dirty?`${K.path} has local changes`:`${K.path} is in sync with the parent checkout`),parentNodeId:R.id,submodulePath:K.path,submoduleCommit:K.commit,outOfSync:K.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:R.id,parentWorkspace:S.workspace,submodule:K}}),c.push({id:`${R.id}--${V}`,source:R.id,target:V,type:"submoduleLink",label:K.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const u=n?`__branch_${n}`:null;if(u&&n){const D=(m.get(n)??[]).map(R=>l.find(K=>K.id===R)).filter(Boolean),$=D.map(R=>R.branchConvergence).filter(Boolean),E=E0(t),I=D.length>0&&D.every(R=>B0(R,n)),M=(E==null?void 0:E.length)===0&&I?O0(n,D):$.length>0?D0($):null,F=(E==null?void 0:E.length)===0&&I?0:$.filter(R=>R.needsConvergence).length,P={id:u,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",health:Da(D.map(R=>R.health)),ahead:0,behind:0,dirty:D.some(R=>R.dirty),dirtyFiles:D.reduce((R,K)=>R+K.dirtyFiles,0),hasConflicts:D.some(R=>R.hasConflicts),activeSessionCount:D.reduce((R,K)=>R+K.activeSessionCount,0),activeSessions:D.flatMap(R=>R.activeSessions),providers:[...new Set(D.flatMap(R=>R.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:F>0?`${F} workspace(s) on ${n} still need follow-up`:D.length>0?`${D.length} workspace(s) currently on ${n}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:M,source:{nodeId:u,machineLabel:n,workspace:t.repoIdentity,health:Da(D.map(R=>R.health)),providers:[],activeSessions:[]}};l.push(P);for(const R of l)if(!(R.id===u||R.type==="submoduleNode")){if(R.branch===n){c.push({id:`${u}--${R.id}`,source:u,target:R.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(R.branch){c.push({id:`${u}--${R.id}`,source:u,target:R.id,type:R.isOrphan?"orphanLink":"parentBranch",label:R.branch,direction:"undirected"});continue}R.isOrphan&&c.push({id:`${u}--${R.id}`,source:u,target:R.id,type:"orphanLink",label:"detached",direction:"undirected"})}}for(const[S,D]of m){if(D.length<2)continue;const $=D.map(E=>l.find(I=>I.id===E)).filter(Boolean);$.sort((E,I)=>E.label.localeCompare(I.label));for(let E=1;E<$.length;E+=1)c.push({id:`wt_${$[E-1].id}--${$[E].id}`,source:$[E-1].id,target:$[E].id,type:"worktreeLink",label:E===1?`${S} peers`:void 0,direction:"undirected"})}const p=l.filter(S=>S.type!=="defaultBranchNode"),b=p.filter(S=>S.isOrphan).length,w=p.filter(S=>S.hasConflicts).length,x=p.filter(S=>S.health==="offline").length,h=p.filter(S=>S.type==="submoduleNode"&&S.outOfSync).length,g=p.filter(S=>{var D;return S.type!=="submoduleNode"&&((D=S.branchConvergence)==null?void 0:D.needsConvergence)}).length,y=p.filter(S=>{var D;return((D=S.branchConvergence)==null?void 0:D.status)==="blocked_review"}).length,f=p.filter(S=>{var D;return((D=S.branchConvergence)==null?void 0:D.status)==="pushed_feature_branch_needs_merge"}).length,A=p.filter(S=>{var D;return((D=S.branchConvergence)==null?void 0:D.status)==="cleanup_candidate"}).length,C=p.filter(S=>{var D;return((D=S.branchConvergence)==null?void 0:D.status)==="not_mergeable"}).length,v=p.filter(S=>S.snapshotWarnings.length>0).length,N=p.filter(S=>S.snapshotCompleteness==="pending_git").length,T=p.filter(S=>S.snapshotCompleteness==="missing_git").length,k=p.filter(S=>S.snapshotCompleteness==="missing_submodule_report").length,j=p.filter(S=>S.snapshotCompleteness==="stale").length,B=[N>0?`${N} node(s) are still waiting for a live peer git snapshot`:null,T>0?`${T} node(s) have no visible peer git snapshot`:null,k>0?`${k} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,j>0?`${j} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return g>0&&d.push(`${g} workspace(s) still need follow-up before the mesh is converged`),b>0&&d.push(`${b} workspace(s) need attention before safe coordination`),y>0&&d.push(`${y} workspace(s) are blocked on branch convergence or upstream sync`),f>0&&d.push(`${f} clean feature branch workspace(s) still need merge follow-up`),A>0&&d.push(`${A} worktree workspace(s) are ready for refine / cleanup`),C>0&&d.push(`${C} workspace(s) have local changes or conflicts blocking convergence`),w>0&&d.push(`${w} workspace(s) report merge conflicts`),x>0&&d.push(`${x} node(s) are currently offline`),h>0&&d.push(`${h} submodule(s) are out of sync with their parent checkout`),d.push(...B),n||d.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:l,edges:c,stats:{totalNodes:p.length,onlineNodes:p.filter(S=>S.health==="online").length,dirtyNodes:p.filter(S=>S.dirty).length,orphanNodes:b,errorNodes:p.filter(S=>!!S.error||S.outOfSync).length,offlineNodes:x,followUpNodes:g,blockedReviewNodes:y,mergeReadyNodes:f,cleanupCandidateNodes:A,notMergeableNodes:C,incompleteSnapshotNodes:v,missingGitSnapshotNodes:T,missingSubmoduleSnapshotNodes:k,staleGitSnapshotNodes:j,totalActiveSessions:p.reduce((S,D)=>S+D.activeSessionCount,0)},warnings:d,snapshotWarnings:B}}const z0={recentFailures:0},mi=i.createContext(Zs("dark"));function nt({label:e,tone:t="default"}){const r=i.useContext(mi);return s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${r.badge(t)}`,children:e})}function Pt({label:e,value:t}){const r=i.useContext(mi);return s.jsxs("div",{className:r.rowClass,children:[s.jsx("span",{className:r.rowLabelClass,children:e}),s.jsx("span",{className:r.rowValueClass,children:t})]})}function G0(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 V0(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 q0(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 Y0(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 X0(e){var r;const t=[];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)t.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 t}function $l(e){return e?e.slice(0,7):null}function J0(e,t){var o,l,c;const r=$l((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=t[0];return a?[$l(a.commit),a.message].filter(Boolean).join(" · "):null}function Q0(e,t){const r=J0(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function Z0(e){const t=(e==null?void 0:e.result)??e,r=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(r==null?void 0:r.entries)?r.entries:[]}function ev(e){var r,n,a,o,l,c;const t=((r=e.selectedSessionEntry)==null?void 0:r.session.workspace)||((n=e.selectedSessionEntry)==null?void 0:n.workspace)||((o=(a=e.selectedNodeStatus)==null?void 0:a.git)==null?void 0:o.workspace)||((l=e.selectedNodeStatus)==null?void 0:l.workspace)||null;if(t&&e.selectedSessionEntry){const d=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}if(t&&e.selectedNodeStatus){const d=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}return null}function tv(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":Y0(e.connection)}function sv(e){var r;const t=e.source;return t!=null&&t.kind?t.kind:((r=t==null?void 0:t.connection)==null?void 0:r.source)??"mesh_status"}function rv(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function nv(e){var t,r,n,a;return[e.meshId,e.refreshedAt,e.nodes.length,((r=(t=e.queue)==null?void 0:t.summary)==null?void 0:r.active)??"",((a=(n=e.ledger)==null?void 0:n.summary)==null?void 0:a.recentFailures)??"",...e.nodes.map(o=>{var l,c,d,m,u,p,b,w,x,h,g,y,f,A,C,v,N,T,k,j,B;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((l=o.connection)==null?void 0:l.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((d=o.connection)==null?void 0:d.source)??"",o.health,o.gitProbePending?1:0,((m=o.git)==null?void 0:m.branch)??"",((u=o.git)==null?void 0:u.upstream)??"",((p=o.git)==null?void 0:p.upstreamStatus)??"",((b=o.git)==null?void 0:b.ahead)??"",((w=o.git)==null?void 0:w.behind)??"",((x=o.git)==null?void 0:x.headCommit)??"",((h=o.git)==null?void 0:h.staged)??"",((g=o.git)==null?void 0:g.modified)??"",((y=o.git)==null?void 0:y.untracked)??"",((f=o.git)==null?void 0:f.deleted)??"",((A=o.git)==null?void 0:A.renamed)??"",(C=o.git)!=null&&C.hasConflicts?1:0,((v=o.git)==null?void 0:v.lastCheckedAt)??"",((N=o.activeSessions)==null?void 0:N.join(","))??"",((T=o.activeSessionDetails)==null?void 0:T.length)??"",((k=o.providers)==null?void 0:k.join(","))??"",((j=o.providerPriority)==null?void 0:j.join(","))??"",o.error??"",(((B=o.git)==null?void 0:B.submodules)??[]).map(L=>[L.path,L.commit,L.dirty?1:0,L.outOfSync?1:0,L.error??""].join("/")).join(",")].join("|")})].join("::")}function Su({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var F,P,R,K,V;const{theme:a}=Qs(),o=i.useMemo(()=>Zs(a),[a]),l=i.useMemo(()=>bu(e),[e]),c=i.useMemo(()=>nv(l),[l]),d=i.useMemo(()=>U0(l),[c]),[m,u]=i.useState(null),[p,b]=i.useState(null),[w,x]=i.useState({}),h=i.useMemo(()=>new Map(l.nodes.map(te=>[te.nodeId,te])),[l.nodes]),g=i.useMemo(()=>new Map(d.nodes.map(te=>[te.id,te])),[d.nodes]),y=((F=l.queue)==null?void 0:F.summary)??null,f=((P=l.ledger)==null?void 0:P.summary)??z0,A=i.useMemo(()=>X0(l),[l]),C=i.useMemo(()=>{const te=new Map;for(const ie of A){const J=ie.session.state||ie.session.lifecycle||"unknown";te.set(J,(te.get(J)??0)+1)}return[...te.entries()].sort((ie,J)=>J[1]-ie[1])},[A]);i.useEffect(()=>{m&&(g.has(m)||(u(null),b(te=>!te||"nodeId"in te&&te.nodeId===m?null:te)))},[g,m]);const v=m?h.get(m)??null:null,N=rv(d,m);i.useEffect(()=>{var te,ie,J;if(m)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:l.meshId,selectedNodeId:m,canonicalNode:S0(v),graphNode:N?{id:N.id,branch:N.branch,upstream:N.upstream,headCommit:N.submoduleCommit,submoduleCount:((ie=(te=v==null?void 0:v.git)==null?void 0:te.submodules)==null?void 0:ie.length)??0,snapshotCompleteness:N.snapshotCompleteness,snapshotWarnings:N.snapshotWarnings,branchConvergence:((J=N.branchConvergence)==null?void 0:J.status)??null}:null})}catch{}},[l.meshId,N,m,v]);const T=(p==null?void 0:p.kind)==="session"?A.find(te=>te.nodeId===p.nodeId&&te.session.sessionId===p.sessionId)??null:null,k=i.useMemo(()=>A.filter(te=>te.nodeId===m),[m,A]),j=ev({coordinatorDaemonId:r,selectedNodeStatus:v,selectedSessionEntry:T}),B=(j==null?void 0:j.workspace)??null,L=B?w[B]??null:null,S=Q0(v,(L==null?void 0:L.entries)??[]),D=i.useCallback(()=>{u(null),b(null)},[]);i.useEffect(()=>{if(!N)return;const te=ie=>{ie.key==="Escape"&&D()};return window.addEventListener("keydown",te),()=>window.removeEventListener("keydown",te)},[D,N]),i.useEffect(()=>{if(!j||!n)return;const{daemonId:te,workspace:ie}=j,J=w[ie];if(J!=null&&J.loading||J&&(J.entries.length>0||J.error))return;let me=!1;return x(je=>{var ke;return{...je,[ie]:{loading:!0,error:null,entries:((ke=je[ie])==null?void 0:ke.entries)??[]}}}),n(te,"git_log",{workspace:ie,limit:5}).then(je=>{me||x(ke=>({...ke,[ie]:{loading:!1,error:null,entries:Z0(je)}}))}).catch(je=>{me||x(ke=>({...ke,[ie]:{loading:!1,error:je instanceof Error?je.message:"git_log failed",entries:[]}}))}),()=>{me=!0}},[w,j,n]);const $=[...d.warnings??[],...l.nodes.filter(te=>te.machineStatus&&te.machineStatus!=="online").map(te=>`${te.machineLabel}: ${te.machineStatus}`)],E=d.stats.incompleteSnapshotNodes>0,I=d.stats.followUpNodes>0?`${d.stats.followUpNodes} need follow-up`:E?"mesh visibility incomplete":"mesh converged",M=d.stats.followUpNodes>0?"danger":E?"warn":"good";return s.jsx(mi.Provider,{value:o,children:s.jsx("div",{className:"flex min-h-0 flex-col gap-4",children:s.jsx("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:s.jsxs("div",{className:`${o.cardClass} relative min-h-0 flex-1 rounded-[28px] p-3 sm:p-4`,style:{minHeight:420},children:[s.jsxs("div",{className:`absolute inset-x-4 top-4 z-30 flex max-h-[42dvh] flex-wrap items-start justify-between gap-3 overflow-y-auto rounded-2xl px-3.5 py-3 backdrop-blur-xl sm:static sm:mb-3 sm:max-h-none sm:overflow-visible sm:backdrop-blur-none ${o.isDark?"border border-white/10 bg-slate-950/85 sm:bg-slate-950/45":"border border-slate-200 bg-white/95 shadow-lg shadow-slate-900/10 sm:bg-white/95 sm:shadow-sm"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-wrap gap-2 text-xs ${o.textSecondary}`,children:[s.jsx(nt,{label:I,tone:M}),d.stats.blockedReviewNodes>0&&s.jsx(nt,{label:`${d.stats.blockedReviewNodes} blocked review`,tone:"danger"}),d.stats.notMergeableNodes>0&&s.jsx(nt,{label:`${d.stats.notMergeableNodes} not mergeable`,tone:"danger"}),d.stats.mergeReadyNodes>0&&s.jsx(nt,{label:`${d.stats.mergeReadyNodes} need merge`,tone:"warn"}),d.stats.cleanupCandidateNodes>0&&s.jsx(nt,{label:`${d.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),d.stats.offlineNodes>0&&s.jsx(nt,{label:`${d.stats.offlineNodes} offline`,tone:"danger"}),d.stats.incompleteSnapshotNodes>0&&s.jsx(nt,{label:`${d.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),d.stats.missingGitSnapshotNodes>0&&s.jsx(nt,{label:`${d.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),d.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(nt,{label:`${d.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),d.stats.staleGitSnapshotNodes>0&&s.jsx(nt,{label:`${d.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((y==null?void 0:y.active)??0)>0&&s.jsx(nt,{label:`${(y==null?void 0:y.active)??0} active queue`,tone:"info"}),s.jsx(nt,{label:`${d.stats.totalNodes} nodes`,tone:"default"}),d.stats.totalActiveSessions>0&&s.jsx(nt,{label:`${d.stats.totalActiveSessions} active sessions`,tone:"info"})]}),s.jsxs("details",{className:`max-w-full rounded-xl px-3 py-2 text-xs ${o.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${o.textSecondary} [&::-webkit-details-marker]:hidden`,children:"Legend & secondary details"}),s.jsxs("div",{className:"mt-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(nt,{label:`${d.stats.dirtyNodes} dirty`,tone:d.stats.dirtyNodes>0?"warn":"good"}),s.jsx(nt,{label:`${d.stats.orphanNodes} orphan`,tone:d.stats.orphanNodes>0?"warn":"good"}),s.jsx(nt,{label:`${f.recentFailures} recent failures`,tone:f.recentFailures>0?"danger":"good"}),C.length===0?s.jsx(nt,{label:"no session metadata"}):C.slice(0,2).map(([te,ie])=>s.jsx(nt,{label:`${ie} ${te}`,tone:V0(te)},te))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(nt,{label:"Anchor = default branch",tone:"info"}),s.jsx(nt,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(nt,{label:"Submodule link = child checkout",tone:"warn"})]}),$.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:$.map(te=>s.jsx("span",{className:o.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:te},te))}),s.jsx("div",{className:`text-xs ${o.textMuted}`,children:"Click a node only when you want drill-down details. The graph itself now carries the convergence state."})]})]})]}),d.nodes.length>0?s.jsx(d0,{data:d,selectedNodeId:m,onNodeClick:te=>{if((p==null?void 0:p.kind)==="node"&&m===te.id){u(null),b(null);return}u(te.id),b({kind:"node",nodeId:te.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:t}),N&&(p==null?void 0:p.kind)==="node"&&s.jsx("div",{className:"absolute inset-x-3 bottom-3 top-20 z-20 flex items-end justify-center p-2 sm:inset-5 sm:top-24 sm:items-start sm:justify-end",onClick:D,role:"presentation",children:s.jsxs("section",{role:"dialog","aria-modal":"false","aria-label":"Selected node",className:o.isDark?"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-white/12 bg-slate-950/96 p-4 shadow-2xl shadow-black/40 backdrop-blur-xl":"max-h-[min(72vh,540px)] w-full max-w-[min(28rem,calc(100vw-2.5rem))] overflow-y-auto rounded-2xl border border-slate-200 bg-white/96 p-4 shadow-2xl shadow-slate-900/15 backdrop-blur-xl",onClick:te=>te.stopPropagation(),children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${o.textPrimary}`,children:N.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:N.id.slice(0,16)})]}),s.jsx("button",{type:"button",onClick:D,className:o.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2.5 py-1 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2.5 py-1 text-xs text-slate-600 transition hover:bg-slate-50",children:"Close"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-2",children:[s.jsx(nt,{label:(v==null?void 0:v.health)??N.health,tone:G0((v==null?void 0:v.health)??N.health)}),N.branch&&s.jsx(nt,{label:N.branch,tone:"default"}),N.ahead>0&&s.jsx(nt,{label:`ahead ${N.ahead}`,tone:"warn"}),N.behind>0&&s.jsx(nt,{label:`behind ${N.behind}`,tone:"warn"}),N.dirtyFiles>0&&s.jsx(nt,{label:`${N.dirtyFiles} dirty`,tone:"warn"}),(v==null?void 0:v.connection)&&s.jsx(nt,{label:tv(v),tone:q0(v.connection)}),k.length>0&&s.jsx(nt,{label:`${k.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(Pt,{label:"Machine",value:N.machineLabel??"not reported"}),s.jsx(Pt,{label:"Locality",value:N.locality}),s.jsx(Pt,{label:"Machine id",value:N.machineId??(v==null?void 0:v.machineId)??"not reported"}),s.jsx(Pt,{label:"Daemon id",value:N.daemonId??(v==null?void 0:v.daemonId)??"not reported"}),s.jsx(Pt,{label:"Workspace",value:(v==null?void 0:v.workspace)??N.workspace}),s.jsx(Pt,{label:"Branch",value:N.branch??"unknown"}),s.jsx(Pt,{label:"HEAD",value:S??(v!=null&&v.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(Pt,{label:"Upstream",value:N.upstream??"none"}),s.jsx(Pt,{label:"Dirty/ahead/behind",value:`${N.dirtyFiles} dirty · ↑${N.ahead}/↓${N.behind}`}),s.jsx(Pt,{label:"Source",value:String(((R=v==null?void 0:v.connection)==null?void 0:R.source)??sv(N))}),s.jsx(Pt,{label:"Transport",value:((K=v==null?void 0:v.connection)==null?void 0:K.transport)??"unknown"}),s.jsx(Pt,{label:"Sessions",value:k.length>0?k.map(te=>te.session.state||te.session.lifecycle||"unknown").join(", "):"none active"})]}),N.snapshotWarnings.length>0&&s.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:"Key warning"}),s.jsx("div",{className:"mt-1",children:N.snapshotWarnings[0]})]}),((V=N.branchConvergence)==null?void 0:V.nextStep)&&s.jsxs("div",{className:o.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsx("div",{className:"font-medium",children:"Follow-up"}),s.jsx("div",{className:"mt-1",children:N.branchConvergence.nextStep})]})]})})]})})})})}function av({activeConv:e,sendDaemonCommand:t,onClose:r}){var v;const n=typeof((v=e.settings)==null?void 0:v.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,o=$d(),{theme:l}=Qs(),c=i.useMemo(()=>Zs(l),[l]),[d,m]=i.useState(null),[u,p]=i.useState(!1),[b,w]=i.useState(null),[x,h]=i.useState(null),g=i.useRef(!1);i.useEffect(()=>{g.current=d!==null},[d]);const y=i.useCallback(async(N=!1)=>{if(!a||!n){w("This coordinator does not expose a live mesh id."),m(null);return}p(!g.current),w(null);try{const T=o!=null&&o.loadMeshStatus?await o.loadMeshStatus(a,n,{refresh:N,retryProfile:N?"settled":"interactive"}):await t(a,"mesh_status",{meshId:n,refresh:N}),k=gu(T);if(!k){w("mesh_status returned an unexpected payload.");return}m(k),g.current=!0,h(k.refreshedAt||new Date().toISOString()),!N&&(o!=null&&o.loadMeshStatus)&&y(!0)}catch(T){w(T instanceof Error?T.message:"Failed to load live mesh status")}finally{p(!1)}},[a,n,o,t]);i.useEffect(()=>{y(!1)},[y]),i.useEffect(()=>{const N=T=>{T.key==="Escape"&&r()};return window.addEventListener("keydown",N),()=>window.removeEventListener("keydown",N)},[r]);const f=(d==null?void 0:d.meshName)||n||"Repo Mesh",A=x?new Date(x).toLocaleTimeString():null,C=i.useMemo(()=>u?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[u]);return s.jsx("div",{className:c.dialogOverlayClass,onClick:r,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:c.dialogShellClass,onClick:N=>N.stopPropagation(),children:[s.jsxs("div",{className:c.dialogHeaderClass,children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.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:s.jsx(ns,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:c.dialogTitleClass,children:f}),s.jsx("span",{className:c.dialogKickerClass,children:"Mesh observability"})]}),s.jsxs("p",{className:c.dialogSubtitleClass,children:[ut(e),e.workspaceName?` · ${e.workspaceName}`:"",d!=null&&d.repoIdentity?` · ${d.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[A&&s.jsxs("span",{className:c.dialogRefreshedChipClass,children:["Refreshed ",A]}),s.jsx("button",{type:"button",onClick:()=>{y(!0)},disabled:u,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:u?"Refreshing…":"Refresh"}),s.jsx("button",{type:"button",onClick:r,className:c.dialogCloseButtonClass,"aria-label":"Close mesh graph",children:s.jsx(jt,{size:16})})]})]}),b&&s.jsx("div",{className:c.isDark?"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5":"shrink-0 border-b border-rose-300 bg-rose-50 px-4 py-2 text-sm text-rose-700 md:px-5",children:b}),s.jsx("div",{className:c.dialogBodyClass,children:d?s.jsx(Su,{status:d,emptyMessage:C,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:c.dialogEmptyClass,children:C})})]})})}function ov(e,t){const{sendCommand:r}=kt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);i.useEffect(()=>{if(!e||!t){a(null);return}l(!0),r(e,"git_remote_url",{workspace:t}).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,t,r]);const c=iv(n);return{remoteUrl:n,githubUrl:c,loading:o}}function iv(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const Nu=5e3;function lv(e){return`git:${e}`}function cv({workspace:e,includeDiffSummary:t=!1,intervalMs:r=Nu}){return{type:"subscribe",topic:"workspace.git",key:lv(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function pi(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ms(e,t){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 t}function dv(e){const t=pi(e);return(t==null?void 0:t.success)===!1?{status:null,error:Ms(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Ms(t,"Git status response did not include status")}}function uv(e){const t=pi(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Ms(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Ms(t,"Git diff summary response did not include diffSummary")}}function Ea(e){return e===void 0||typeof e=="boolean"}function mv(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Ea(t.binary)&&Ea(t.truncated)&&Ea(t.staged)}function pv(e){const t=pi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Ms(t,"Git file diff request failed")}:mv(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Ms(t,"Git file diff response did not include a valid diff object")}}function hv({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=Nu}){const{sendCommand:o,sendData:l}=kt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[p,b]=i.useState(null),[w,x]=i.useState(!1),[h,g]=i.useState(null),y=i.useCallback(async()=>{if(!(!d||!e||!c)){x(!0),g(null);try{const A=dv(await o(e,"git_status",{workspace:c}));if(A.error){u(null),b(null),g(A.error);return}if(u(A.status),!n){b(null);return}const C=uv(await o(e,"git_diff_summary",{workspace:c}));if(C.error){b(null),g(C.error);return}b(C.diffSummary)}catch(A){g(Ms(A,"Git status request failed"))}finally{x(!1)}}},[d,e,n,o,c]),f=i.useMemo(()=>c?cv({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!f){u(null),b(null),x(!1),g(null);return}const A=l?Qt.subscribe({sendData:l},e,f,C=>{var v,N;C.workspace===c&&(u(C.status),b(C.diffSummary??null),g(((v=C.status)==null?void 0:v.error)||((N=C.diffSummary)==null?void 0:N.error)||null),x(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{A==null||A()}},[d,e,y,f,l,c]),{status:m,diffSummary:p,loading:w,error:h,refresh:y}}const fv={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},xv={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 Bl(e){return e.split("/").pop()??e}function bv(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function gv({files:e,truncated:t,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${a}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(o=>{const l=n===o.path,c=fv[o.status]??"?",d=xv[o.status]??"text-zinc-400",m=bv(o.path),u=Bl(o.path),p=o.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return s.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:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&s.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),s.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Bl(o.oldPath)]}),p]}),!o.binary&&(o.insertions>0||o.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&s.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&s.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function yv(e,t){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"),s.jsx("div",{className:`px-3 ${r}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function vv({diff:e,binary:t,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 s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
|
|
66
|
+
`);return s.jsxs("div",{ref:l,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,m)=>yv(d,m))}),r&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function wv(e,t){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const n={};for(const a of t.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(`
|
|
67
|
+
`)}function Cu({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=kt(),{status:a,diffSummary:o,loading:l,error:c,refresh:d}=hv({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=i.useState(null),[p,b]=i.useState(null),[w,x]=i.useState(""),[h,g]=i.useState(!1),[y,f]=i.useState(!1),[A,C]=i.useState(null),[v,N]=i.useState(null),{githubUrl:T}=ov(e,t),k=i.useCallback(async $=>{if(!((m==null?void 0:m.path)===$.path&&!m.loading)){u({path:$.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const E=await n(e,"git_diff_file",{workspace:t,path:$.path,staged:$.staged}),I=pv(E);if(I.error||!I.diff){u({path:$.path,diff:"",binary:!1,truncated:!1,loading:!1,error:I.error??"Failed to load diff"});return}u({path:$.path,diff:I.diff.diff,binary:I.diff.binary??!1,truncated:I.diff.truncated??!1,loading:!1,error:null})}catch(E){const I=E instanceof Error?E.message:"Failed to load diff";u({path:$.path,diff:"",binary:!1,truncated:!1,loading:!1,error:I})}}},[e,n,m,t]),j=i.useCallback($=>{x(""),g(!1),C(null),N(null),b($)},[]),B=i.useCallback(()=>{b(null),C(null),f(!1)},[]),L=i.useCallback(async()=>{var $,E,I;if(p){f(!0),C(null);try{let M;p==="checkpoint"?M=await n(e,"git_checkpoint",{workspace:t,message:w,includeUntracked:h}):p==="stash"?M=await n(e,"git_stash_push",{workspace:t,message:w,includeUntracked:h}):p==="stash_pop"?M=await n(e,"git_stash_pop",{workspace:t}):p==="checkout_files"&&m&&(M=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const F=(M==null?void 0:M.result)??M;if((F==null?void 0:F.success)===!1||F!=null&&F.error){C((F==null?void 0:F.error)??"Action failed"),f(!1);return}p==="checkpoint"?N(`Checkpoint created: ${((E=($=F==null?void 0:F.checkpoint)==null?void 0:$.commit)==null?void 0:E.slice(0,7))??"done"}`):p==="stash"?N(`Stashed as ${((I=F==null?void 0:F.stash)==null?void 0:I.stashRef)??"stash@{0}"}`):p==="stash_pop"?N("Stash restored"):(N("File reverted"),u(null)),b(null),await d()}catch(M){C(M instanceof Error?M.message:"Action failed")}finally{f(!1)}}},[p,n,e,t,w,h,m,d]),S=!!(a!=null&&a.hasConflicts),D=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:$=>{$.target===$.currentTarget&&r()},children:s.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:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),T&&s.jsx("a",{href:`${T}/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 ↗"})]}),s.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:"↺"}),s.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(jt,{className:"h-4 w-4"})})]}),a&&s.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&&s.jsxs("span",{title:a.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&s.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&s.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&s.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&s.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&s.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&s.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),D===0&&!a.error&&s.jsx("span",{className:"text-emerald-500",children:"clean"}),o&&o.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[o.files.length," file",o.files.length!==1?"s":"",o.totalInsertions>0&&s.jsxs("span",{className:"text-emerald-500",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&s.jsxs("span",{className:"text-red-400",children:[" -",o.totalDeletions]})]})]}),c&&s.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}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[l&&!o&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&s.jsx(gv,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:k}),!l&&!o&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?s.jsx(vv,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),v&&s.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:[s.jsx("span",{children:v}),s.jsx("button",{onClick:()=>N(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>j("checkpoint"),disabled:S,title:S?"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"}),s.jsx("button",{onClick:()=>j("stash"),disabled:S,title:S?"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"}),s.jsx("button",{onClick:()=>j("stash_pop"),disabled:S||!(a!=null&&a.stashCount),title:S?"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"}),s.jsx("button",{onClick:()=>j("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&&s.jsx("button",{onClick:()=>{const $=wv((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText($),N("Copied to clipboard"),setTimeout(()=>N(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),p&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[p==="checkpoint"&&"Create checkpoint commit",p==="stash"&&"Stash changes",p==="stash_pop"&&"Restore latest stash?",p==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(p==="checkpoint"||p==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:w,onChange:$=>x($.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}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:h,onChange:$=>g($.target.checked)}),"Include untracked files"]})]}),A&&s.jsx("p",{className:"text-xs text-red-400",children:A}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.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"}),s.jsx("button",{onClick:L,disabled:y||(p==="checkpoint"||p==="stash")&&!w.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 jv({isMobile:e,showMobileChatMode:t,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[m,u]=i.useState(!1),[p,b]=i.useState(!1),[w,x]=i.useState("quickstart"),[h,g]=i.useState("workspace"),y=i.useMemo(()=>!t&&!e,[t,e]),f=i.useCallback(k=>{a(k),k&&l(!1)},[]),A=i.useCallback(k=>{l(k),k&&a(!1)},[]),C=i.useCallback(()=>{x(r===0?"quickstart":"shortcuts"),g("workspace"),d(!0),a(!1),l(!1)},[r]),v=i.useCallback(()=>{d(!1)},[]),N=i.useCallback(()=>{u(!0)},[]),T=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!y){b(!1);return}b(!0);const k=window.setTimeout(()=>{b(!1)},1e4);return()=>window.clearTimeout(k)},[y]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:p,guideTab:w,shortcutSection:h,isDesktopDashboard:y,setGuideTab:x,setShortcutSection:g,handleInboxOpenChange:f,handleHiddenOpenChange:A,handleOpenShortcutHelp:C,closeShortcutHelp:v,openNewSession:N,closeNewSession:T}}function kv(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 Sv(e){return e instanceof Error?e.message:String(e||"")}function Nv(e){const t=Sv(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Cv({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:l,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:p,ides:b,actionLogs:w,sendDaemonCommand:x,setActionLogs:h,setCliViewModeOverrides:g,isStandalone:y,initialDataLoaded:f,userName:A,requestedMobileTabKey:C,onRequestedMobileTabConsumed:v,requestedMachineId:N,onRequestedMachineConsumed:T,requestedMobileSection:k,onRequestedMobileSectionConsumed:j,containerRef:B,isSplitMode:L,numGroups:S,groupSizes:D,groupedConvs:$,clearedTabs:E,focusedGroup:I,focusGroup:M,moveTabToGroup:F,splitTabRelative:P,closeGroup:R,handleResizeStart:K,groupActiveTabIds:V,setGroupActiveTab:te,groupTabOrders:ie,setGroupTabOrder:J,toggleHiddenTab:me,visibleConversations:je,requestedDesktopTabKey:ke,onRequestedDesktopTabConsumed:q,onDesktopActiveTabChange:ge,onRequestScrollToBottom:fe,onHideConversation:we,onShowHiddenConversation:xe,onShowAllHiddenConversations:Ne,scrollToBottomRequest:Q,machineEntries:he,layoutProfile:oe,onBrowseMachineDirectory:ue,onSaveMachineWorkspace:le,onLaunchMachineIde:de,onLaunchMachineProvider:Z,onListMachineMeshes:ve,onLaunchMeshCoordinator:ce,onListMachineSavedSessions:pe,notifications:ae,notificationUnreadCount:Ie,liveSessionInboxState:Ce,onMarkNotificationRead:_e,onMarkNotificationUnread:H,onDeleteNotification:Me}){const Ae=St.useRef(null),{inboxOpen:He,hiddenOpen:Ge,shortcutHelpOpen:Xe,newSessionOpen:Ye,guideNudgeVisible:tt,guideTab:ct,shortcutSection:mt,isDesktopDashboard:pt,setGuideTab:O,setShortcutSection:be,handleInboxOpenChange:Te,handleHiddenOpenChange:Be,handleOpenShortcutHelp:qe,closeShortcutHelp:z,openNewSession:U,closeNewSession:X}=jv({isMobile:t,showMobileChatMode:e,visibleConversationCount:je.length}),[re,W]=St.useState(null),[G,se]=St.useState(null),ne=St.useCallback((_,Y)=>{W({daemonId:_,workspace:Y})},[]),Se=St.useCallback(_=>{se(_)},[]),Ee=St.useCallback(_=>{var Y;Nr.flushSync(()=>{xe(_)}),(Y=Ae.current)==null||Y.restoreHiddenTabToSavedLocation(_.tabKey)},[xe]),Oe=St.useCallback(_=>{var ye;const Y=u.find(We=>ao(We,_))||p.find(We=>ao(We,_));Y&&(p.some(We=>We.tabKey===Y.tabKey)&&Ee(Y),ge(Y.tabKey),(ye=Ae.current)==null||ye.activateConversationTab(Y.tabKey),fe(Y.tabKey,"notification-open")),_e(_.id),Te(!1)},[Ee,p,u,ge,_e,fe]),Re=St.useCallback(()=>{var Y;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Y=Ae.current)==null||Y.resetAllPanelsToMain(),Be(!1))},[Be]),Fe=St.useCallback(async _=>{var Ke;if(!r)return;const Y=(Ke=r.modalButtons)==null?void 0:Ke[_];if(!Y)return;const ye=Us(r);if(!ye)return;const We=Y.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),De=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(We);try{await x(ye,"resolve_action",{button:Y,action:De?"approve":"reject",buttonIndex:_,...fs(r)})}catch(rt){Nv(rt)||console.error("[Shortcut approval] Failed:",rt)}},[r,x]),{isMac:Ue,actionDefinitions:Le,actionShortcuts:Ze,shortcutListening:et,shortcutListeningDraft:gt,setShortcutListening:yt,setShortcutListeningDraft:dt,saveShortcuts:xt}=vy({enabled:pt&&!Xe,onTrigger:_=>{var Y,ye,We,De,Ke,rt,At,bt,ts,Er,$r,Br,Or,Fr,Wr,Hr;if(_==="openShortcutHelp"){qe();return}if(_==="openNewSession"){U();return}if(_==="hideCurrentTab"){r&&we(r);return}if(_==="toggleHiddenTabs"){Be(!Ge);return}if(_==="openHistoryForActiveTab"){r&&!st(r)&&o(r);return}if(_==="openRemoteForActiveTab"){r&&!at(r)&&!st(r)&&l(r);return}if(_==="splitActiveTabRight"){(Y=Ae.current)==null||Y.splitActiveTabRight();return}if(_==="splitActiveTabDown"){(ye=Ae.current)==null||ye.splitActiveTabDown();return}if(_==="floatActiveTab"){(We=Ae.current)==null||We.floatActiveTab();return}if(_==="popoutActiveTab"){(De=Ae.current)==null||De.popoutActiveTab();return}if(_==="dockActiveTab"){(Ke=Ae.current)==null||Ke.dockActiveTab();return}if(_==="focusLeftPane"){(rt=Ae.current)==null||rt.focusLeftPane();return}if(_==="focusRightPane"){(At=Ae.current)==null||At.focusRightPane();return}if(_==="focusUpPane"){(bt=Ae.current)==null||bt.focusUpPane();return}if(_==="focusDownPane"){(ts=Ae.current)==null||ts.focusDownPane();return}if(_==="moveActiveTabToLeftPane"){(Er=Ae.current)==null||Er.moveActiveTabToLeftPane();return}if(_==="moveActiveTabToRightPane"){($r=Ae.current)==null||$r.moveActiveTabToRightPane();return}if(_==="moveActiveTabToUpPane"){(Br=Ae.current)==null||Br.moveActiveTabToUpPane();return}if(_==="moveActiveTabToDownPane"){(Or=Ae.current)==null||Or.moveActiveTabToDownPane();return}if(_==="triggerPrimaryApprovalAction"){Fe(0);return}if(_==="triggerSecondaryApprovalAction"){Fe(1);return}if(_==="triggerTertiaryApprovalAction"){Fe(2);return}if(_==="setActiveTabShortcut"){(Fr=Ae.current)==null||Fr.setShortcutForActiveTab();return}if(_==="selectPreviousGroupTab"){(Wr=Ae.current)==null||Wr.activatePreviousTabInGroup();return}if(_==="selectNextGroupTab"){(Hr=Ae.current)==null||Hr.activateNextTabInGroup();return}!r||!at(r)||st(r)||_==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Ve=St.useCallback(()=>{z(),yt(null),dt([])},[z,yt,dt]),Kt=St.useMemo(()=>mt==="all"?Le:Le.filter(_=>kv(_)===mt),[Le,mt]),ee=St.useCallback(()=>{const _=Object.fromEntries(Le.map(Y=>[Y.id,""]));xt(_)},[Le,xt]),$e=St.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const _=Object.fromEntries(Le.map(Y=>[Y.id,Y.defaultShortcut]));xt(_)},[Le,xt]);return St.useEffect(()=>{const _=Y=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Y.metaKey&&Y.key.toLowerCase()==="w":Y.ctrlKey&&Y.key.toLowerCase()==="w")&&(Y.preventDefault(),r&&we&&we(r))};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[r,we]),St.useEffect(()=>{if(!Xe||et)return;const _=Y=>{Y.key==="Escape"&&(Y.preventDefault(),Ve())};return window.addEventListener("keydown",_,!0),()=>window.removeEventListener("keydown",_,!0)},[Ve,Xe,et]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(gx,{activeConv:r,wsStatus:n,isConnected:a,conversations:je,hiddenConversations:p,onOpenHistory:o,onHideConversation:we,onShowConversation:Ee,onShowAllHidden:Ne,onResetPanelsToMain:Re,notifications:ae,notificationUnreadCount:Ie,onOpenNotification:Oe,onMarkNotificationRead:_e,onMarkNotificationUnread:H,onDeleteNotification:Me,inboxOpen:He,onInboxOpenChange:Te,hiddenOpen:Ge,onHiddenOpenChange:Be,onOpenNewSession:t?void 0:U,onOpenDashboardGuide:qe,guideNudgeVisible:tt,actionShortcuts:Ze,onOpenRemote:()=>{!r||at(r)||st(r)||l(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:ne,onOpenMeshGraph:Se}),e?s.jsx(ly,{conversations:u,hiddenConversations:p,ides:b,actionLogs:w,sendDaemonCommand:x,setActionLogs:h,setCliViewModeOverrides:g,isStandalone:y,userName:A,requestedActiveTabKey:C,onRequestedActiveTabConsumed:v,requestedMachineId:N,onRequestedMachineConsumed:T,requestedMobileSection:k,onRequestedMobileSectionConsumed:j,onOpenHistory:o,onOpenRemote:l,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Ne,onHideConversation:we,onOpenMeshGraph:Se,onOpenNewSession:U,liveSessionInboxState:Ce}):t?s.jsx(xy,{containerRef:B,isSplitMode:L,numGroups:S,groupSizes:D,groupedConvs:$,clearedTabs:E,ides:b,actionLogs:w,sendDaemonCommand:x,setActionLogs:h,isStandalone:y,hasRegisteredMachines:he.length>0,userName:A,focusedGroup:I,focusGroup:M,moveTabToGroup:F,splitTabRelative:P,closeGroup:R,handleResizeStart:K,groupActiveTabIds:V,setGroupActiveTab:te,groupTabOrders:ie,setGroupTabOrder:J,toggleHiddenTab:me,onOpenNewSession:U,allowTabShortcuts:!1,liveSessionInboxState:Ce}):s.jsx(Py,{visibleConversations:je,clearedTabs:E,ides:b,actionLogs:w,sendDaemonCommand:x,setActionLogs:h,isStandalone:y,hasRegisteredMachines:he.length>0,initialDataLoaded:f,userName:A,toggleHiddenTab:me,actionShortcuts:Ze,registerActionHandlers:_=>{Ae.current=_},onActiveTabChange:ge,requestedActiveTabKey:ke,onRequestedActiveTabConsumed:q,onRequestScrollToBottom:fe,scrollToBottomRequest:Q,onOpenNewSession:U,liveSessionInboxState:Ce,layoutProfile:oe}),Ye&&s.jsx(Oy,{machines:he,ides:b,onClose:X,onBrowseDirectory:ue,onSaveWorkspace:le,onLaunchIde:de,onLaunchProvider:Z,onListMeshes:ve,onLaunchMeshCoordinator:ce,onListSavedSessions:pe}),G&&s.jsx(av,{activeConv:G,sendDaemonCommand:x,onClose:()=>se(null)}),re&&s.jsx(Cu,{daemonId:re.daemonId,workspace:re.workspace,onClose:()=>W(null)}),Xe&&s.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:Ve,children:s.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:_=>_.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.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."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Ve,"aria-label":"Close dashboard guide",children:s.jsx(jt,{size:14})})]}),s.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(_=>s.jsx("button",{type:"button",className:`btn btn-sm ${ct===_.id?"btn-primary":"btn-secondary"}`,onClick:()=>O(_.id),children:_.label},_.id))}),ct==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Ue?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),ct==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.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."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.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."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),ct==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.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(_=>s.jsx("button",{type:"button",className:`btn btn-sm ${mt===_.id?"btn-primary":"btn-secondary"}`,onClick:()=>be(_.id),children:_.label},_.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ee,children:"Disable all"}),s.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:$e,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Kt.map(_=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${et===_.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:_.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:_.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:_.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.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:et===_.id?gt.length>0?`${gt.join(" ")} ...`:"Listening...":Ze[_.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{yt(_.id),dt([])},children:et===_.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Y={...Ze};Y[_.id]="",xt(Y)},children:"Disable"})]})]})},_.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Ue?"⌘⇧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 $a=[{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 Iv({onClose:e}){const[t,r]=i.useState(0),n=$a[t],a=t===$a.length-1;return s.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:[s.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:[s.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:s.jsx(jt,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:$a.map((o,l)=>s.jsx("div",{style:{width:l===t?24:8,height:8,borderRadius:4,background:l===t?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},l))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:n.icon})," ",n.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&s.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:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&s.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 →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>a?e():r(o=>o+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
|
|
68
|
+
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
69
|
+
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
70
|
+
`})]})}function Mv({hasExtensions:e,ideName:t,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.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:t}),n.map(o=>{const l=r===o.tabKey,c=o.status==="waiting_approval",d=o.status==="generating";return s.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:[s.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&&s.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 Av({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,l]=i.useState(()=>a||"native"),c=i.useMemo(()=>id(t),[t]),d=i.useMemo(()=>e?Yo(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=i.useMemo(()=>d.find(h=>h.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(h=>h.streamSource==="agent-stream"),[d]),p=i.useMemo(()=>e?Ht(d,e.id):null,[d,e]);i.useEffect(()=>{a&&l(a)},[a]),i.useEffect(()=>{if(a||!p)return;const h=p.streamSource==="native"?"native":p.tabKey;!h||o===h||o==="native"&&l(h)},[o,p,a]),i.useEffect(()=>{var h;o!=="native"&&(u.some(g=>g.tabKey===o)||l(((h=u[0])==null?void 0:h.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(m||u[0]&&l(u[0].tabKey))},[o,m,u]);const b=i.useMemo(()=>o==="native"&&m?m:u.find(h=>h.tabKey===o)||p||m||u[0],[o,m,p,u]),w=i.useMemo(()=>u.map(h=>({tabKey:h.tabKey,title:ed(h)||n,status:h.status})),[u,n]),x=i.useCallback(h=>{if(h)return d.find(g=>ao(g,{sessionId:h,routeId:h,tabKey:h,providerSessionId:h}))},[d]);return{activeChatTab:o,setActiveChatTab:l,activeConv:b,conversations:d,extensionTabs:w,hasExtensions:w.length>0,resolveConversationByTarget:x}}function Tv({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:l,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:p}){const[b,w]=i.useState("split"),[x,h]=i.useState(()=>is(e)?"native":e.tabKey),g=i.useRef(null),y=i.useMemo(()=>t||r.find(M=>M.id===e.routeId),[e.routeId,t,r]),f=i.useMemo(()=>lt((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:A,extensionTabs:C,hasExtensions:v}=Av({ideData:y,allIdes:r,connectionStates:n,ideName:f||"IDE",preferredTabKey:is(e)?void 0:e.tabKey}),N=i.useMemo(()=>y?Ht(A,y.id):null,[y,A]);i.useEffect(()=>{const M=g.current,F={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(g.current=F,!(M&&M.routeId===F.routeId&&M.tabKey===F.tabKey&&M.streamSource===F.streamSource)){if(is(e)){h("native");return}h(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(x==="native"){if(A.some(M=>M.streamSource==="native"))return;(N==null?void 0:N.streamSource)==="agent-stream"&&h(N.tabKey);return}if(!A.some(M=>M.tabKey===x)){if((N==null?void 0:N.streamSource)==="agent-stream"){h(N.tabKey);return}h("native")}},[A,x,N]);const T=i.useMemo(()=>x==="native"?A.find(M=>M.streamSource==="native")||e:A.find(M=>M.tabKey===x)||e,[e,A,x]),k=vd(T),j=i.useMemo(()=>k.status||k.modalMessage||k.modalButtons?{...T,...k.status?{status:k.status}:{},...k.modalMessage!==void 0?{modalMessage:k.modalMessage}:{},...k.modalButtons!==void 0?{modalButtons:k.modalButtons}:{}}:T,[T,k]),B=Lr(j),L=Vn({sendDaemonCommand:o,activeConv:j,setActionLogs:l,isStandalone:c}),{connScreenshot:S,screenshotUsage:D,handleRemoteAction:$}=Xd({doId:B,targetSessionId:$c(j),connState:j.connectionState||"new",viewMode:b}),E=i.useMemo(()=>a.filter(M=>M.routeId===j.tabKey),[a,j.tabKey]);i.useEffect(()=>{u==null||u(j)},[j,u]),i.useEffect(()=>{const M=F=>{F.key==="Escape"&&p()};return window.addEventListener("keydown",M),()=>window.removeEventListener("keydown",M)},[p]);const I=i.useCallback(M=>{M.stopPropagation()},[]);return s.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:p,children:s.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:I,children:[s.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:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.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:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(Rt,{size:16})}),s.jsx("span",{className:"truncate",children:$o(T)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:p,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(M=>{const F=b===M;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${F?"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:()=>w(M),title:M==="split"?"Split view":"Remote only",children:M==="split"?s.jsx(Ym,{size:15}):s.jsx(Rt,{size:15})},M)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>m(T),title:"Chat History",children:[s.jsx(No,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:p,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${b==="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:[b!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${b==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(Mv,{hasExtensions:v,ideName:f||"IDE",activeChatTab:x,extensionTabs:C,onSelectTab:h}),s.jsx(kc,{activeConv:j,onModalButton:L.handleModalButton}),s.jsx(io,{activeConv:j,ideEntry:y,showMetaChips:!1,handleSendChat:L.handleSendChat,isSendingChat:L.isSendingChat,sendFeedbackMessage:L.sendFeedbackMessage,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:E,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${b==="split"?"order-1 md:order-2":""}`,children:s.jsx(wc,{addLog:()=>{},connState:j.connectionState||"new",connScreenshot:S,screenshotUsage:D,transportType:j.transport,onAction:$})})]})]})})}function _v({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=ix(e);return s.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:[s.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.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:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[s.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",o,"?"]}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:t?"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."})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),s.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"}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function Lv({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var l;return s.jsxs(s.Fragment,{children:[s.jsx(mx,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(qo,{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}),t.conversation&&s.jsx(Tv,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),r.open&&r.targetConv&&(at(r.targetConv)||st(r.targetConv))&&s.jsx(_v,{activeConv:r.targetConv,canSaveAndStop:at(r.targetConv)&&!st(r.targetConv)&&!!((l=r.targetConv.resume)!=null&&l.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),s.jsx(od,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(Iv,{onClose:o.onClose})]})}function Rv({daemons:e,targetVersion:t,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:o}){return e.length===0?null:s.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:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(Tr,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[r?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(l=>{const c=Lt(l,{fallbackId:l.id}),d=n[l.id],m=l.version||l.daemonVersion||"unknown",u=l.versionUpdateRequired===!0,b=Pd(l)==="preview"?"Update to preview":u?"Update now":"Upgrade";return s.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:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(l.id),children:"retry"}):s.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:b})]},l.id)})]}),!r&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(jt,{size:16})})]})}function Pv(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function Dv(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function Ev(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>Dv(t)).map(t=>t.id)}}function $v(){var vi,wi,ji,ki;const{sendCommand:e}=kt(),t=Rr(),r=yd(),n=jo(),a=Ys(),[o,l]=fm(),c=o.get("activeTab"),d=((vi=n.state)==null?void 0:vi.openRemoteForTabKey)||null,m=((wi=n.state)==null?void 0:wi.openMachineId)||null,u=((ji=n.state)==null?void 0:ji.mobileSection)||null,p=Xc(),b=p.ides||[],w=p.initialLoaded??!0,{updateRouteChats:x,setToasts:h}=p,[g,y]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),f=p.toasts||[],A=p.wsStatus||"connected",C=p.isConnected??!0,v=p.connectionStates||{},N=p.showReconnected||!1,{layoutProfile:T,groupAssignments:k,updateGroupAssignments:j,focusedGroup:B,updateFocusedGroup:L,focusGroup:S,groupActiveTabIds:D,updateGroupActiveTabIds:$,setGroupActiveTab:E,groupTabOrders:I,updateGroupTabOrders:M,setGroupTabOrder:F,groupSizes:P,updateGroupSizes:R,isMobile:K,hasHydratedStoredLayout:V,hydrateStoredLayout:te,focusConversationTab:ie}=rg(),[J,me]=i.useState(()=>Qo());i.useEffect(()=>fb(me),[]);const je=i.useMemo(()=>Pv({isMobile:K,mobileViewMode:J}),[K,J]),[ke,q]=i.useState([]),[ge,fe]=i.useState({}),[we,xe]=i.useState({});_r("Dashboard",{ideCount:b.length,toastCount:f.length,focusedGroup:B,groupCount:Object.keys(k).length,actionLogCount:ke.length});const Ne=i.useMemo(()=>b.filter(Je=>Je.type==="adhdev-daemon").sort(Po),[b]),Q=Ne[0],he=!!Q;i.useEffect(()=>{const{metadataDaemonIds:Je,runtimeDaemonIds:Bt}=Ev(Ne);for(const er of Je)t(er,{minFreshMs:3e4}).catch(()=>{});for(const er of Bt)r(er,{minFreshMs:3e4}).catch(()=>{})},[t,r,Ne]);const oe=(Q==null?void 0:Q.terminalBackend)||null,ue=Q?Lt(Q,{fallbackId:Q.id}):null,le=(Q==null?void 0:Q.id)||null,de=i.useMemo(()=>Ab(b,ge),[b,ge]),{hiddenTabs:Z,autoHiddenTabs:ve,autoHideTarget:ce,hideTarget:pe,toggleTarget:ae,showTarget:Ie,showAllTabs:Ce}=Mb(),{conversations:_e,visibleConversations:H,visibleTabKeys:Me,resolveConversationBySessionId:Ae,resolveConversationByTarget:He}=Hb({ides:de,connectionStates:v,clearedTabs:we,hiddenTabs:Z}),Ge=i.useMemo(()=>new Map(_e.map(Je=>[Je.tabKey,Je])),[_e]),Xe=i.useMemo(()=>Ib(_e,Z,ve),[_e,Z,ve]);i.useEffect(()=>{for(const Je of Xe)ce(Je)},[Xe,ce]),Bf(H,je),i.useEffect(()=>{Object.keys(ge).length!==0&&fe(Je=>Tb(Je,b))},[b,ge]);const Ye=i.useMemo(()=>zp(b),[b]),{notifications:tt,unreadCount:ct}=yg({conversations:_e,liveSessionInboxState:Ye}),{handleMarkDashboardNotificationRead:mt,handleMarkDashboardNotificationUnread:pt,handleDeleteDashboardNotification:O}=vg({notifications:tt,sendDaemonCommand:e}),{containerRef:be,normalizedGroupAssignments:Te,numGroups:Be,isSplitMode:qe,groupedConvs:z,moveTabToGroup:U,closeGroup:X,handleResizeStart:re,splitTabRelative:W}=dg({groupAssignments:k,updateGroupAssignments:j,updateFocusedGroup:L,updateGroupActiveTabIds:$,updateGroupTabOrders:M,groupSizes:P,updateGroupSizes:R,isMobile:K,visibleConversations:H,visibleTabKeys:Me}),{activeConv:G,openDesktopConversation:se,requestScrollToBottom:ne,scrollToBottomRequest:Se,setDesktopActiveTab:Ee}=Pg({isMobile:K,conversations:_e,visibleConversations:H,groupActiveTabIds:D,focusedGroup:B,groupedConvs:z,setSearchParams:l});$g({activeConv:G,isMobile:K,liveSessionInboxState:Ye,sendDaemonCommand:e});const{requestedDesktopTabKey:Oe,requestedMobileTabKey:Re,consumeRequestedActiveTab:Fe}=Kb({isMobile:K,urlActiveTab:c,resolveConversationBySessionId:Ae,setSearchParams:l}),{remoteDialogConv:Ue,remoteDialogIdeEntry:Le,remoteDialogActiveConv:Ze,setRemoteDialogActiveConv:et,openRemoteDialog:gt,closeRemoteDialog:yt,cliStopDialogOpen:dt,cliStopTargetConv:xt,requestCliStop:Ve,cancelCliStop:Kt,confirmCliStop:ee}=Fg({isMobile:K,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Oe,conversations:_e,ides:b,resolveConversationByTarget:He,activeConv:G,sendDaemonCommand:e}),{historyModalOpen:$e,openHistoryModal:_,closeHistoryModal:Y,historyTargetConv:ye,isSavedSessionHistoryTarget:We,isHistoryCreatingChat:De,isHistoryRefreshingHistory:Ke,handleHistorySwitchSession:rt,handleHistoryNewChat:At,handleHistoryRefresh:bt,savedHistorySessions:ts,savedHistoryFilters:Er,setSavedHistoryFilters:$r,missingWorkspaceResumePath:Br,isSavedHistoryLoading:Or,resumingSavedHistorySessionId:Fr,handleRefreshSavedHistory:Wr,handleResumeSavedHistorySession:Hr}=Bg({activeConv:G,remoteDialogConv:Ue,remoteDialogActiveConv:Ze,ides:b,sendDaemonCommand:e,updateRouteChats:x,setToasts:h,setClearedTabs:xe,setSearchParams:l}),Lu=i.useMemo(()=>H,[H]),Kr=K&&J==="chat",Ru=i.useMemo(()=>_e.filter(Je=>Yn(Z,Je)),[_e,Z]),bi=i.useCallback(Je=>{const Bt=new URLSearchParams(o);Bt.set("activeTab",Je),l(Bt,{replace:!0})},[o,l]),{trackPendingLaunch:Pu}=Tg({ides:b,conversations:_e,onOpenSession:bi}),{handleBrowseMachineDirectory:Du,handleSaveMachineWorkspace:Eu,handleLaunchMachineIde:$u,handleLaunchMachineProvider:Bu,handleListMachineMeshes:Ou,handleLaunchMeshCoordinator:Fu,handleListMachineSavedSessions:Wu,setActiveCliViewMode:Hu}=_g({sendDaemonCommand:e,trackPendingLaunch:Pu,onOpenSession:bi,activeConv:G,ides:b,setCliViewModeOverrides:fe});_b({visibleConversations:H,clearedTabs:we,setClearedTabs:xe,setActionLogs:q}),Ub({ides:b,sendDaemonCommand:e,setToasts:h,resolveConversationByTarget:He});const{isRefreshingHistory:Ku,handleRefreshHistory:Uu}=Rd({sendDaemonCommand:e,activeConv:G,chats:(ki=b.find(Je=>Je.id===(G==null?void 0:G.routeId)))==null?void 0:ki.chats,updateRouteChats:x,setToasts:h,setClearedTabs:xe});ag({urlActiveTab:K&&!Kr?c:null,conversations:_e,resolveConversationBySessionId:Ae,normalizedGroupAssignments:Te,hasHydratedStoredLayout:K&&!Kr?V:!0,hydrateStoredLayout:K&&!Kr?te:()=>{},focusConversationTab:ie,setSearchParams:l,historyModalOpen:$e,activeConv:G,isRefreshingHistory:Ku,ides:b,handleRefreshHistory:Uu});const zu=i.useMemo(()=>!G||!at(G)||st(G)?null:Js(G),[G]),{versionMismatchDaemons:Gu,hasRequiredVersionDaemons:gi,targetVersion:Vu,versionBannerDismissed:qu,setVersionBannerDismissed:Yu,upgradingDaemons:Xu,handleBannerUpgrade:Ju}=mg({ides:b,sendDaemonCommand:e}),yi=i.useCallback(Je=>{Ie(Je),se(Je)},[se,Ie]),Qu=i.useCallback(Je=>{pe(Je)},[pe]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[s.jsx(px,{terminalBackend:oe,isStandalone:he,machineLabel:ue,machineKey:le}),(!qu||gi)&&s.jsx(Rv,{daemons:Gu,targetVersion:Vu,required:gi,upgradingDaemons:Xu,onUpgrade:Ju,onDismiss:()=>Yu(!0)}),s.jsx(Cv,{showMobileChatMode:Kr,isMobile:K,activeConv:G,wsStatus:A,isConnected:C,onOpenHistory:Je=>{Je&&et(Je),_()},onOpenRemote:gt,onStopCli:Ve,activeCliViewMode:zu,onSetActiveCliViewMode:Hu,mobileChatConversations:Lu,ides:b,actionLogs:ke,sendDaemonCommand:e,setActionLogs:q,setCliViewModeOverrides:fe,isStandalone:he,initialDataLoaded:w,userName:p.userName,requestedMobileTabKey:Re,onRequestedMobileTabConsumed:Fe,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:be,isSplitMode:qe,numGroups:Be,groupSizes:P,groupedConvs:z,clearedTabs:we,focusedGroup:B,focusGroup:S,moveTabToGroup:U,splitTabRelative:W,closeGroup:X,handleResizeStart:re,groupActiveTabIds:D,setGroupActiveTab:E,groupTabOrders:I,setGroupTabOrder:F,toggleHiddenTab:Je=>ae(Ge.get(Je)||{tabKey:Je}),visibleConversations:H,hiddenConversations:Ru,requestedDesktopTabKey:Oe,onRequestedDesktopTabConsumed:Fe,onDesktopActiveTabChange:Ee,onRequestScrollToBottom:ne,onHideConversation:Qu,onShowHiddenConversation:yi,onShowAllHiddenConversations:Ce,scrollToBottomRequest:Se,machineEntries:Ne,layoutProfile:T,onBrowseMachineDirectory:Du,onSaveMachineWorkspace:Eu,onLaunchMachineIde:$u,onLaunchMachineProvider:Bu,onListMachineMeshes:Ou,onLaunchMeshCoordinator:Fu,onListMachineSavedSessions:Wu,notifications:tt,notificationUnreadCount:ct,liveSessionInboxState:Ye,onMarkNotificationRead:mt,onMarkNotificationUnread:pt,onDeleteNotification:O}),s.jsx("style",{children:`
|
|
71
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
72
|
+
`}),s.jsx(Lv,{historyModal:{open:$e,targetConv:ye,ides:b,isCreatingChat:De,isRefreshingHistory:We?!1:Ke,savedSessions:ts,savedHistoryFilters:Er,missingWorkspaceResumePath:Br||null,onSavedHistoryFiltersChange:$r,isSavedSessionsLoading:Or,isResumingSavedSessionId:Fr,onClose:Y,onNewChat:At,onSwitchSession:rt,onRefreshHistory:We?Wr:bt,onResumeSavedSession:Hr},remoteDialog:{conversation:Ue,ideEntry:Le,ides:b,connectionStates:v,actionLogs:ke,sendDaemonCommand:e,setActionLogs:q,isStandalone:he,userName:p.userName,onOpenHistory:Je=>{Je&&et(Je),_()},onConversationChange:et,onClose:yt},cliStopDialog:{open:dt,targetConv:xt,onCancel:Kt,onStopNow:async()=>{await ee("hard")},onSaveAndStop:async()=>{await ee("save")}},connectionBanner:{wsStatus:A,showReconnected:N,loginUrl:p.connectionLoginUrl,onReconnect:p.retryServerConnection},toastOverlay:{toasts:f,onDismiss:Je=>h(Bt=>Bt.filter(er=>er.id!==Je)),onClick:Je=>{if(Je.targetKey){const Bt=He(Je.targetKey);Bt&&(ie(Bt.tabKey,Te),yi(Bt),ne(Bt.tabKey,"toast-open"))}}},onboarding:{open:g,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}}})]})}function Bv({machineId:e,registeredMachineId:t,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,l]=i.useState([]),[c,d]=i.useState(null),[m,u]=i.useState(null),[p,b]=i.useState(!1),[w,x]=i.useState(null),[h,g]=i.useState(!1),[y,f]=i.useState(""),A=i.useRef(null),C=i.useCallback(P=>{A.current=P},[]),v=i.useCallback((P,R,K=!1)=>{l(V=>[...V.slice(-100),{timestamp:Date.now(),level:P,message:R}]),setTimeout(()=>{var V;return(V=a.current)==null?void 0:V.scrollIntoView({behavior:"smooth"})},100),K&&ot.showToast(R,P==="error"||P==="warn"?"warning":"success")},[a]),N=i.useCallback(P=>{const R=P instanceof Error?P.message:String(P||"");return R.includes("P2P command timeout")||R.includes("P2P not connected")||R.includes("P2P not available")},[]),T=i.useCallback(async(P,R)=>{var K;if(!e||c)return!1;d(P),v("info",`Launching ${lt(P)}${R!=null&&R.workspace?` in ${R.workspace}`:""}...`);try{const V={ideType:P,enableCdp:!0};(K=R==null?void 0:R.workspace)!=null&&K.trim()?V.workspace=R.workspace.trim():R!=null&&R.useDefaultWorkspace&&(V.useDefaultWorkspace=!0);const te=await r(e,"launch_ide",V);return v(te!=null&&te.success?"info":"error",te!=null&&te.success?`${lt(P)} launched`:`Failed: ${te==null?void 0:te.error}`,!0),!!(te!=null&&te.success)}catch(V){return v("error",`Launch error: ${V.message}`,!0),!1}finally{d(null)}},[e,c,v,r]),k=i.useCallback(async P=>{if(!e)return{success:!1};const{cliType:R,dir:K,workspaceId:V,useDefaultWorkspace:te,useHome:ie,argsStr:J,model:me,resumeSessionId:je}=P;if(!R)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const ke=J?J.split(/\s+/).filter(Boolean):void 0,q=(K==null?void 0:K.trim())||(V?"(saved id)":te?"(default workspace)":ie?"(home)":"");v("info",`Launching ${R}${q?` in ${q}`:""}${me?` (model: ${me})`:""}...`),u(R);try{const ge={cliType:R,cliArgs:ke,initialModel:me||void 0};K!=null&&K.trim()?ge.dir=K.trim():V?ge.workspaceId=V:te?ge.useDefaultWorkspace=!0:ie&&(ge.useHome=!0),je&&(ge.resumeSessionId=je);const fe=await r(e,"launch_cli",ge),we=(fe==null?void 0:fe.result)||fe;return fe!=null&&fe.success?(v("info",`${R} launched`,!0),(we==null?void 0:we.launchSource)==="home"?v("info","📂 Running in home directory (explicit choice)"):(we==null?void 0:we.launchSource)==="defaultWorkspace"&&v("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:we==null?void 0:we.sessionId}):(v("error",`Failed: ${(fe==null?void 0:fe.error)||(we==null?void 0:we.error)}`,!0),(fe==null?void 0:fe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&x({cliType:R,argsStr:J,model:me}),{success:!1,sessionId:we==null?void 0:we.sessionId})}catch(ge){return N(ge)?(v("warn",`${R} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(v("error",`Launch error: ${ge.message}`,!0),{success:!1})}finally{u(null)}},[e,v,N,r]),j=i.useCallback(async(P,R,K,V)=>e?P?R.trim()?k({cliType:P,dir:R,argsStr:K,model:V}):(x({cliType:P,argsStr:K,model:V}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,k]),B=i.useCallback(async(P,R,K)=>{if(e&&window.confirm(`Stop ${P}?
|
|
73
|
+
This will terminate the process.`))try{const V=await r(e,"stop_cli",{cliType:P,dir:R,targetSessionId:K});V!=null&&V.success?v("info",`${P} stopped`,!0):v("error",`Stop failed: ${(V==null?void 0:V.error)||"Unknown error"}`,!0)}catch(V){v("error",`Stop failed: ${V.message}`,!0)}},[e,v,r]),L=i.useCallback(async P=>{try{await r(P.daemonId,"restart_ide",{ideType:P.type}),v("info",`${lt(P.type)} restart initiated`,!0)}catch(R){v("error",`Restart failed: ${R.message}`,!0)}},[v,r]),S=i.useCallback(async P=>{if(window.confirm(`Stop ${lt(P.type)}?
|
|
74
|
+
This will disconnect CDP and optionally kill the process.`))try{const R=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});R!=null&&R.success?v("info",`${lt(P.type)} stopped`,!0):v("error",`Stop failed: ${(R==null?void 0:R.error)||"Unknown error"}`,!0)}catch(R){v("error",`Stop failed: ${R.message}`,!0)}},[v,r]),D=i.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});v("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){v("error",`Detection failed: ${P.message}`,!0)}},[e,v,r]),$=i.useCallback(async P=>{if(!e||!P.trim())return!1;b(!0);try{const R=await r(e,"workspace_add",{path:P.trim()});return R!=null&&R.success?(v("info",`Workspace added: ${P.trim()}`),!0):(v("error",(R==null?void 0:R.error)||"workspace_add failed"),!1)}catch(R){return v("error",R.message),!1}finally{b(!1)}},[e,v,r]),E=i.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){b(!0);try{const R=await r(e,"workspace_remove",{id:P});R!=null&&R.success?v("info","Workspace removed",!0):v("error",(R==null?void 0:R.error)||"workspace_remove failed",!0)}catch(R){v("error",R.message,!0)}finally{b(!1)}}},[e,v,r]),I=i.useCallback(async P=>{var R;if(e){b(!0);try{const K=await r(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(K!=null&&K.success){v("info",P?"Default workspace updated":"Default workspace cleared",!0);const V=typeof K.defaultWorkspacePath=="string"?K.defaultWorkspacePath:"";V&&((R=A.current)==null||R.call(A,V))}else v("error",(K==null?void 0:K.error)||"workspace_set_default failed",!0)}catch(K){v("error",K.message,!0)}finally{b(!1)}}},[e,v,r]),M=i.useCallback(async P=>{var K;if(!e||!P.trim())return;const R=P.trim();b(!0);try{const V=await r(e,"workspace_set_default",{path:R});V!=null&&V.success?(v("info","Default workspace set from history"),(K=A.current)==null||K.call(A,R)):v("error",(V==null?void 0:V.error)||"Could not set default (path missing on disk?)")}catch(V){v("error",V.message)}finally{b(!1)}},[e,v,r]),F=i.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:t,nickname:y})}catch(P){v("warn",`Live nickname updated, but account sync failed: ${P.message}`)}v("info",`Nickname set to "${y||"(cleared)"}"`),g(!1)}catch(P){v("error",`Failed: ${P.message}`)}},[e,y,t,v,n,r]);return{logs:o,launchingIde:c,launchingAgentType:m,workspaceBusy:p,launchPick:w,setLaunchPick:x,editingNickname:h,setEditingNickname:g,nicknameInput:y,setNicknameInput:f,addLog:v,handleLaunchIde:T,runLaunchCliCore:k,handleLaunchCli:j,handleStopCli:B,handleRestartIde:L,handleStopIde:S,handleDetectIdes:D,handleWorkspaceAdd:$,handleWorkspaceRemove:E,handleWorkspaceSetDefault:I,handleWorkspaceResumePath:M,handleSaveNickname:F,setOnDefaultWorkspaceChanged:C}}function Ov({machineId:e,machine:t,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:l}){var L;const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[p,b]=i.useState(!1),[w,x]=i.useState(""),[h,g]=i.useState([]),[y,f]=i.useState(!1),[A,C]=i.useState(""),v=i.useCallback(async S=>{f(!0),C("");try{const D=await Qn(l,e,S);x(D.path),g(D.directories)}catch(D){C(D instanceof Error?D.message:"Could not load folder")}finally{f(!1)}},[e,l]),N=i.useCallback(()=>{b(!0);const S=[...r.map($=>$.workspace),...n.map($=>$.workspace),...a.map($=>$.workspace)],D=Jn(t.platform,Xn(S,t.defaultWorkspacePath,(t.workspaces||[]).map($=>$.path)));v(D)},[a,n,r,v,t.defaultWorkspacePath,t.platform,t.workspaces]),T=typeof t.uptime=="number"||typeof t.freeMem=="number"||typeof t.availableMem=="number"||Array.isArray(t.loadavg)&&t.loadavg.length>0,k=t.availableMem??t.freeMem??t.totalMem,j=T&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-k)/t.totalMem*100))):0,B=((L=t.loadavg)==null?void 0:L[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(zr,{icon:s.jsx(mc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Jp(t.uptime):"Waiting…"}),s.jsx(zr,{icon:s.jsx(Rt,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(zr,{icon:s.jsx(Io,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(zr,{icon:s.jsx(Jm,{size:16}),label:"ACPs",value:`${a.length}`})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx(Oi,{value:T?Math.min(Math.round(B/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:T?`${B.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Oi,{value:j,max:100,label:"Memory",color:"#3b82f6",detail:T?`${ca(t.totalMem-k)} / ${ca(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${ca(t.totalMem)} total`})]})]}),s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[s.jsx(Ss,{size:14})," Workspaces"]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),s.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:t.defaultWorkspaceId||"",onChange:S=>void u(S.target.value===""?null:S.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(S=>s.jsx("option",{value:S.id,children:S.label||S.path},S.id))]}),t.defaultWorkspacePath&&s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:t.defaultWorkspacePath,children:t.defaultWorkspacePath})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.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:N,children:"Select workspace…"}),s.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(t.workspaces||[]).length>0&&s.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(t.workspaces||[]).map(S=>s.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:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[S.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:zn(S.path,S.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:S.path,children:S.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(S.id),children:"Remove"})]},S.id))})]}),p&&s.jsx(Zn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:h,busy:y,error:A,confirmLabel:"Add workspace",onClose:()=>b(!1),onNavigate:S=>{v(S)},onConfirm:S=>{(async()=>{if(!S)return;await d(S)&&b(!1)})()}})]})}function Fv(e){if(!e||typeof e!="object")return null;const t=e,r=t.result&&typeof t.result=="object"?t.result:t;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function Wv(e,t,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=t.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 Ba(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function Ol(e){if(!e||typeof e!="object")return null;if(Ba(e))return e;const t=e,r=t.result;return Ba(r)?r:Ba(t.sourceConfig)?t.sourceConfig:null}function Hv(e){const t=e.trim();return t||null}const Fl=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],Kv=[{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 Uv({machineId:e,provider:t,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[l,c]=i.useState("codex-cli"),[d,m]=i.useState([]),[u,p]=i.useState(""),[b,w]=i.useState([]),[x,h]=i.useState(""),g=i.useRef(null),y=i.useRef(null),f=k=>{m(j=>j.includes(k)?j.filter(B=>B!==k):[...j,k])},A=()=>m([...Fl]),C=()=>m([]);i.useEffect(()=>{var k;(k=g.current)==null||k.scrollIntoView({behavior:"smooth"})},[b]),i.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const v=i.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const k=await r(e,"provider_auto_fix_status",{providerType:t.type});(k==null?void 0:k.running)===!1&&a==="running"&&(o("done"),w(j=>[...j,`
|
|
75
|
+
✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,t.type,r,a]),N=async()=>{if(d.length!==0){o("running"),w(["🚀 Starting auto-fix...",`Agent: ${l}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),h("");try{const k=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:l,...u?{comment:u}:{}});k!=null&&k.success&&(k!=null&&k.started||k!=null&&k.running)?(w(j=>[...j,"✅ Agent started. Monitoring progress..."]),v()):(o("error"),h((k==null?void 0:k.error)||"Failed to start auto-fix"))}catch(k){o("error"),h((k==null?void 0:k.message)||"Connection failed")}}},T=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),w(k=>[...k,`
|
|
76
|
+
⚠️ Auto-fix cancelled.`]),o("done"),y.current&&clearInterval(y.current)}catch{}};return s.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:s.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:k=>k.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:t.icon||"🔧"}),s.jsxs("div",{children:[s.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",t.displayName]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),s.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),s.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),s.jsx("div",{className:"flex gap-2",children:Kv.map(k=>s.jsxs("button",{onClick:()=>c(k.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:l===k.value?k.color+"66":"var(--border-subtle)",background:l===k.value?k.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:l===k.value?k.color:"var(--text-primary)"},children:k.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:k.desc})]},k.value))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:A,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),s.jsx("button",{onClick:C,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Fl.map(k=>s.jsxs("button",{onClick:()=>f(k),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(k)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(k)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(k)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(k)?"☑ ":"☐ ",k]},k))})]}),s.jsxs("div",{children:[s.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",s.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),s.jsx("textarea",{value:u,onChange:k=>p(k.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")&&s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),s.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:[b.map((k,j)=>s.jsx("div",{className:k.startsWith("✅")?"text-green-400":"",style:k.startsWith("❌")||k.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:k},j)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:g})]}),x&&s.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:x})]})]}),s.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[s.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"]}),s.jsxs("div",{className:"flex gap-2",children:[a==="config"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:N,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"&&s.jsx("button",{onClick:T,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{o("config"),w([]),h("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function zv({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var v;const o=t.filter(N=>N.category==="ide"),[l,c]=i.useState(((v=o[0])==null?void 0:v.type)||""),[d,m]=i.useState(""),[u,p]=i.useState(""),[b,w]=i.useState(!1),[x,h]=i.useState(""),[g,y]=i.useState(!1),f=N=>{const T=N.toLowerCase().replace(/[^a-z0-9-]/g,"");m(T),(!u||u===A(d))&&p(A(T))},A=N=>N.split("-").map(T=>T.charAt(0).toUpperCase()+T.slice(1)).join(" "),C=async()=>{if(!(!d||!u||!l)){w(!0),h("");try{const N=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:l});N!=null&&N.success||N!=null&&N.created?(y(!0),a==null||a(d)):h((N==null?void 0:N.error)||"Failed to create provider")}catch(N){h((N==null?void 0:N.message)||"Connection failed")}w(!1)}};return s.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:s.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:N=>N.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),s.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:g?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[s.jsx("code",{className:"text-violet-400",children:d})," has been created at ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",s.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(N=>s.jsxs("button",{onClick:()=>c(N.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:l===N.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l===N.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:N.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:l===N.type?"#a78bfa":"var(--text-secondary)"},children:N.displayName})]},N.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),s.jsx("input",{value:d,onChange:N=>f(N.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"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),s.jsx("input",{value:u,onChange:N=>p(N.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"})]}),x&&s.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:x})]})}),s.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:g?s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),s.jsx("button",{onClick:C,disabled:!d||!u||b,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||b?.4:1},children:b?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Wl(e){return e==="cli"||e==="acp"}function Gv(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 Vv(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 Hl(e){if(!e)return"No result yet";const t=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t}: ${r} — ${n}`:`${t}: ${r}`}function qv({machineId:e,providers:t,sendDaemonCommand:r}){var $;const[n,a]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(null),[m,u]=i.useState("all"),[p,b]=i.useState(null),[w,x]=i.useState(!1),[h,g]=i.useState(null),[y,f]=i.useState("normal"),[A,C]=i.useState(""),[v,N]=i.useState(!1),T=i.useCallback(async()=>{if(e)try{const E=await r(e,"get_provider_source_config",{}),I=Ol(E);I&&(g(I),f(I.sourceMode),C(I.explicitProviderDir||""))}catch{}},[e,r]),k=i.useCallback(async()=>{if(e){l(!0);try{const E=await r(e,"get_provider_settings",{}),I=Fv(E);if(I){const M=Wv(I,t,{filterSchema:F=>F.filter(P=>P.key!=="enabled")});M.sort((F,P)=>F.category.localeCompare(P.category)||F.displayName.localeCompare(P.displayName)),a(M)}}catch{}l(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&k(),h||T()},[]);const j=async(E,I,M)=>{d(`${E}.${I}`),a(F=>F.map(P=>P.type===E?{...P,values:{...P.values,[I]:M}}:P));try{const F=await r(e,"set_provider_setting",{providerType:E,key:I,value:M});F!=null&&F.success||k()}catch{k()}d(null)},B=async(E,I)=>{await j(E,"enabled",I),await k()},L=async E=>{d(`${E}.detect`);try{await r(e,"detect_provider",{providerType:E})}finally{await k(),d(null)}},S=async E=>{await j(E,"executablePath",""),await j(E,"executableArgs",""),await k()},D=async()=>{N(!0);try{const E=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:Hv(A)}),I=Ol(E);I?(g(I),f(I.sourceMode),C(I.explicitProviderDir||"")):await T(),await k()}catch{await T()}N(!1)};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex justify-between items-center mb-4",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(E=>s.jsx("button",{onClick:()=>u(E),className:`machine-btn text-[10px] px-2 py-0.5 ${m===E?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:E.toUpperCase()},E))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>x(!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"}),s.jsx("button",{onClick:k,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),s.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."})]}),s.jsx("button",{onClick:T,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),s.jsxs("select",{value:y,onChange:E=>f(E.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),s.jsx("input",{type:"text",value:A,onChange:E=>C(E.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void D(),disabled:v,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:v?"Applying…":"Apply + Reload"})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(h==null?void 0:h.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(h==null?void 0:h.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",(($=h==null?void 0:h.providerRoots)==null?void 0:$.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(E=>E.category===m).length>1&&(()=>{const E=n.filter(P=>P.category===m),I=new Map;for(const P of E)for(const R of P.schema){if(R.type!=="boolean")continue;const K=I.get(R.key),V=!!(P.values[R.key]??R.default);K?(K.onCount+=V?1:0,K.total+=1):I.set(R.key,{label:R.label||R.key,onCount:V?1:0,total:1})}const M=[...I.entries()].filter(([,P])=>P.total===E.length);if(M.length===0)return null;const F=async(P,R)=>{for(const K of E)await j(K.type,P,R)};return s.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[s.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",E.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:M.map(([P,R])=>{const K=R.onCount===R.total,V=R.onCount===0;return s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:"text-text-secondary font-medium",children:R.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",R.onCount,"/",R.total,")"]}),s.jsx("button",{onClick:()=>void F(P,!0),disabled:K,className:`machine-btn text-[9px] px-1.5 py-px ${K?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void F(P,!1),disabled:V,className:`machine-btn text-[9px] px-1.5 py-px ${V?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},P)})})]})})(),o&&n.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):s.jsx("div",{className:"flex flex-col gap-2",children:n.filter(E=>m==="all"||E.category===m).map(E=>s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[s.jsx("span",{className:"text-lg",children:E.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:E.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:E.category==="acp"?"rgba(139,92,246,0.08)":E.category==="cli"?"rgba(59,130,246,0.08)":E.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:E.category==="acp"?"#a78bfa":E.category==="cli"?"#60a5fa":E.category==="ide"?"#86efac":"var(--status-warning)"},children:E.category}),Wl(E.category)&&(()=>{const I=t.find(P=>P.type===E.type),M=(I==null?void 0:I.enabled)===!0||E.values.enabled===!0,F=(I==null?void 0:I.machineStatus)||(M?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${Vv(F)}`,children:Gv(F)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void B(E.type,!M),disabled:c===`${E.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${M?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:M?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void L(E.type),disabled:!M||c===`${E.type}.detect`,title:M?"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 ${M?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void S(E.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),E.category==="ide"&&s.jsx("button",{onClick:()=>b(t.find(I=>I.type===E.type)||{type:E.type,name:E.displayName,displayName:E.displayName,icon:E.icon,category:E.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"})]}),Wl(E.category)&&(()=>{const I=t.find(M=>M.type===E.type);return s.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:[s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",Hl(I==null?void 0:I.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Hl(I==null?void 0:I.lastVerification)]}),s.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."})]})})(),s.jsx("div",{className:"flex flex-col gap-2",children:E.schema.map(I=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[I.label||I.key,c===`${E.type}.${I.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),I.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:I.description})]}),s.jsx("div",{className:"shrink-0",children:I.type==="boolean"?s.jsx("button",{onClick:()=>j(E.type,I.key,!(E.values[I.key]??I.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:E.values[I.key]??I.default?"#8b5cf6":"var(--border-subtle)"},children:s.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:E.values[I.key]??I.default?21:3}})}):I.type==="number"?s.jsx("input",{type:"number",value:Number(E.values[I.key]??I.default??0)||0,min:I.min,max:I.max,onChange:M=>{const F=parseInt(M.target.value)||0;I.min!==void 0&&F<I.min||I.max!==void 0&&F>I.max||j(E.type,I.key,F)},className:"machine-input w-20 text-center text-[11px]"}):I.type==="select"&&I.options?s.jsx("select",{value:String(E.values[I.key]??I.default??""),onChange:M=>j(E.type,I.key,M.target.value),className:"machine-input text-[11px]",children:I.options.map(M=>s.jsx("option",{value:M,children:M},M))}):s.jsx("input",{type:"text",value:String(E.values[I.key]??I.default??""),onBlur:M=>j(E.type,I.key,M.target.value),className:"machine-input w-[120px] text-[11px]"})})]},I.key))})]},E.type))}),p&&s.jsx(Uv,{machineId:e,provider:p,sendDaemonCommand:r,onClose:()=>b(null)}),w&&s.jsx(zv,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>x(!1),onCreated:()=>{x(!1),k()}})]})}const Yv=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Xv({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function Jv(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Qv(e){return e.trim().toLowerCase()}function ta(e,t){const r=Qv(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function hi(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function qs(e,t=220){const r=hi(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Zv(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.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 t=="string"){const r=t.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function ew(e,t){return e.filter(r=>ta([r.level,r.message],t))}function Kl(e){return`${e.timestamp}:${e.level}:${e.message}`}function tw(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const l of e.entries)n.set(Kl(l),l);for(const l of t.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 t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function sw(e,t,r=120){if(t.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of t)n.set(a.id,a);return Array.from(n.values()).sort((a,o)=>a.ts-o.ts).slice(-r)}function rw(e,t){return e.split(`
|
|
77
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>ta([r],t))}function nw(e,t){return e.filter(r=>ta([r.level,r.category,r.stage,r.interactionId,hi(r.payload)],t))}function aw(e,t){return e.filter(r=>ta([r.kind,r.topic,r.interactionId,hi(r.payload)],t))}function Ul(e){return e==="warn"||e==="error"}function ow({daemonLogs:e,daemonRawLines:t,trace:r,webEvents:n}){return{all:e.length+t.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=>Ul(a.level)).length+r.filter(a=>Ul(a.level)).length}}function iw({daemonLogs:e,daemonRawLines:t,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(`
|
|
78
|
+
`)):t.length>0&&a.push(["[daemon logs]",...t].join(`
|
|
79
|
+
`)),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(`
|
|
80
|
+
`)),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(`
|
|
81
|
+
`)),a.join(`
|
|
82
|
+
|
|
83
|
+
`)}function lw({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[l,c]=i.useState(""),[d,m]=i.useState([]),[u,p]=i.useState([]),[b,w]=i.useState(null),[x,h]=i.useState(!0),[g,y]=i.useState("info"),[f,A]=i.useState("all"),[C,v]=i.useState(!0),[N,T]=i.useState(!0),[k,j]=i.useState(""),[B,L]=i.useState(""),[S,D]=i.useState(0),$=i.useRef(0),E=i.useRef(0),I=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),M=i.useRef([]),F=i.useCallback(()=>{const J={entries:[],kind:"empty",rawText:"",lastTs:0};I.current=J,$.current=0,n([]),c(""),o("empty"),v(!0)},[]),P=i.useCallback(()=>{M.current=[],E.current=0,m([]),T(!0)},[]),R=i.useCallback(J=>{J!==g&&(F(),y(J))},[g,F]),K=i.useCallback(J=>{A(me=>me===J?me:J)},[]),V=i.useCallback(()=>{F(),P(),p([]),w(null),j(""),L(""),Fs.clear()},[F,P]),te=i.useCallback(()=>{D(J=>J+1)},[]),ie=i.useCallback(async()=>{if(!e)return;const J=$.current,me=E.current,[je,ke]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:g,since:J}),t(e,"get_debug_trace",Xv({count:120,since:me,category:f}))]);if(je.status==="fulfilled"){const q=je.value,ge=(q==null?void 0:q.result)||q,fe=Zv(ge),we=tw(I.current,fe,300);I.current=we,$.current=we.lastTs,v(!1),j((q==null?void 0:q.success)===!1?String((q==null?void 0:q.error)||"Could not load daemon logs"):""),o(we.kind),c(we.rawText),n(we.entries)}else v(!1),j(je.reason instanceof Error?je.reason.message:"Could not load daemon logs");if(ke.status==="fulfilled"){const q=ke.value,ge=(q==null?void 0:q.result)||q;if((q==null?void 0:q.success)===!1)L(String((q==null?void 0:q.error)||"Could not load daemon trace"));else if(Array.isArray(ge==null?void 0:ge.trace)){const fe=ge.trace,we=sw(M.current,fe,120),xe=fe.reduce((Ne,Q)=>Math.max(Ne,Number(Q.ts||0)),me);M.current=we,xe>me&&(E.current=xe),L(""),m(we)}else L("");T(!1)}else T(!1),L(ke.reason instanceof Error?ke.reason.message:"Could not load daemon trace");p(Fs.list({limit:120})),w(Date.now())},[g,e,t,f]);return i.useEffect(()=>{P()},[P,f]),i.useEffect(()=>{if(!e||(ie(),!x))return;const J=setInterval(()=>{ie()},3e3);return()=>clearInterval(J)},[x,ie,e,S]),{daemonLogs:r,daemonLogKind:a,daemonRawText:l,debugTrace:d,webEvents:u,lastUpdatedAt:b,autoRefresh:x,logLevel:g,traceCategory:f,daemonLoading:C,traceLoading:N,daemonFetchError:k,traceFetchError:B,setAutoRefresh:h,setLogLevel:R,setTraceCategory:K,refresh:te,clear:V}}function cw({daemonLoading:e,traceLoading:t,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":t?"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 zl(e){return e==="warn"||e==="error"}function dw(e){const t=e.toLowerCase();return/\[(err|error)\]/i.test(e)||t.includes(" error ")||t.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||t.includes(" warning ")||t.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function uw(e,t){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+t}function Gl(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function mw(e){const t=qs(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function pw(e){const t=qs(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function hw({daemonLogs:e,daemonRawLines:t,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:pw(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:mw(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),t.forEach((o,l)=>{a.push({id:`raw-file-${l}`,source:"raw_file",ts:uw(o,l),severity:dw(o),message:o,raw:o})}),a.sort((o,l)=>o.ts!==l.ts?o.ts-l.ts:Gl(o.source)-Gl(l.source))}function fw(e){return`${e.source}:${e.severity}:${e.message}`}function xw(e){const t=e.filter(n=>zl(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!zl(n.severity))continue;const a=fw(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:t.length,latestIssue:t[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 bw(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Vl(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${bw(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function gw({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
84
|
+
`)),a.push(["[source status]",...r.map(l=>`${l.label}: ${l.status} - ${l.detail}`)].join(`
|
|
85
|
+
`)),t.latestIssue&&a.push(["[latest issue]",Vl(t.latestIssue)].join(`
|
|
86
|
+
`)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(l=>`${l.count}x ${l.severity.toUpperCase()} ${l.source} ${l.message}`)].join(`
|
|
87
|
+
`));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(Vl):["No diagnostic events captured."]].join(`
|
|
88
|
+
`)),a.join(`
|
|
89
|
+
|
|
90
|
+
`)}function yw(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function vw(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function ww({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:l,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:p}){const b=Jv(n,o),w=ew(e,c),x=rw(t,c),h=nw(b,c),g=aw(a,c),y=yw(w,l),f=l==="all"?x:[],A=vw(h,l),C=l==="issues"?[]:g,v=ow({daemonLogs:w,daemonRawLines:x,trace:h,webEvents:g}),N=hw({daemonLogs:y,daemonRawLines:f,trace:A,webEvents:C}),T=xw(N),k=cw({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:p,daemonLogKind:r,daemonLogsCount:w.length,daemonRawLineCount:x.length,traceCount:h.length,webEventCount:g.length});return{filteredDaemonLogs:w,filteredDaemonRawLines:x,filteredTraceEntries:h,filteredWebEvents:g,visibleDaemonLogs:y,visibleDaemonRawLines:f,visibleTraceEntries:A,visibleWebEvents:C,quickFilterCounts:v,diagnosticEvents:N,diagnosticsSummary:T,sourceStates:k}}function jw(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Iu(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function go(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 Oa(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 fi(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function kw({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${go(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Iu(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:fi(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function Sw({quickFilter:e,quickFilterCounts:t,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:l,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(p=>s.jsx("button",{type:"button",onClick:()=>a(p.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===p.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:p.label},p.id))}),s.jsx("input",{value:r,onChange:p=>o(p.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"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:l,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function Nw({logLevel:e,traceCategory:t,onLogLevelChange:r,onTraceCategoryChange:n}){return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.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))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:Yv.map(a=>s.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function Cw({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:l,traceFetchError:c}){var u,p;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((p=e.latestIssue)==null?void 0:p.severity)==="warn"?"warning":"good",m=l||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Oa(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.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"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Oa(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[fi(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:Iu(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Oa(m)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:l||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",jw(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(b=>s.jsxs("div",{children:[b.label,": ",b.status]},b.id))})]})]})}function Iw({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",fi(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function Mw({streams:e,sectionsOpen:t,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:l,visibleWebEvents:c,quickFilter:d,searchQuery:m}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.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:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.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&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>s.jsx(kw,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.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:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.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)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.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&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.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&&s.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&&s.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,p)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${p}`)),e.daemonLogKind!=="text"&&a.map((u,p)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${go(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.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"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${p}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.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:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.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&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&l.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&l.length===0&&!e.traceFetchError&&s.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=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${go(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:qs(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.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:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.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&&s.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=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:qs(u.payload,360)||"No payload"})]},u.id))]})]})]})}function Aw({machineId:e,sendDaemonCommand:t}){const r=lw({machineId:e,sendDaemonCommand:t}),[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),p=i.useMemo(()=>ww({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&&p.diagnosticEvents.length>0){const x=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=m.current)==null||h.scrollIntoView({behavior:x}),u.current=!0},50)}},[p.diagnosticEvents.length,r.autoRefresh]);const b=i.useCallback(async()=>{var h;const x=iw({daemonLogs:p.visibleDaemonLogs,daemonRawLines:p.visibleDaemonRawLines,trace:p.visibleTraceEntries,webEvents:p.visibleWebEvents});if(!x.trim()){ot.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(x)),ot.showToast("Copied visible logs to clipboard.","success")}catch(g){ot.showToast(g instanceof Error?g.message:"Could not copy visible logs","warning")}},[p.visibleDaemonLogs,p.visibleDaemonRawLines,p.visibleTraceEntries,p.visibleWebEvents]),w=i.useCallback(async()=>{var h;const x=gw({events:p.diagnosticEvents,summary:p.diagnosticsSummary,sources:p.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(x)),ot.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){ot.showToast(g instanceof Error?g.message:"Could not copy diagnostic bundle","warning")}},[p.diagnosticEvents,p.diagnosticsSummary,p.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(Sw,{quickFilter:n,quickFilterCounts:p.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:l,onCopyDiagnostics:()=>{w()},onCopyVisible:()=>{b()},onToggleAutoRefresh:()=>r.setAutoRefresh(x=>!x),onRefresh:r.refresh,onClear:r.clear}),s.jsx(Nw,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(Cw,{diagnosticsSummary:p.diagnosticsSummary,diagnosticEventsCount:p.diagnosticEvents.length,sourceStates:p.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(Iw,{patterns:p.diagnosticsSummary.repeatedPatterns}),s.jsx(Mw,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:p.diagnosticEvents,visibleDaemonLogs:p.visibleDaemonLogs,visibleDaemonRawLines:p.visibleDaemonRawLines,visibleTraceEntries:p.visibleTraceEntries,visibleWebEvents:p.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function Tw(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 Mu(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function _w(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const l=String((o==null?void 0:o.lifecycle)||"").trim(),c=Mu((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)?t.push(o):(l==="stopped"||l==="failed")&&(d||c)?r.push(o):n.push(o)}return{liveRuntimes:t,recoverySnapshots:r,inactiveRecords:n}}function Lw(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Fa(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 Wa(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Ha(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function ql(e){if(!e)return"unknown";const t=Date.now()-e,r=Math.max(0,Math.round(t/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 Rw(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function Pw(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 Dw(e){var r;const t=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}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(n=>n>1).length}function Ew({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,l]=i.useState(null),[c,d]=i.useState(!1),m=jb(e,{enabled:!!e,includeSessions:!0,limit:Yi,intervalMs:gf}),u=m.diagnostics,p=m.loading,b=m.applyDiagnostics,w=i.useMemo(()=>Tw({diagnostics:u,loading:p,refreshing:c,error:n}),[u,p,c,n]),x=i.useMemo(()=>new Map(t.map(L=>[L.sessionId||L.id,L])),[t]),h=i.useCallback(async()=>{if(e){d(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Yi}),S=Wa(L);if(!(S!=null&&S.success))throw new Error((S==null?void 0:S.error)||"Could not load hosted runtime diagnostics");b(S.diagnostics||S.result||null),a("")}catch(L){const S=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(S)}finally{d(!1)}}},[b,e,r]);i.useEffect(()=>{!e||u||p||c||h()},[u,p,e,h,c]);const g=i.useCallback(async(L,S)=>{const D=`${L}:${S.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${S.displayName}?
|
|
91
|
+
This will terminate the hosted runtime.`))){l(D);try{const $=await r(e,L,{sessionId:S.sessionId}),E=Wa($);if(!(E!=null&&E.success))throw new Error((E==null?void 0:E.error)||"Session host action failed");const I=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";ot.showToast(`Session host ${I}: ${S.displayName}`,"success"),await h()}catch($){const E=$ instanceof Error?$.message:"Session host action failed";ot.showToast(E,"warning"),a(E)}finally{l($=>$===D?null:$)}}},[e,h,r]),y=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
92
|
+
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 S=await r(e,"session_host_prune_duplicate_sessions",{}),D=Wa(S);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Duplicate prune failed");const $=D.result||{},E=Array.isArray($.prunedSessionIds)?$.prunedSessionIds.length:0,I=typeof $.duplicateGroupCount=="number"?$.duplicateGroupCount:0;ot.showToast(`Pruned ${E} duplicate runtime(s) across ${I} group(s)`,"success"),await h()}catch(S){const D=S instanceof Error?S.message:"Duplicate prune failed";ot.showToast(D,"warning"),a(D)}finally{l(S=>S==="session_host_prune_duplicate_sessions"?null:S)}}},[e,h,r]),f=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((L,S)=>(S.lastActivityAt||0)-(L.lastActivityAt||0)),[u==null?void 0:u.sessions]),A=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)||[]}:_w(f),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,f]),C=A.liveRuntimes,v=A.recoverySnapshots,N=A.inactiveRecords,T=i.useMemo(()=>Dw(C),[C]),k=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),j=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[u==null?void 0:u.recentLogs]),B=(L,S)=>{var K;const D=o===`session_host_resume_session:${L.sessionId}`,$=o===`session_host_restart_session:${L.sessionId}`,E=o===`session_host_stop_session:${L.sessionId}`,I=Mu(L.meta),M=x.get(L.sessionId),F=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,P=S==="recovery"?"Recover":"Resume",R=Lw(S);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:L.displayName||(M==null?void 0:M.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${Pw(L.lifecycle)}`,children:L.lifecycle}),I&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:I})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:L.workspaceLabel||(M==null?void 0:M.runtimeWorkspaceLabel)||L.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:L.runtimeKey}),L.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",L.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((K=L.writeOwner)==null?void 0:K.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:Rw(L.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(lc,{size:11})," ",F]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",ql(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",R]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[S==="recovery"&&(L.lifecycle==="interrupted"||L.lifecycle==="failed"||L.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_resume_session",L)},children:D?`${P}ing…`:P}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_restart_session",L)},children:$?"Restarting…":"Restart"}),S==="live"&&(L.lifecycle==="running"||L.lifecycle==="starting"||L.lifecycle==="interrupted")&&s.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:()=>{g("session_host_stop_session",L)},children:E?"Stopping…":"Stop"})]})]})},L.sessionId)};return s.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(os,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:kx()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[T>0&&s.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 (${T})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${w.toneClass}`,children:w.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:p||c,children:[s.jsx(Tr,{size:13}),p||c?"Refreshing…":"Refresh"]})]})]}),n&&!u&&s.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:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Ir,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:ql(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Ha(u.hostStartedAt)})]})]}),j&&s.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:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(Ir,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:j.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Ha(j.timestamp),j.sessionId?` · ${j.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Io,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Fa("live")}),C.length===0?s.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."}):s.jsx("div",{className:"space-y-2",children:C.map(L=>B(L,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(os,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Fa("recovery")}),v.length===0?s.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."}):s.jsx("div",{className:"space-y-2",children:v.map(L=>B(L,"recovery"))})]}),N.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Fa("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:N.map(L=>B(L,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),k.length===0?s.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."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:k.map(L=>{var D;const S=f.find($=>$.sessionId===L.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(S==null?void 0:S.displayName)||((D=x.get(L.sessionId))==null?void 0:D.cliName)||L.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[L.action,L.lifecycle?` · ${L.lifecycle}`:"",L.detail?` · ${L.detail}`:"",L.error?` · ${L.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${L.success===!1?"text-red-300":"text-text-secondary"}`,children:Ha(L.timestamp)})]},`${L.sessionId}:${L.timestamp}:${L.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function $w({machine:e,launchPick:t,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return s.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:s.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:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.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."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.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=>s.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:t.cliType,workspaceId:o.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Ka({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function Ua({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function Bw({machineEntry:e,providers:t,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=Pd(e),p=Ps(e,m),b=jr(e,p),w=u==="preview"?"Update to preview":"Update daemon";return s.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&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ka,{icon:s.jsx(Zt,{size:13}),children:"Current Chats"}),s.jsx(Ua,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(x=>{const h=ho(x);return s.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(x),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:ut(x)}),h>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Kn(h)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Cs(x)})]},x.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ka,{icon:s.jsx(mc,{size:13}),children:"Recent Launches"}),s.jsx(Ua,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(x=>{const{metaText:h,updatedLabel:g}=Gd(x);return s.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(x),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:x.label}),g&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:g})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:h})]},x.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ka,{icon:s.jsx(Ir,{size:13}),children:"Daemon Update"}),s.jsx(Ua,{className:"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:b?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[b?"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.",p&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",p,u?` (${u})`:""]})]}),s.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:[s.jsx(Tr,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:w})]})]})})]})]})}function Ow(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function Fw({machine:e,selectedWorkspace:t,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:l,onOpenBrowseDialog:c}){return s.jsxs("div",{className:"mb-3",children:[s.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[s.jsx("select",{value:t,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?s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>s.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",zn(d.path,d.label)]},d.id)),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):s.jsxs(s.Fragment,{children:[s.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),s.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),t==="__custom__"&&(a?s.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…"}):s.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}))]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:t==="__custom__"?r?s.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?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:t===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),s.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const Ww={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 ln(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function za({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:l,sendDaemonCommand:c,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const p=Ys(),{handleLaunchIde:b,handleStopCli:w,handleRestartIde:x,handleStopIde:h,handleDetectIdes:g,launchingIde:y,launchingAgentType:f,addLog:A}=l,[C,v]=i.useState(null),N=i.useCallback(_=>{_&&p(ls(_))},[p]),T=Ww[e],k=e==="ide",j=e==="acp",B=i.useMemo(()=>n.filter(_=>Is(_,e)),[e,n]),L=i.useMemo(()=>new Map(B.map(_=>[_.type,_.displayName||_.type])),[B]),[S,D]=i.useState(""),[$,E]=i.useState(""),[I,M]=i.useState([]),[F,P]=i.useState(""),[R,K]=i.useState(""),[V,te]=i.useState([]),[ie,J]=i.useState(!1),[me,je]=i.useState(!1),[ke,q]=i.useState(""),[ge,fe]=i.useState(!1),[we,xe]=i.useState(()=>Nt()),[Ne,Q]=i.useState(null),[he,oe]=i.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[ue,le]=i.useState(m||""),[de,Z]=i.useState([]),[ve,ce]=i.useState(!1),[pe,ae]=i.useState(""),[Ie,Ce]=i.useState([]),[_e,H]=i.useState(!1),[Me,Ae]=i.useState(""),He=i.useRef(null),[Ge,Xe]=i.useState(null),Ye=i.useRef("__home__"),[tt,ct]=i.useState("__home__"),[mt,pt]=i.useState(!1),O=i.useRef(0),be=de.filter(_=>!a.some(Y=>Y.type===_&&vt(Y.status)!=="stopped")),Te=i.useRef({});i.useEffect(()=>{t.defaultWorkspaceId&&!he&&oe(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){oe("__custom__"),le(m);return}d&&(oe(d),le(""))},[d,m]),i.useEffect(()=>{k||S&&(B.some(_=>_.type===S)||(D(""),K("")))},[B,k,S]);const Be=(()=>{if(he==="__custom__")return ue.trim();if(!he)return"";const _=(t.workspaces||[]).find(Y=>Y.id===he);return(_==null?void 0:_.path)||""})(),qe=i.useCallback(_=>{const Y=Te.current[_];Y&&(clearTimeout(Y),delete Te.current[_]),Z(ye=>ye.includes(_)?ye.filter(We=>We!==_):ye)},[]),z=i.useRef(new Set),U=i.useCallback(async _=>{if(c){H(!0),Ae("");try{const Y=await Qn(c,r,_);ae(Y.path),le(Y.path),Ce(Y.directories)}catch(Y){Ae(Y instanceof Error?Y.message:"Could not load folder")}finally{H(!1)}}},[r,c]),X=i.useCallback(()=>{if(!c)return;oe("__custom__"),ce(!0);const _=a.map(ye=>ye.workspace),Y=Jn(t.platform,Xn(ue.trim(),Be,m,_,t.defaultWorkspacePath,(t.workspaces||[]).map(ye=>ye.path)));U(Y)},[ue,m,U,t.defaultWorkspacePath,t.platform,t.workspaces,a,Be,c]),re=i.useCallback(_=>{const Y=String(_.workspace||"").trim();if(!Y)return;const ye=(t.workspaces||[]).find(We=>ln(We.path)===ln(Y));if(ye){oe(ye.id),le("");return}oe("__custom__"),le(Y)},[t.workspaces]),W=i.useCallback(_=>{const Y=String(_.workspace||"").trim();if(!Y)return{workspaceId:null,workspacePath:"",useHome:!0};const ye=(t.workspaces||[]).find(We=>ln(We.path)===ln(Y));return ye?{workspaceId:ye.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:Y,useHome:!1}},[t.workspaces]),G=i.useCallback(async _=>{if(!c||!_||e!=="cli"){te([]),J(!1),je(!1),q("");return}const Y=O.current+1;O.current=Y,J(!0),q("");try{const ye=await c(r,"list_saved_sessions",{providerType:_,kind:"cli",limit:30});if(O.current!==Y)return;const We=(ye==null?void 0:ye.result)??ye;te(Array.isArray(We==null?void 0:We.sessions)?We.sessions:[])}catch(ye){if(O.current!==Y)return;te([]),q(ye instanceof Error?ye.message:"Could not load saved sessions")}finally{O.current===Y&&(J(!1),je(!0))}},[e,r,c]),se=i.useMemo(()=>{if(e!=="cli"||!S)return null;const _=L.get(S)||S;return{routeId:r,daemonId:r,providerSessionId:R||void 0,transport:"pty",mode:"chat",agentName:_,agentType:S,status:"idle",title:_,messages:[],ideType:S,workspaceName:Be,workspacePath:Be,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${S}`}},[e,r,L,Be,R,S]),ne=i.useCallback(_=>{if(e==="ide"||!_){M([]);return}M(bo(r,_))},[e,r]),Se=i.useCallback((_,Y)=>{e==="ide"||!_||(Ey(r,_,Y),M(bo(r,_)))},[e,r]);i.useEffect(()=>{O.current+=1,K(""),ne(S),je(!1),te([]),q(""),J(!1)},[e,ne,G,S]);const Ee=i.useMemo(()=>V.find(_=>_.providerSessionId===R)||null,[V,R]);i.useEffect(()=>{if(!R)return;const _=V.find(Y=>Y.providerSessionId===R);_!=null&&_.canResume||K("")},[V,R]);const Oe=i.useCallback((_,Y)=>{He.current=Y,Ye.current=_.selectedWorkspaceKey||"__home__",ct(_.selectedWorkspaceKey||"__home__"),Xe(_)},[]),Re=i.useCallback(()=>{He.current&&(pt(!0),He.current().finally(()=>{He.current=null,pt(!1),Xe(null)}))},[]),Fe=i.useCallback(_=>{if(!_)return;Z(ye=>ye.includes(_)?ye:[...ye,_]);const Y=Te.current[_];Y&&clearTimeout(Y),Te.current[_]=setTimeout(()=>{Z(ye=>ye.includes(_)?ye.filter(We=>We!==_):ye),delete Te.current[_]},2e4)},[]);i.useEffect(()=>{for(const Y of a)vt(Y.status)!=="stopped"&&(de.includes(Y.type)&&!z.current.has(Y.type)&&(z.current.add(Y.type),A("info",`${L.get(Y.type)||Y.type} launched`,!0)),qe(Y.type));const _=new Set(a.filter(Y=>vt(Y.status)!=="stopped").map(Y=>Y.type));z.current.forEach(Y=>{!de.includes(Y)&&!_.has(Y)&&z.current.delete(Y)})},[A,qe,a,de,L]),i.useEffect(()=>()=>{Object.values(Te.current).forEach(clearTimeout),Te.current={}},[]);const[Ue,Le]=i.useState({}),[Ze,et]=i.useState(null);i.useEffect(()=>{if(!k||!r||!c)return;(async()=>{try{const Y=await c(r,"get_ide_extensions",{}),ye=(Y==null?void 0:Y.result)||Y;ye!=null&&ye.success&&(ye!=null&&ye.ideExtensions)&&Le(ye.ideExtensions)}catch{}})()},[k,r,c]);const gt=_=>k?lt(_.type):e==="cli"?_.cliName:_.acpName,yt=k?t.detectedIdes||[]:[],dt=i.useCallback(async _=>{const Y=(_==null?void 0:_.type)||S,ye=(_==null?void 0:_.workspacePath)??Be;if(k){await b(Y,ye?{workspace:ye}:void 0)&&Fe(Y);return}const We=await l.runLaunchCliCore({cliType:Y,dir:_!=null&&_.workspaceId?void 0:ye||void 0,workspaceId:(_==null?void 0:_.workspaceId)||void 0,useHome:(_==null?void 0:_.useHome)||!(_!=null&&_.workspaceId)&&!ye,argsStr:(_==null?void 0:_.argsStr)??($||void 0),model:(_==null?void 0:_.model)??(j&&F||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!j&&e==="cli"&&Y===S&&R||void 0});if(We.success||We.pending){const De=(_==null?void 0:_.argsStr)??$;!k&&(De!=null&&De.trim())&&(ou(r,Y,De),ne(Y)),Fe(Y),We.success&&We.sessionId&&N(We.sessionId)}},[l,b,j,k,$,F,ne,Fe,r,N,Be,R,S]),xt=nd(k?"ide":j?"acp":"cli",!k&&!j&&!!R),Ve=ad(k?"ide":j?"acp":"cli",!k&&!j&&!!R),Kt=()=>{var De;const _=k?lt(S):L.get(S)||S,Y=!k&&!j&&!!R,{options:ye,selectedKey:We}=js({machine:t,currentWorkspaceId:he&&he!=="__custom__"?he:null,currentWorkspacePath:Be});Oe({title:Y?Go(_):bs("start-fresh",_),description:Y?Vo():gs("start-fresh"),confirmLabel:xt,busyLabel:Ve,workspaceOptions:ye,selectedWorkspaceKey:We,details:[{label:"Mode",value:T.label},{label:"Provider",value:_},...!k&&e==="cli"&&R?[{label:"Resume",value:((De=V.find(Ke=>Ke.providerSessionId===R))==null?void 0:De.title)||R}]:[],...!k&&$.trim()?[{label:"Arguments",value:$.trim()}]:[],...j&&F.trim()?[{label:"Model",value:F.trim()}]:[]]},async()=>{const Ke=ye.find(rt=>rt.key===Ye.current);Ke!=null&&Ke.workspaceId?(oe(Ke.workspaceId),le("")):Ke!=null&&Ke.workspacePath?(oe("__custom__"),le(Ke.workspacePath)):(oe(""),le("")),await dt({workspaceId:(Ke==null?void 0:Ke.workspaceId)??null,workspacePath:(Ke==null?void 0:Ke.workspacePath)??"",useHome:!(Ke!=null&&Ke.workspaceId)&&!(Ke!=null&&Ke.workspacePath)})})},ee=_=>{k?h(_):w(_.type,_.workspace,_.id)},$e=i.useCallback(async(_,Y,ye=!1)=>{if(_.mode===Y){ye&&_.sessionId&&N(_.sessionId);return}if(!c||!_.sessionId){ye&&_.sessionId&&N(_.sessionId);return}try{await c(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:Y}),ye&&N(_.sessionId)}catch(We){const De=Nd(We);Sd(We)?console.warn(De?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",We instanceof Error?We.message:String(We)):console.error("Failed to switch CLI view mode:",We)}},[r,N,c]);return s.jsxs("div",{children:[s.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${T.accent} relative overflow-hidden`,children:[s.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",T.label," to Launch"]}),s.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:k?yt.length>0?yt.map(_=>{const Y=a.find(rt=>(rt.type||"").toLowerCase()===(_.type||"").toLowerCase()&&vt(rt.status)!=="stopped"),ye=_.running||!!Y,We=!!Y&&Y.cdpConnected,De=de.includes(_.type||_.id||""),Ke=S===(_.type||"");return s.jsxs("button",{onClick:()=>{if(We&&Y){const rt=Y.sessionId;rt?p(ls(rt),{state:{openRemoteForTabKey:rt}}):p("/dashboard",{state:{openRemoteForTabKey:Y.id}});return}De||D(rt=>rt===(_.type||"")?"":_.type||"")},disabled:!!y||De,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${We?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Ke?"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!==_.type?.4:1},children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:o(_.type)}),ye&&s.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${We?"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"}`})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.name||lt(_.type)}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${We?"text-green-400":De?"text-orange-400":Ke?"text-accent-primary":"text-text-muted"}`,children:We?"Open Session":De?"Starting...":Ke?"Configure":"Select"})]})]},_.type)}):s.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.",s.jsxs("button",{onClick:g,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:[s.jsx(Gm,{size:14})," Scan System"]})]}):B.length>0?B.map(_=>{const Y=S===_.type,ye=de.includes(_.type),De=!!a.find(Ke=>Ke.type===_.type&&vt(Ke.status)!=="stopped");return s.jsxs("button",{onClick:()=>D(Ke=>Ke===_.type?"":_.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${Y?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[s.jsxs("div",{className:"relative",children:[s.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:_.icon}),De&&s.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)]"})]}),s.jsxs("div",{className:"flex flex-col items-center",children:[s.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:_.displayName}),s.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${ye?"text-orange-400":Y?"text-accent-primary":"text-text-muted"}`,children:ye?"Starting...":Y?"Configure":"Select"})]})]},_.type)}):s.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.",s.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."})]})}),S&&(k?yt.find(_=>_.type===S):B.find(_=>_.type===S))&&s.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:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[s.jsx("span",{children:"Launch Settings"}),s.jsx("span",{className:"text-accent-primary font-bold",children:k?lt(S):L.get(S)||S})]}),s.jsx(Fw,{machine:t,selectedWorkspace:he,resolvedWorkspacePath:Be,customPath:ue,canBrowse:!!c,onWorkspaceChange:oe,onCustomPathChange:le,onOpenBrowseDialog:X}),!k&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!j&&e==="cli"&&s.jsx(lu,{busy:!!f||!!y||de.includes(S),savedSessionsLoading:ie,savedSessionsError:ke,savedSessionsLoaded:me,savedSessionsCount:V.length,selectedSession:Ee,onRefresh:()=>void G(S),onOpenHistory:()=>{S&&(fe(!0),iu({hasLoadedInitialResults:me,isLoading:ie})&&G(S))},onClearSelection:()=>K("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[j&&s.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),s.jsx("input",{type:"text",placeholder:"Leave empty for default",value:F,onChange:_=>P(_.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.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[s.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),s.jsx("input",{type:"text",placeholder:"Optional flags...",value:$,onChange:_=>E(_.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"}),I.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:I.map(_=>s.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:_,children:[s.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>E(_),children:_}),s.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:()=>Se(S,_),"aria-label":`Remove startup arguments: ${_}`,title:"Remove startup arguments",children:s.jsx(jt,{size:12})})]},_))})]})]})]}),s.jsx("div",{className:"flex justify-end mt-2",children:s.jsx("button",{onClick:Kt,disabled:!!f||!!y||de.includes(S),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:f===S||y===S?"⏳ Launching...":"▶ Launch"})})]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+de.filter(_=>!a.some(Y=>Y.type===_&&vt(Y.status)!=="stopped")).length,")"]}),a.length===0&&be.length===0?s.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 ",T.plural," running"]}):s.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[be.map(_=>s.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:s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(_)}),s.jsxs("div",{children:[s.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:k?lt(_):L.get(_)||_}),s.jsx("div",{className:"text-[11px] text-text-muted",children:f===_?"Launching process...":"Waiting for process and session to register..."})]})]}),s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold",style:{background:"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:"var(--status-warning)"},children:"starting"})]})},`pending:${_}`)),a.map(_=>{const Y=k?_:null,ye=!k&&!j?_:null,We=vt(_.status);return s.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center mb-2",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:"text-lg",children:o(_.type)}),s.jsxs("div",{children:[s.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[gt(_),(Y==null?void 0:Y.version)&&s.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",Y.version]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[s.jsx("span",{className:"truncate",children:_.workspace||"—"}),u&&_.git&&_.workspace?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:De=>{De.stopPropagation(),u(_.daemonId??r,_.workspace)},children:s.jsx(zs,{git:_.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(zs,{git:_.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(ye==null?void 0:ye.mode)&&s.jsx("span",{className:ye.mode==="chat"?"text-violet-400":"text-text-secondary",children:ye.mode==="chat"?"Chat view":"Terminal view"})]}),ye&&(ye.runtimeKey||ye.runtimeWriteOwner)&&s.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[ye.runtimeKey&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),s.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",ye.runtimeKey]}),s.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 De;(De=navigator.clipboard)==null||De.writeText(`adhdev attach ${ye.runtimeKey}`),v(ye.runtimeKey||null),window.setTimeout(()=>{v(Ke=>Ke===ye.runtimeKey?null:Ke)},1200)},children:C===ye.runtimeKey?"Copied":"Copy"})]}),ye.runtimeWriteOwner&&s.jsx("span",{style:{color:ye.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:ye.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Ow(ye.runtimeWriteOwner)})]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${We==="stopped"?"bg-red-500/[0.08] text-red-500":We==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:We}),k&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const De=_.sessionId;if(De){p(ls(De),{state:{openRemoteForTabKey:De}});return}p("/dashboard",{state:{openRemoteForTabKey:_.id}})},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-primary transition-colors cursor-pointer",title:"Open remote control",children:s.jsx(Rt,{size:13})}),s.jsx("button",{onClick:()=>{const De=_.workspace||"",{options:Ke,selectedKey:rt}=js({machine:t,currentWorkspacePath:De});Oe({title:bs("restart-ide",lt(_.type)),description:gs("restart-ide"),confirmLabel:Gs("restart-ide"),busyLabel:Vs("restart-ide"),workspaceOptions:Ke,selectedWorkspaceKey:rt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:lt(_.type)}]},async()=>{const At=Ke.find(ts=>ts.key===Ye.current),bt=(At==null?void 0:At.workspacePath)??"";if(bt&&bt!==De){await dt({type:_.type,workspacePath:bt});return}await x(_)})},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:s.jsx(Tr,{size:14})})]}),j&&s.jsx("button",{onClick:()=>{const De=_.sessionId;De&&N(De)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!_.sessionId,children:s.jsx(Zt,{size:14})}),ye&&We!=="stopped"&&s.jsxs(s.Fragment,{children:[ye.mode&&s.jsx(Ko,{mode:ye.mode,onChange:De=>void $e(ye,De,!1),compact:!0}),s.jsx("button",{onClick:()=>{const De=_.sessionId;De&&N(De)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!_.sessionId,children:ye.mode==="chat"?s.jsx(Zt,{size:14}):s.jsx(Rt,{size:13})})]}),We==="stopped"?s.jsx("button",{onClick:()=>{const De=_.workspace||"",Ke=k?lt(_.type):gt(_),{options:rt,selectedKey:At}=js({machine:t,currentWorkspacePath:De});Oe({title:bs("restart-stopped",Ke),description:gs("restart-stopped"),confirmLabel:Gs("restart-stopped"),busyLabel:Vs("restart-stopped"),workspaceOptions:rt,selectedWorkspaceKey:At,details:[{label:"Mode",value:T.label},{label:"Provider",value:Ke}]},async()=>{const bt=rt.find(ts=>ts.key===Ye.current);await dt({type:_.type,workspaceId:(bt==null?void 0:bt.workspaceId)??null,workspacePath:(bt==null?void 0:bt.workspacePath)??"",useHome:!(bt!=null&&bt.workspaceId)&&!(bt!=null&&bt.workspacePath)})})},disabled:de.includes(_.type),className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-green-500/20 text-green-400 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed",title:"Restart",children:de.includes(_.type)?"⏳":s.jsx(Mo,{size:14})}):s.jsx("button",{onClick:()=>ee(_),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:s.jsx(jt,{size:14})})]})]}),Y&&Y.aiAgents.length>0&&s.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:Y.aiAgents.map(De=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Mn(De.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[De.name," · ",vt(De.status)]},De.id))}),Y&&(Ue[Y.type]||[]).length>0&&c&&s.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[s.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),s.jsx("div",{className:"flex flex-wrap gap-2",children:(Ue[Y.type]||[]).map(De=>s.jsxs("button",{disabled:Ze===`${Y.type}.${De.type}`,onClick:async()=>{const Ke=`${Y.type}.${De.type}`;et(Ke);try{await c(r,"set_ide_extension",{ideType:Y.type,extensionType:De.type,enabled:!De.enabled}),Le(rt=>({...rt,[Y.type]:(rt[Y.type]||[]).map(At=>At.type===De.type?{...At,enabled:!At.enabled}:At)}))}catch(rt){console.error("Extension toggle failed:",rt)}finally{et(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 ${De.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${De.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),De.name,s.jsx("span",{className:"text-[9px] font-normal",children:De.enabled?"ON":"OFF"})]},De.type))})]})]},_.id)})]}),ve&&c&&s.jsx(Zn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:pe,directories:Ie,busy:_e,error:Me,confirmLabel:"Use this folder",onClose:()=>ce(!1),onNavigate:_=>{U(_)},onConfirm:_=>{le(_),oe("__custom__"),ce(!1)}}),Ge&&s.jsx(si,{title:Ge.title,description:Ge.description,details:Ge.details,workspaceOptions:Ge.workspaceOptions,selectedWorkspaceKey:tt,onWorkspaceChange:_=>{Ye.current=_,ct(_)},confirmLabel:Ge.confirmLabel,busyLabel:Ge.busyLabel,busy:mt,onConfirm:Re,onCancel:()=>{He.current=null,Xe(null)}}),ge&&se&&s.jsx(qo,{activeConv:se,ides:[],isCreatingChat:!1,isRefreshingHistory:ie,savedSessions:V,isSavedSessionsLoading:ie,isResumingSavedSessionId:Ne,savedHistoryFilters:we,missingWorkspaceResumePath:Be||null,onSavedHistoryFiltersChange:xe,onClose:()=>fe(!1),onNewChat:()=>{K(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{G(S)},onResumeSavedSession:_=>{if(!_.canResume||Ne)return;const Y=W(_);K(_.providerSessionId),re(_),Q(_.providerSessionId),fe(!1),dt({type:_.providerType,workspaceId:Y.workspaceId,workspacePath:Y.workspacePath,useHome:Y.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{Q(ye=>ye===_.providerSessionId?null:ye)})}})]})}const Yl=[{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 Hw({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:l,getIcon:c,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:p,onOpenGitDialog:b}){var g;const[w,x]=i.useState(d);i.useEffect(()=>{x(d)},[d]);const h=i.useMemo(()=>({ide:n.length,cli:a.length,acp:o.length}),[n.length,a.length,o.length]);return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),s.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),s.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[s.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Yl.map(y=>s.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${w===y.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>x(y.id),children:[s.jsx("span",{children:y.label}),s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${w===y.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:h[y.id]})]},y.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(g=Yl.find(y=>y.id===w))==null?void 0:g.helper})]}),w==="ide"&&s.jsx(za,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:c,actions:l,sendDaemonCommand:p,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b}),w==="cli"&&s.jsx(za,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:c,actions:l,sendDaemonCommand:p,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b}),w==="acp"&&s.jsx(za,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:c,actions:l,sendDaemonCommand:p,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:b})]})}function Kw({onNicknameSynced:e}={}){var le,de,Z,ve,ce,pe,ae,Ie,Ce,_e;const{id:t}=xm(),r=Ys(),n=jo(),{sendCommand:a}=kt(),o=Rr(),l=yd(),c=Xc(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(H=>H.id===t&&H.type==="adhdev-daemon"),p=d.some(H=>H.type==="adhdev-daemon"),b=t?(le=c.connectionRetryStatuses)==null?void 0:le[t]:void 0,w=!!(b!=null&&b.blocked),[x,h]=i.useState("workspace"),[g,y]=i.useState(null),f=i.useCallback((H,Me)=>{y({daemonId:H,workspace:Me})},[]),[A,C]=i.useState("ide"),v=i.useRef(null),[N,T]=i.useState(null),k=i.useRef("__home__"),[j,B]=i.useState("__home__"),[L,S]=i.useState(!1),D=i.useRef(null);i.useEffect(()=>{!t||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(t,{minFreshMs:3e4}).catch(()=>{})},[o,u,t]),i.useEffect(()=>{if(!t||!u||x!=="overview")return;const H=u.machine;(typeof(H==null?void 0:H.cpus)!="number"||typeof(H==null?void 0:H.totalMem)!="number"||typeof(H==null?void 0:H.arch)!="string"||typeof(H==null?void 0:H.release)!="string")&&l(t,{minFreshMs:3e4}).catch(()=>{})},[x,l,u,t]),wb(t&&x==="overview"?[t]:[],{enabled:x==="overview",intervalMs:hf});const $=()=>{if(p){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},E=Bv({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:D});i.useEffect(()=>ot.onToast(Me=>{c.setToasts(He=>{if(He.some(Ye=>Ye.message===Me.message&&Me.timestamp-Ye.timestamp<3e3))return He;const Xe={id:Me.id,message:Me.message,type:Me.type,timestamp:Me.timestamp,targetKey:Me.targetKey,actions:Me.actions};return[...He.slice(-4),Xe]});const Ae=Me.duration||5e3;setTimeout(()=>c.setToasts(He=>He.filter(Ge=>Ge.id!==Me.id)),Ae)}),[c]);const I=(u==null?void 0:u.availableProviders)||[],M={};for(const H of I)M[H.type]=H.icon;const F=H=>M[H]||"",P=u?{id:u.id,hostname:Sc(u,{fallbackId:u.id}),platform:((de=u.machine)==null?void 0:de.platform)||"unknown",arch:((Z=u.machine)==null?void 0:Z.arch)||"",cpus:((ve=u.machine)==null?void 0:ve.cpus)||0,totalMem:((ce=u.machine)==null?void 0:ce.totalMem)||0,freeMem:(pe=u.machine)==null?void 0:pe.freeMem,availableMem:(ae=u.machine)==null?void 0:ae.availableMem,loadavg:(Ie=u.machine)==null?void 0:Ie.loadavg,uptime:(Ce=u.machine)==null?void 0:Ce.uptime,release:((_e=u.machine)==null?void 0:_e.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,R=d.filter(H=>H.daemonId===t&&H.type!=="adhdev-daemon").filter(H=>!Mr(H)&&!$s(H)).map(H=>({id:H.id,sessionId:H.sessionId,type:H.type,version:H.version||"",instanceId:H.instanceId||"",status:H.status,workspace:H.workspace||null,terminals:H.terminals||0,aiAgents:ah(H.aiAgents||(H.agents||[]).map(Me=>({id:Me.name,name:Me.name,status:Me.status,version:Me.version}))),activeChat:H.activeChat||null,chats:H.chats||[],childSessions:H.childSessions||[],cdpConnected:H.cdpConnected||!1,daemonId:t,lastMessageAt:H.lastMessageAt})),K=d.filter(H=>H.daemonId===t&&Mr(H)).map(H=>({id:H.id,sessionId:H.sessionId,type:H.type,cliName:H.cliName||H.type,status:H.status,workspace:H.workspace||"",activeChat:H.activeChat||null,providerSessionId:H.providerSessionId,mode:H.mode,runtimeKey:H.runtimeKey,runtimeDisplayName:H.runtimeDisplayName,runtimeWorkspaceLabel:H.runtimeWorkspaceLabel,runtimeWriteOwner:H.runtimeWriteOwner||null,runtimeAttachedClients:H.runtimeAttachedClients||[],daemonId:t,lastMessageAt:H.lastMessageAt})),V=d.filter(H=>H.daemonId===t&&$s(H)).map(H=>({id:H.id,sessionId:H.sessionId,type:H.type,acpName:H.cliName||H.type,status:H.status,workspace:H.workspace||"",activeChat:H.activeChat||null,providerSessionId:H.providerSessionId,daemonId:t,lastMessageAt:H.lastMessageAt})),te=u?Lt(u,{fallbackId:t}):"",ie="workspace",J=n.state,me=J==null?void 0:J.initialMachineTab,je=J==null?void 0:J.initialWorkspaceCategory,ke=J==null?void 0:J.initialWorkspaceId,q=J==null?void 0:J.initialWorkspacePath,ge=me==="ides"||me==="clis"||me==="acps"?"workspace":me||ie,fe=me==="ides"?"ide":me==="clis"?"cli":me==="acps"?"acp":je,we=[...R.map(H=>{var Me;return{id:`ide:${H.type}:${H.workspace||""}`,label:((Me=H.activeChat)==null?void 0:Me.title)||H.type,kind:"ide",providerType:H.type,subtitle:H.workspace||void 0,workspace:H.workspace||void 0,lastLaunchedAt:H.lastMessageAt||0}}),...K.map(H=>{var Me;return{id:`cli:${H.type}:${H.workspace||""}`,label:((Me=H.activeChat)==null?void 0:Me.title)||H.cliName,kind:"cli",providerType:H.type,providerSessionId:H.providerSessionId,subtitle:H.workspace||void 0,workspace:H.workspace||void 0,lastLaunchedAt:H.lastMessageAt||0}}),...V.map(H=>{var Me;return{id:`acp:${H.type}:${H.workspace||""}`,label:((Me=H.activeChat)==null?void 0:Me.title)||H.acpName,kind:"acp",providerType:H.type,providerSessionId:H.providerSessionId,subtitle:Ns(H.summaryMetadata)||H.workspace||void 0,workspace:H.workspace||void 0,lastLaunchedAt:H.lastMessageAt||0}})].sort((H,Me)=>(Me.lastLaunchedAt||0)-(H.lastLaunchedAt||0)),xe=((u==null?void 0:u.recentLaunches)||[]).length>0?((u==null?void 0:u.recentLaunches)||[]).map(H=>({id:H.id,label:H.title||H.providerName||H.providerType,kind:H.kind,providerType:H.providerType,providerSessionId:H.providerSessionId,subtitle:Ns(H.summaryMetadata)||H.workspace||void 0,workspace:H.workspace,summaryMetadata:H.summaryMetadata,lastLaunchedAt:H.lastLaunchedAt})):we,Ne=i.useMemo(()=>{var Me;const H=((Me=c.connectionStates)==null?void 0:Me[t||""])||void 0;return d.filter(Ae=>Ae.daemonId===t&&Ae.type!=="adhdev-daemon").flatMap(Ae=>Yo(Ae,{connectionStates:t&&H?{[t]:H}:void 0,defaultConnectionState:H})).filter(Ae=>!(Ae.transport==="pty"&&Ae.mode==="terminal")).sort((Ae,He)=>ho(He)-ho(Ae))},[d,c.connectionStates,t]),Q=i.useCallback(H=>{const Me=Od(H);Me&&r(ls(Me))},[r]),he=i.useCallback(()=>{v.current&&(S(!0),v.current().finally(()=>{v.current=null,S(!1),T(null)}))},[]),oe=i.useCallback(H=>{if(!P)return;const{options:Me,selectedKey:Ae}=js({machine:P,currentWorkspacePath:H.workspace}),He=async()=>{C(H.kind),h("workspace")};v.current=async()=>{const Ge=Me.find(tt=>tt.key===k.current),Xe=(Ge==null?void 0:Ge.workspacePath)??null,Ye=(Ge==null?void 0:Ge.workspaceId)??null;if(H.kind==="ide"&&H.providerType){await E.handleLaunchIde(H.providerType,Xe?{workspace:Xe}:void 0);return}if((H.kind==="cli"||H.kind==="acp")&&H.providerType){await E.runLaunchCliCore({cliType:H.providerType,dir:Ye?void 0:Xe||"",workspaceId:Ye||void 0,model:H.kind==="acp"&&Cc(H.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:H.providerSessionId});return}await He()},k.current=Ae,B(Ae),T({title:H.kind==="ide"?bs("restart-ide",H.label):H.providerSessionId?Go(H.label):bs("start-fresh",H.label),description:H.kind==="ide"?gs("restart-ide"):H.providerSessionId?Vo():gs("start-fresh"),confirmLabel:H.kind==="ide"?Gs("restart-ide"):H.providerSessionId?Rn(!0):Gs("start-fresh"),busyLabel:H.kind==="ide"?Vs("restart-ide"):H.providerSessionId?Uo(!0):Vs("start-fresh"),workspaceOptions:Me,details:[{label:"Mode",value:H.kind.toUpperCase()},...H.providerType?[{label:"Provider",value:H.providerType}]:[]]})},[E,P]);if(i.useEffect(()=>{h(ge)},[ie,ge,t]),i.useEffect(()=>{fe&&C(fe)},[fe,t]),!P)return m?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:$,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const ue=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Rt,{size:14})," Workspace"]}),count:R.length+K.length+V.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(os,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Wn,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qm,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Um,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.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:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:$,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:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[E.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:E.nicknameInput,onChange:H=>E.setNicknameInput(H.target.value),onKeyDown:H=>{H.key==="Enter"&&E.handleSaveNickname(),H.key==="Escape"&&E.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:E.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>E.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{E.setEditingNickname(!0),E.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:te}),w?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&t&&s.jsx("button",{onClick:()=>c.retryConnection(t),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"})]}):s.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"})]}),s.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:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[P.platform," · ",P.arch]}),s.jsxs("span",{children:[P.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),P.p2p.available&&s.jsxs("span",{children:["P2P ",P.p2p.state==="connected"?"connected":P.p2p.state]}),P.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:P.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ue.map(H=>s.jsxs("button",{onClick:()=>h(H.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${x===H.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[H.label,H.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${x===H.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:H.count})]},H.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[x==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(Bw,{machineEntry:u,providers:I,recentLaunches:xe,currentConversations:Ne,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",Dd(u))}catch{}},onOpenRecent:oe,onOpenConversation:Q}),s.jsx(Hw,{machine:P,machineId:t,providers:I,ideSessions:R,cliSessions:K,acpSessions:V,actions:E,getIcon:F,initialCategory:A,initialWorkspaceId:ke,initialWorkspacePath:q,sendDaemonCommand:a,onOpenGitDialog:f})]}),x==="providers"&&s.jsx(qv,{machineId:t,providers:I,sendDaemonCommand:a}),x==="overview"&&s.jsx(Ov,{machineId:t,machine:P,ideSessions:R,cliSessions:K,acpSessions:V,actions:E,sendDaemonCommand:a}),x==="session-host"&&s.jsx(Ew,{machineId:t,cliSessions:K,sendDaemonCommand:a}),x==="logs"&&s.jsx(Aw,{machineId:t,sendDaemonCommand:a})]})})}),E.launchPick&&P&&s.jsx($w,{machine:P,launchPick:E.launchPick,actions:E}),N&&s.jsx(si,{title:N.title,description:N.description,details:N.details,workspaceOptions:N.workspaceOptions,selectedWorkspaceKey:j,onWorkspaceChange:H=>{k.current=H,B(H)},confirmLabel:N.confirmLabel,busyLabel:N.busyLabel,busy:L,onConfirm:he,onCancel:()=>{v.current=null,T(null)}}),g&&s.jsx(Cu,{daemonId:g.daemonId,workspace:g.workspace,onClose:()=>y(null)}),s.jsx(od,{toasts:c.toasts||[],onDismiss:H=>c.setToasts(Me=>Me.filter(Ae=>Ae.id!==H)),onClickToast:H=>{H.targetKey&&r(ls(H.targetKey))}}),s.jsx("style",{children:`
|
|
93
|
+
@keyframes toast-in {
|
|
94
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
95
|
+
to { opacity: 1; transform: translateX(0); }
|
|
96
|
+
}
|
|
97
|
+
`})]})}const cn=[{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."}],Uw={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function wn(e){var n;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function zw(e){const t=wn(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function Gw(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function Vw(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${r}`}function qw(e,t){return[...Array.isArray(t==null?void 0:t.cliSessions)?t.cliSessions:[],...Array.isArray(t==null?void 0:t.acpSessions)?t.acpSessions:[],...Array.isArray(t==null?void 0:t.sessions)?t.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 Ga(e){return{...Uw,...(e==null?void 0:e.policy)||{}}}function Yw({meshId:e,availableCliAgents:t}){const r=t.find(a=>{const o=a.id.toLowerCase(),l=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||l.includes("hermes")}),n=Bd(r==null?void 0:r.meshCoordinator,{meshId:e});return n?s.jsx(wt,{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:s.jsx(cu,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function Xw(){var Ye,tt,ct,mt,pt;const{sendCommand:e}=kt(),{ides:t}=cs(),r=t.find(O=>O.daemonMode||O.type==="adhdev-daemon"),n=(r==null?void 0:r.id)||"",a=[];let o=[];if(r){const O=r.availableProviders||[];o=Dx(O);for(const be of O)be.category==="cli"&&a.push({id:be.type||be.id,name:be.displayName||be.name||be.type,meshCoordinator:be.meshCoordinator})}const[l,c]=i.useState([]),[d,m]=i.useState(null),[u,p]=i.useState(!0),[b,w]=i.useState(null),[x,h]=i.useState(!1),[g,y]=i.useState(null),[f,A]=i.useState({}),[C,v]=i.useState([]),[N,T]=i.useState(null),[k,j]=i.useState(null),[B,L]=i.useState(!1),[S,D]=i.useState(null),[$,E]=i.useState(null),[I,M]=i.useState(!1),[F,P]=i.useState(!1),[R,K]=i.useState(!1),[V,te]=i.useState(""),[ie,J]=i.useState(""),[me,je]=i.useState(!1),[ke,q]=i.useState(""),[ge,fe]=i.useState(""),[we,xe]=i.useState(!1),[Ne,Q]=i.useState(""),[he,oe]=i.useState([]),ue=l.find(O=>O.id===d)||null;i.useEffect(()=>{A(Object.fromEntries(((ue==null?void 0:ue.nodes)||[]).map(O=>[O.id,wn(O)])))},[ue]),i.useEffect(()=>{const O=Ex(o);we&&he.length===0&&O.length>0&&oe(O)},[we,o,he.length]),i.useEffect(()=>{const O=new Set(((ue==null?void 0:ue.nodes)||[]).map(be=>be.id));N&&!O.has(N)&&T(null)},[ue,N]);const le=i.useCallback(async()=>{if(n){p(!0);try{const O=await e(n,"list_meshes");O!=null&&O.success?(c(O.meshes||[]),w(null)):w((O==null?void 0:O.error)||"Failed to load meshes")}catch(O){w((O==null?void 0:O.message)||"Failed to load meshes")}finally{p(!1)}}},[n,e]),de=i.useCallback(async O=>{if(!n||!O){v([]);return}try{const be=await e(n,"get_mesh_queue",{meshId:O});be!=null&&be.success?v(Array.isArray(be.queue)?be.queue:[]):v([])}catch{v([])}},[n,e]),Z=i.useCallback(async O=>{var be;if(!n||!O){E(null),te(""),J("");return}M(!0);try{const Te=await e(n,"get_mesh_host_pairing",{meshId:O});Te!=null&&Te.success?(E(Te),te(Te.hostAddress||((be=Te.meshHost)==null?void 0:be.hostAddress)||"")):E({success:!1,error:(Te==null?void 0:Te.error)||"Failed to load Mesh Host pairing"}),J("")}catch(Te){E({success:!1,error:(Te==null?void 0:Te.message)||"Failed to load Mesh Host pairing"}),J("")}finally{M(!1)}},[n,e]);i.useEffect(()=>{le()},[le]),i.useEffect(()=>{de(d)},[de,d]),i.useEffect(()=>{Z(d)},[Z,d]);async function ve(){if(!(!n||!d))try{L(!0),D(null);const O=await e(n,"mesh_status",{meshId:d});if((O==null?void 0:O.success)===!1){j(null),D((O==null?void 0:O.error)||"mesh_status failed");return}const be=gu(O);be?j(be):(j(null),D("mesh_status returned an unexpected payload."))}catch(O){j(null),D((O==null?void 0:O.message)||"Failed to load mesh graph")}finally{L(!1)}}i.useEffect(()=>{d&&(j(null),D(null),ve())},[d]);async function ce(){var O;if(!(!n||!ke.trim()))try{const be=await e(n,"create_mesh",{name:ke.trim(),repoIdentity:ge.trim()||void 0});be!=null&&be.success?(je(!1),q(""),fe(""),await le(),m(((O=be.mesh)==null?void 0:O.id)||null)):w((be==null?void 0:be.error)||"Create failed")}catch(be){w((be==null?void 0:be.message)||"Create failed")}}async function pe(O){if(!(!n||!confirm("Delete this mesh?")))try{await e(n,"delete_mesh",{meshId:O}),m(null),await le()}catch(be){w((be==null?void 0:be.message)||"Delete failed")}}async function ae(){if(!(!n||!d||!Ne.trim()))try{const O=await e(n,"add_mesh_node",{meshId:d,workspace:Ne.trim(),providerPriority:lo(he,o)});O!=null&&O.success?(xe(!1),Q(""),oe([]),await le(),await de(d)):w((O==null?void 0:O.error)||"Add node failed")}catch(O){w((O==null?void 0:O.message)||"Add node failed")}}async function Ie(O){var Be;if(!n||!d)return;const be=Ga(ue),Te=((Be=cn.find(qe=>qe.value===be.sessionCleanupOnNodeRemove))==null?void 0:Be.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
|
|
98
|
+
|
|
99
|
+
Node removal cleanup policy: ${Te}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:O}),N===O&&T(null),await le(),await de(d)}catch(qe){w((qe==null?void 0:qe.message)||"Remove node failed")}}async function Ce(O){if(!n||!d)return;const be={...Ga(ue),...O};try{h(!0),w(null);const Te=await e(n,"update_mesh",{meshId:d,policy:be});if((Te==null?void 0:Te.success)===!1){w(Te.error||"Policy update failed");return}await le()}catch(Te){w((Te==null?void 0:Te.message)||"Policy update failed")}finally{h(!1)}}async function _e(){var O;if(!(!n||!d||!V.trim()||!ie.trim())){P(!0);try{const be=await e(n,"configure_mesh_host_pairing",{meshId:d,hostAddress:V.trim(),token:ie.trim()});be!=null&&be.success?(E(be),te(be.hostAddress||((O=be.meshHost)==null?void 0:O.hostAddress)||V.trim()),await le()):E({success:!1,error:(be==null?void 0:be.error)||"Failed to save Mesh Host pairing"})}catch(be){E({success:!1,error:(be==null?void 0:be.message)||"Failed to save Mesh Host pairing"})}finally{P(!1)}}}async function H(){if(!(!n||!d||!ie.trim())){K(!0);try{const O=await e(n,"join_mesh_host_pairing",{meshId:d,token:ie.trim()});O!=null&&O.success?(E(O),J(""),await le(),await Z(d),await ve()):E({success:!1,meshHost:O==null?void 0:O.meshHost,manualPairing:O==null?void 0:O.manualPairing,error:(O==null?void 0:O.error)||"Failed to apply Mesh Host join"})}catch(O){E({success:!1,error:(O==null?void 0:O.message)||"Failed to apply Mesh Host join"})}finally{K(!1)}}}async function Me(O){if(!n||!d)return;const be=lo(f[O.id]||wn(O),o),Te={...O.policy||{}};delete Te.provider_priority,be.length?Te.providerPriority=be:delete Te.providerPriority;try{y(O.id),w(null);const Be=await e(n,"update_mesh_node",{meshId:d,nodeId:O.id,policy:Te});if((Be==null?void 0:Be.success)===!1){w(Be.error||"Node policy update failed");return}await le()}catch(Be){w((Be==null?void 0:Be.message)||"Node policy update failed")}finally{y(null)}}if(!n)return s.jsx(wr,{icon:s.jsx(ns,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!ue)return s.jsxs(wr,{icon:s.jsx(ns,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>je(!0),children:"+ Create Mesh"}),children:[b&&s.jsx(Es,{variant:"error",className:"mb-4",children:b}),me&&s.jsx(wt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Tt,{label:"Name",children:s.jsx(cr,{value:ke,onChange:O=>q(O.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Tt,{label:"Repo Identity (optional)",children:s.jsx(cr,{value:ge,onChange:O=>fe(O.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:ce,disabled:!ke.trim(),children:"Create"}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>je(!1),children:"Cancel"})]})]})}),u?s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):l.length===0?s.jsx(Pn,{icon:s.jsx(ns,{}),title:"No meshes",description:"Create a mesh to get started."}):s.jsx("div",{className:"flex flex-col gap-2",children:l.map(O=>s.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:()=>m(O.id),children:[s.jsx("div",{className:"font-semibold text-sm",children:O.name}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:O.repoIdentity||"No repo identity"}),s.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[O.nodes.length," node(s)"]})]},O.id))})]});const Ae=Ga(ue),He=($==null?void 0:$.meshHost)||ue.meshHost||{},Ge=((Ye=$==null?void 0:$.manualPairing)==null?void 0:Ye.status)||((tt=He.pairing)==null?void 0:tt.status)||"not_configured",Xe=((ct=$==null?void 0:$.manualPairing)==null?void 0:ct.description)||"Manual address/token config is saved locally; Apply join sends the token once to the Mesh Host command endpoint. P2P runtime signaling remains outside this slice.";return s.jsxs(wr,{icon:s.jsx(ns,{}),title:ue.name,subtitle:ue.repoIdentity||"Repo Mesh",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>m(null),children:"← Back"}),s.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>pe(ue.id),children:"Delete"})]}),children:[b&&s.jsx(Es,{variant:"error",className:"mb-4",children:b}),s.jsx(wt,{title:"Mesh Host pairing",description:"Standalone manual pairing. Save a Mesh Host address/token, apply the join to the host command endpoint, then check persisted status.",children:s.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(280px,420px)]",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-4 text-sm",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"text-text-muted",children:"Local role"}),s.jsx("span",{className:"rounded-full border border-accent-primary/25 bg-accent-primary/10 px-2 py-0.5 text-xs font-semibold text-accent-primary",children:He.role||"host"}),s.jsx("span",{className:"text-text-muted",children:"Pairing"}),s.jsx("span",{className:"rounded-full border border-border-subtle px-2 py-0.5 text-xs font-mono text-text-primary",children:I?"loading":Ge})]}),s.jsxs("div",{className:"mt-3 grid gap-2 text-xs text-text-muted",children:[s.jsxs("div",{children:["Host address: ",s.jsx("code",{className:"text-text-primary",children:He.hostAddress||"not configured"})]}),s.jsxs("div",{children:["Token id: ",s.jsx("code",{className:"text-text-primary",children:((mt=He.pairing)==null?void 0:mt.tokenId)||"not configured"})]}),s.jsxs("div",{children:["Can own coordinator: ",s.jsx("code",{className:"text-text-primary",children:String(He.canOwnCoordinator??He.role!=="member")})]}),s.jsxs("div",{children:["Can own queue: ",s.jsx("code",{className:"text-text-primary",children:String(He.canOwnQueue??He.role!=="member")})]})]}),s.jsx("p",{className:"mt-3 text-xs leading-relaxed text-text-secondary",children:Xe}),($==null?void 0:$.error)&&s.jsx("div",{className:"mt-3 rounded-lg border border-red-500/25 bg-red-500/10 px-3 py-2 text-xs text-red-300",children:$.error})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-panel p-4",children:[s.jsx(Tt,{label:"Mesh Host address",hint:"Example: http://127.0.0.1:3847 or a reachable HTTPS/WSS host endpoint.",children:s.jsx(cr,{value:V,onChange:O=>te(O.target.value),placeholder:"http://127.0.0.1:3847",disabled:F||R})}),s.jsx(Tt,{label:"Pairing token",hint:"The raw token is used once to derive a local token id; it is not displayed after save.",children:s.jsx(cr,{value:ie,onChange:O=>J(O.target.value),placeholder:"paste Mesh Host pairing token",type:"password",disabled:F||R})}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:_e,disabled:F||R||!V.trim()||!ie.trim(),children:F?"Saving...":"Save manual pairing"}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:H,disabled:R||F||!ie.trim(),children:R?"Applying...":"Apply join"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>Z(d),disabled:I||F||R,children:I?"Checking...":"Check saved config"})]})]})]})}),s.jsxs(wt,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[s.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[s.jsx(Tt,{label:"Checkpoint before task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ae.requirePreTaskCheckpoint?"yes":"no",onChange:O=>Ce({requirePreTaskCheckpoint:O.target.value==="yes"}),disabled:x,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(Tt,{label:"Checkpoint after task",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ae.requirePostTaskCheckpoint?"yes":"no",onChange:O=>Ce({requirePostTaskCheckpoint:O.target.value==="yes"}),disabled:x,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(Tt,{label:"Push approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ae.requireApprovalForPush?"required":"not_required",onChange:O=>Ce({requireApprovalForPush:O.target.value==="required"}),disabled:x,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Tt,{label:"Submodule main auto-publish",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ae.allowAutoPublishSubmoduleMainCommits?"enabled":"disabled",onChange:O=>Ce({allowAutoPublishSubmoduleMainCommits:O.target.value==="enabled"}),disabled:x,children:[s.jsx("option",{value:"disabled",children:"Require explicit approval"}),s.jsx("option",{value:"enabled",children:"Allow Refinery non-force publish"})]})}),s.jsx(Tt,{label:"Destructive git approval",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ae.requireApprovalForDestructiveGit?"required":"not_required",onChange:O=>Ce({requireApprovalForDestructiveGit:O.target.value==="required"}),disabled:x,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(Tt,{label:"Dirty workspace behavior",children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ae.dirtyWorkspaceBehavior||"warn",onChange:O=>Ce({dirtyWorkspaceBehavior:O.target.value}),disabled:x,children:[s.jsx("option",{value:"warn",children:"Warn and continue"}),s.jsx("option",{value:"block",children:"Block task"}),s.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),s.jsx(Tt,{label:"Max parallel tasks",children:s.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(Ae.maxParallelTasks??2),onChange:O=>Ce({maxParallelTasks:Number(O.target.value)}),disabled:x,children:[1,2,3,4,5,6,7,8].map(O=>s.jsx("option",{value:O,children:O},O))})})]}),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Tt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ae.sessionCleanupOnNodeRemove||"preserve",onChange:O=>Ce({sessionCleanupOnNodeRemove:O.target.value}),disabled:x,children:cn.map(O=>s.jsx("option",{value:O.value,children:O.label},O.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((pt=cn.find(O=>O.value===Ae.sessionCleanupOnNodeRemove))==null?void 0:pt.description)||cn[0].description})]}),x&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),s.jsxs(wt,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:ve,disabled:B,children:B?"Loading...":"Refresh Graph"})]}),S&&s.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:S}),k?s.jsx(Su,{status:k,emptyMessage:"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon.",daemonId:n,sendDaemonCommand:e}):s.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:B?"Loading graph...":"Refresh the graph to inspect queue activity, sessions, node drift, and mesh topology from this standalone daemon."})]}),s.jsxs(wt,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[s.jsx("div",{className:"flex justify-end mb-3",children:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>xe(!0),children:"+ Add Node"})}),we&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),s.jsx("button",{onClick:()=>xe(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(jt,{size:16})})]}),s.jsx(Tt,{label:"Workspace Path",children:s.jsx(cr,{value:Ne,onChange:O=>Q(O.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(Tt,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:s.jsx(ol,{value:he,availableProviders:o,onChange:oe})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:ae,disabled:!Ne.trim(),className:"btn btn-primary btn-sm",children:"Add"}),s.jsx("button",{onClick:()=>xe(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),ue.nodes.length===0?s.jsx(Pn,{icon:s.jsx(Ss,{}),title:"No nodes",description:"Add a workspace to this mesh."}):s.jsx("div",{className:"flex flex-col gap-2",children:ue.nodes.map(O=>{const be=wn(O),Te=zw(O),Be=Gw(O,C),qe=qw(O,r),z=N===O.id;return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${z?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>T(z?null:O.id),onKeyDown:U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),T(z?null:O.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("div",{className:"text-sm font-medium",children:O.workspace.split("/").pop()}),Be.length>0&&s.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:[Be.length," active task",Be.length===1?"":"s"]})]}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:O.workspace}),s.jsx("div",{className:"mt-3 max-w-2xl",onClick:U=>U.stopPropagation(),children:s.jsxs(Tt,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[s.jsx(ol,{value:f[O.id]??be,availableProviders:o,onChange:U=>A(X=>({...X,[O.id]:U})),disabled:g===O.id,saveButton:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:U=>{U.stopPropagation(),Me(O)},disabled:g===O.id,children:g===O.id?"Saving...":"Save policy"})}),s.jsxs("div",{className:"mt-2 text-[12px]",children:[s.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),s.jsx("span",{className:Te.configured?"text-text-primary font-mono":"text-amber-400",children:Te.label}),Te.launchBlockedMessage&&s.jsxs("span",{className:"ml-2 text-amber-400",children:["(",Te.launchBlockedMessage,")"]})]})]})})]}),s.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:U=>{U.stopPropagation(),Ie(O.id)},children:s.jsx(jt,{size:14})})]}),z&&s.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",s.jsx("span",{className:"font-mono",children:O.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",s.jsx("span",{className:Te.configured?"text-green-400":"text-amber-400",children:Te.configured?"yes":"provider priority not configured"})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",s.jsx("span",{className:"font-mono",children:O.repoRoot||O.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",qe.length]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",Be.length>0||qe.length>0?"active":"idle/unknown"]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),Be.length===0?s.jsx("div",{children:"No active assigned queue task for this node."}):s.jsx("ul",{className:"m-0 pl-4",children:Be.map(U=>s.jsx("li",{className:"font-mono",children:Vw(U)},U.id))})]}),qe.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),s.jsx("ul",{className:"m-0 pl-4",children:qe.map(U=>s.jsxs("li",{className:"font-mono",children:[U.provider," / ",U.status," / ",U.id]},U.id))})]})]})]},O.id)})})]}),s.jsx(Yw,{meshId:ue.id,availableCliAgents:a})]})}function xi(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Jw(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=xi();return r&&!t.searchParams.has("token")&&t.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Gt(e,t){return await fetch(Jw(e),{credentials:"same-origin",...t})}function Au(){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 Qw{constructor(){Qe(this,"adapters",new Map);Qe(this,"states",new Map);Qe(this,"runtimeListeners",new Map);Qe(this,"screenshotCallbacks",new Map);Qe(this,"statusCallbacks",new Set);Qe(this,"stateChangeCallbacks",new Set);Qe(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(t,r){this.adapters.set(t,r),this.states.set(t,r.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,r){this.states.set(t,r);const n=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(n,r))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const r=this.resolveDaemonId(t);return r?this.adapters.get(r):void 0}getState(t){const r=this.resolveDaemonId(t);return r&&this.states.get(r)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,r){return!1}sendPtyInput(t,r,n){return this.ptyInputSender?this.ptyInputSender(t,r,n):!1}onScreenshot(t,r){return this.screenshotCallbacks.set(t,r),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,r){this.screenshotCallbacks.forEach(n=>n(t,r))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,r){this.statusCallbacks.forEach(n=>n(t,r))}emitRuntimeSnapshot(t,r,n=0,a=!1,o,l){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:n,text:r,truncated:a,cols:o,rows:l})}emitSessionOutput(t,r,n){!t||typeof r!="string"||!r||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(t,r){const n=this.runtimeListeners.get(t)||new Set;return n.add(r),this.runtimeListeners.set(t,n),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,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 Gt(`${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(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const zt=new Qw;function Zw(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=xi();return r?`${t}?token=${encodeURIComponent(r)}`:t}const dn=Zw(),Xl=3e3,ej=3e4;let Ft=null,tj=0;const Fn=new Map;let ms=null,Sr=null;function Jl(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function pr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function sj(e){return e==="connected"?"connected":e}async function jn(e,t,r){const n=dd(e,r||{}),a=Ft;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++tj}_${Date.now()}`;return new Promise((l,c)=>{const d=setTimeout(()=>{Fn.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);Fn.set(o,{resolve:m=>{clearTimeout(d),l(m)},reject:m=>{clearTimeout(d),c(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function yo(e,t){const r=Ft;if(!r||r.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(t)),!0}catch{return!1}}function Tu(e,t,r){const n=Ft;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=dd(e,{sessionId:t,targetSessionId:t,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}zt.registerPtyInputSender(Tu);class rj{constructor(t){Qe(this,"daemonId");Qe(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Ft==null?void 0:Ft.readyState)===WebSocket.OPEN}get connectionState(){return(Ft==null?void 0:Ft.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return jn(this.daemonId,t,r)}async sendInput(t,r){return jn(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,ms&&(clearInterval(ms),ms=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await jn(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());zt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ms=setInterval(r,2e3)}stopScreenshots(t){ms&&(clearInterval(ms),ms=null)}}let Et=null;function nj(e){return(!Et||Et.daemonId!==e)&&(Et=new rj(e)),Et}function aj({children:e}){const t=i.useRef(Cr()),r=Cr();t.current=r;const{setUserName:n}=cs(),a=i.useRef(n);a.current=n;const o=i.useRef(null),l=i.useRef(null),[,c]=i.useState("disconnected"),d=i.useCallback((h,g)=>{c(h),Sr==null||Sr(h,g)},[]),m=i.useRef(null),u=i.useRef(),p=i.useRef(Xl),b=i.useRef(!0),w=i.useRef(!1),x=i.useRef("initial_connect");return i.useEffect(()=>{b.current=!0,w.current=!1;function h(){var f,A;if(!b.current||((f=m.current)==null?void 0:f.readyState)===WebSocket.OPEN||((A=m.current)==null?void 0:A.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${dn}...`),pr("connect_attempt",{url:dn,reason:x.current,delayMs:p.current});let y;try{y=new WebSocket(dn)}catch(C){console.error("[Standalone WS] Failed to create WebSocket:",C),g();return}m.current=y,y.onopen=()=>{if(!b.current){y.close();return}d("connected"),p.current=Xl,pr("open",{url:dn,reason:x.current}),Qt.resubscribeAll({sendData:yo}),console.log("[Standalone WS] Connected")},Ft=y,y.onmessage=C=>{var v,N;try{const T=JSON.parse(C.data);if((T.type==="command_result"||T.type==="error")&&T.requestId){const k=Fn.get(T.requestId);k&&(Fn.delete(T.requestId),T.type==="error"?k.reject(new Error(((v=T.data)==null?void 0:v.message)||"Command failed")):k.resolve(T.data));return}if(T.type==="session_output"){const k=T.sessionId||T.cliId||T.cliType;k&&zt.emitSessionOutput(k,typeof T.data=="string"?T.data:"",typeof T.seq=="number"?T.seq:void 0);return}if(T.type==="runtime_snapshot"){zt.emitRuntimeSnapshot(T.sessionId,typeof T.text=="string"?T.text:"",typeof T.seq=="number"?T.seq:0,!!T.truncated,typeof T.cols=="number"?T.cols:void 0,typeof T.rows=="number"?T.rows:void 0);return}if(T.type==="topic_update"){const k=T.update;k&&Qt.publish(k);return}if(T.type==="status"||T.type==="initial_state"){const k=T.data;if(!k)return;const{injectEntries:j,markLoaded:B,getIdes:L}=t.current,S=k.instanceId||"standalone",D=L().find(I=>I.id===S),$=nj(S);zt.register(S,$),zt.setState(S,"connected"),d("connected",S),zt.emitStatus(S,k);const E=Ln(k,{daemonId:S,existingDaemon:D,existingEntries:L()});Jl("ws_status",{type:T.type,daemonId:S,sessions:(k.sessions||[]).map(I=>({id:I.id,parentId:I.parentId,providerType:I.providerType,kind:I.kind,transport:I.transport,unread:I.unread,inboxBucket:I.inboxBucket,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,title:I.title})),recentLaunches:(k.recentLaunches||[]).map(I=>({id:I.id,providerType:I.providerType,kind:I.kind,workspace:I.workspace,lastLaunchedAt:I.lastLaunchedAt}))}),Jl("entries",{daemonId:S,entries:E.filter(I=>I.type!=="adhdev-daemon").map(I=>({id:I.id,type:I.type,unread:I.unread,inboxBucket:I.inboxBucket,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,sessionId:I.sessionId}))}),E.length>0&&j(E,{authoritativeDaemonIds:[S]}),B(),l.current!==S&&((N=o.current)==null||N.call(o),l.current=S,o.current=Qt.subscribe({sendData:yo},S,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${S}`,params:{includeSessions:!0}},I=>{if(I.topic!=="daemon.metadata")return;const M=t.current.getIdes(),F=M.find(R=>R.id===S),P=Ln(I.status,{daemonId:S,existingDaemon:F,existingEntries:M,timestamp:I.timestamp});P.length>0&&t.current.injectEntries(P,{authoritativeDaemonIds:[S]}),I.userName&&a.current&&a.current(I.userName)}))}}catch(T){console.error("[Standalone WS] Parse error:",T)}},y.onclose=C=>{b.current&&(Et==null||Et.stopScreenshots(),Et&&zt.setState(Et.daemonId,"disconnected"),d("disconnected"),m.current=null,x.current=`close:${C.code}${C.wasClean?":clean":":unclean"}`,pr("close",{code:C.code,reason:C.reason||"",wasClean:C.wasClean}),g())},y.onerror=C=>{w.current||!b.current||(x.current="error",pr("error",{message:C instanceof Event?"event":String(C),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",C))}}function g(){if(!b.current)return;clearTimeout(u.current);const y=p.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),pr("schedule_reconnect",{reason:x.current,delayMs:y}),u.current=setTimeout(()=>{p.current=Math.min(p.current*1.5,ej),h()},y)}return h(),()=>{var y;b.current=!1,w.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,Ft=null),Et&&(Et.stopScreenshots(),zt.unregister(Et.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function oj({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(Sr=(l,c)=>{r(l),c&&a(c)},()=>{Sr=null}),[]);const o=i.useMemo(()=>{const l=t==="connected",c=sj(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:l,connectionStates:d}},[t,n]);return s.jsx(Rm,{connectionOverrides:o,children:s.jsx(aj,{children:e})})}const _u="adhdev_standalone_font_preferences",ks={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},sa=[{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"}],Ar=[{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"}],ij=new Set(sa.map(e=>e.id)),lj=new Set(Ar.map(e=>e.id));function qt(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:kn("chat",t.chat),code:kn("code",t.code),terminal:kn("terminal",t.terminal)}}function kn(e,t){const r=ks[e],n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?ij:lj).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function Sn(e,t){var a;const r=kn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?sa:Ar;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function cj(e){const t=qt(e),r=Sn("chat",t.chat),n=Sn("code",t.code),a=Sn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function hs(e,t=document.documentElement){const r=qt(e),n=cj(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function vo(e){const t=qt(e);try{localStorage.setItem(_u,JSON.stringify(t))}catch{}return t}function dj(){try{const e=localStorage.getItem(_u);if(e)return qt(JSON.parse(e))}catch{}return ks}function uj(){return hs(dj())}function hr(e,t){var n;const r=e==="chat"?sa:Ar;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const mj=[{id:"dashboard",path:"/dashboard",icon:s.jsx(ic,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(os,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Hs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx(Wn,{}),label:"Settings"}];function pj({children:e}){const t=Ys(),r=jo(),n=i.useMemo(()=>mj.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>t(o.path)})),[r.pathname,t]),a=i.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Docs"}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(cc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(dc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Vx,{brand:({collapsed:o})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&s.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.81"]}),footerActions:({collapsed:o,toggleCollapsed:l})=>s.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:[s.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&s.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const hj=[{icon:s.jsx(os,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Zt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(uc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(Rt,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Hs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(cc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],fj=[{icon:s.jsx(Xm,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(ic,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Hn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Km,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(lc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(zm,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],xj=[{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 bj(){return s.jsxs(wr,{icon:s.jsx(dc,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:s.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:[s.jsx(wt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),s.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."}),s.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."})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.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 ↗"}),s.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 ↗"}),s.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 ↗"})]})]})}),s.jsx(wt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:hj.map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.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]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(wt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:ud.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:pd.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:md.map(e=>`${e.icon} ${e.name}`)}].map(e=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(t=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:t},t))})]},e.label))})}),s.jsx(wt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:fj.map(e=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.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]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),s.jsx(wt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),s.jsx("tbody",{children:xj.map((e,t)=>s.jsxs("tr",{className:t%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),s.jsx(Pn,{icon:s.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:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(op,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Va(e,t,r){return{...e,[t]:r}}function qa({surface:e,title:t,description:r,value:n,options:a,onChange:o}){return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.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=>s.jsx("option",{value:l.id,children:l.label},l.id))}),n.preset==="custom"&&s.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})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",s.jsx("span",{className:"font-mono break-all",children:Sn(e,n)})]})]})]})}function gj({value:e,savedValue:t,saving:r=!1,error:n,notice:a,onChange:o,onSave:l,onResetToSaved:c,onResetToDefaults:d}){const m=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.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&&s.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&&s.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}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(qa,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:sa,onChange:u=>o(Va(e,"chat",u))}),s.jsx(qa,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Ar,onChange:u=>o(Va(e,"code",u))}),s.jsx(qa,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Ar,onChange:u=>o(Va(e,"terminal",u))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",hr("chat",e.chat.preset)," · Code: ",hr("code",e.code.preset)," · Terminal: ",hr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",hr("chat",ks.chat.preset)," / ",hr("code",ks.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.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"}),s.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"}),s.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 yj(){const{ides:e}=cs(),t=e.find(q=>q.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=kt(),{userName:a}=cs(),[o,l]=i.useState(a||""),[c,d]=i.useState(null),[m,u]=i.useState(null),[p,b]=i.useState(ks),[w,x]=i.useState(!1),[h,g]=i.useState(""),[y,f]=i.useState(""),[A,C]=i.useState("127.0.0.1"),[v,N]=i.useState(""),[T,k]=i.useState(""),[j,B]=i.useState(""),[L,S]=i.useState(""),[D,$]=i.useState(""),[E,I]=i.useState(!1),M=async()=>{const ge=await(await Gt("/auth/session")).json();d(ge)},F=async()=>{const ge=await(await Gt("/api/v1/standalone/preferences")).json();u(ge),C(ge.standaloneBindHost);const fe=qt(ge.standaloneFontPreferences);b(fe),hs(fe),vo(fe)};i.useEffect(()=>{a!==void 0&&l(a)},[a]),i.useEffect(()=>{Promise.all([M(),F()]).catch(q=>{S(q instanceof Error?q.message:String(q))})},[]),i.useEffect(()=>{hs(p)},[p]);const P=q=>{const ge=q.target.value.trim();t!=null&&t.id&&ge!==a&&n(t.id,"set_user_name",{userName:ge}).catch(console.error)},[R,K]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),V=q=>{K(q);try{localStorage.setItem("adhdev_sound",q?"1":"0")}catch{}},te=async()=>{g(""),f(""),x(!0);try{const q=qt(p),ge=await Gt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:q})}),fe=await ge.json();if(!ge.ok)throw new Error((fe==null?void 0:fe.error)||"Failed to save standalone font preferences");const we=qt(fe.standaloneFontPreferences);u(fe),b(we),hs(we),vo(we),f("Standalone chat fonts saved for this self-hosted dashboard.")}catch(q){g(q instanceof Error?q.message:String(q))}finally{x(!1)}},ie=()=>{const q=qt(m==null?void 0:m.standaloneFontPreferences);g(""),f(""),b(q),hs(q)},J=()=>{g(""),f(""),b(ks),hs(ks)},me=async()=>{S(""),$(""),I(!0);try{const q=await Gt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:A})}),ge=await q.json();if(!q.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save standalone network preference");u(ge),C(ge.standaloneBindHost),$(ge.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(q){S(q instanceof Error?q.message:String(q))}finally{I(!1)}},je=async()=>{if(S(""),$(""),T.trim().length<4){S("Password must be at least 4 characters.");return}if(T!==j){S("New password and confirmation do not match.");return}I(!0);try{const q=await Gt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:T})}),ge=await q.json();if(!q.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save password");d(ge),await F(),N(""),k(""),B(""),$(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),Au()}catch(q){S(q instanceof Error?q.message:String(q))}finally{I(!1)}},ke=async()=>{S(""),$(""),I(!0);try{const q=await Gt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ge=await q.json();if(!q.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to clear password");d(ge),await F(),N(""),k(""),B(""),$("Standalone password disabled.")}catch(q){S(q instanceof Error?q.message:String(q))}finally{I(!1)}};return s.jsxs(wr,{icon:s.jsx(Wn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.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)&&s.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."}),s.jsx(wt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:"Version"}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.81"]}),s.jsx("span",{className:"text-text-muted",children:"Status"}),s.jsx("span",{className:t?"text-green-400":"text-yellow-400",children:t?"● Running":"○ Not connected"}),s.jsx("span",{className:"text-text-muted",children:"Current bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Default bind"}),s.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:"Auth"}),s.jsx("span",{className:"text-xs",children:c!=null&&c.hasPasswordAuth?"Password enabled":c!=null&&c.hasTokenAuth?"Token enabled":"No auth configured"})]})}),s.jsx(wt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.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."}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.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:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:A==="127.0.0.1",onChange:()=>C("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),s.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."})]})]}),s.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:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:A==="0.0.0.0",onChange:()=>C("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),s.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."})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{type:"button",onClick:()=>{me()},disabled:E,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:E?"Saving…":"Save default network mode"}),s.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","."]})]})]})}),s.jsx(wt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.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."}),L&&s.jsx(Es,{variant:"error",children:L}),D&&s.jsx(Es,{variant:"success",children:D}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.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:v,onChange:q=>N(q.target.value)}),s.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:T,onChange:q=>k(q.target.value)}),s.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:j,onChange:q=>B(q.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{je()},disabled:E,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:E?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{ke()},disabled:E,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"})]})]})}),s.jsx(wt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(q=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${q.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:q.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:q.type})]},q.type))})}),s.jsx(wt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:s.jsx(sb,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),s.jsx(wt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),s.jsx(ob,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.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."}),s.jsx(hb,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),s.jsx(gj,{value:p,savedValue:qt(m==null?void 0:m.standaloneFontPreferences),saving:w,error:h,notice:y,onChange:b,onSave:()=>{te()},onResetToSaved:ie,onResetToDefaults:J})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),s.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."}),s.jsx(bb,{})]})]})}),s.jsx(wt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Zx,{}),s.jsx(ps,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ap,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:R,onChange:V})]})}),s.jsx(wt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:s.jsx("div",{className:"flex flex-col gap-3",children:s.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:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Hm,{size:16,className:"text-text-secondary"})," Display Name"]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),s.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:q=>l(q.target.value),onBlur:P,onKeyDown:q=>{q.key==="Enter"&&q.currentTarget.blur()}})]})})})]})}zx();mb();uj();const vj=ac({baseUrl:"",getToken:xi});function wj({children:e}){const[t,r]=i.useState(null),[n,a]=i.useState(!0),[o,l]=i.useState(""),[c,d]=i.useState(""),[m,u]=i.useState(!1),p=async()=>{a(!0),d("");try{const x=await(await Gt("/auth/session")).json();r(x)}catch(w){d(w instanceof Error?w.message:String(w))}finally{a(!1)}};i.useEffect(()=>{p()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let w=!1;return(async()=>{try{const x=await Gt("/api/v1/standalone/preferences");if(!x.ok)return;const h=await x.json();if(w)return;const g=qt(h.standaloneFontPreferences);hs(g),vo(g)}catch{}})(),()=>{w=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const b=async w=>{w.preventDefault(),u(!0),d("");try{const x=await Gt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),h=await x.json();if(!x.ok)throw new Error((h==null?void 0:h.error)||"Login failed");r(h),l(""),Au()}catch(x){d(x instanceof Error?x.message:String(x))}finally{u(!1)}};return n?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):t?!t.required||t.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.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:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:t.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."})]}),t.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:b,children:[s.jsx("input",{type:"password",value:o,onChange:w=>l(w.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),s.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"})]}):s.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&&s.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})]})}):s.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 Ql(){const{ides:e,initialLoaded:t}=cs();if(!t)return s.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?s.jsx(Ja,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Ja,{to:"/dashboard",replace:!0})}function jj(){const e=i.useMemo(()=>({sendCommand:jn,sendData:yo,sendPtyInput:Tu}),[]);return s.jsx(bm,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Em,{client:vj,children:s.jsx(wj,{children:s.jsx(oj,{children:s.jsx(Bm,{value:e,children:s.jsx(pj,{children:s.jsxs(gm,{children:[s.jsx(ss,{path:"/dashboard",element:s.jsx($v,{})}),s.jsx(ss,{path:"/machine",element:s.jsx(Ql,{})}),s.jsx(ss,{path:"/machines/:id",element:s.jsx(Kw,{})}),s.jsx(ss,{path:"/machines",element:s.jsx(Ql,{})}),s.jsx(ss,{path:"/about",element:s.jsx(bj,{})}),s.jsx(ss,{path:"/settings",element:s.jsx(yj,{})}),s.jsx(ss,{path:"/mesh",element:s.jsx(Xw,{})}),s.jsx(ss,{path:"*",element:s.jsx(Ja,{to:"/dashboard",replace:!0})})]})})})})})})})}tx({connectionManager:zt});ym(document.getElementById("root")).render(s.jsx(jj,{}));
|