@adhdev/daemon-standalone 0.9.82-rc.5 → 0.9.82-rc.51
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 +22461 -20426
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-s07lLC64.js +98 -0
- package/public/assets/index-sfey5a4c.css +1 -0
- package/public/assets/{terminal-DCVDkSIp.js → terminal-D46M5EWH.js} +4 -4
- package/public/assets/{vendor-piMzuE8Y.js → vendor-CgiI0UIA.js} +29 -29
- package/public/index.html +3 -3
- package/vendor/mcp-server/index.js +425 -39
- package/vendor/mcp-server/index.js.map +1 -1
- package/public/assets/index-B8fg8KB1.css +0 -1
- package/public/assets/index-BG1OOql2.js +0 -98
|
@@ -0,0 +1,98 @@
|
|
|
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 Uu=Object.defineProperty;var zu=(e,t,r)=>t in e?Uu(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var Ze=(e,t,r)=>zu(e,typeof t!="symbol"?t+"":t,r);import{r as i,j as s,M as xo,a as Vu,b as Gu,c as qu,R as St,d as Sr,t as Yu,e as Xu,u as qs,D as Ju,f as Ua,g as za,i as Qu,h as Zu,C as em,B as tm,k as sm,l as rm,H as bi,P as gi,m as nm,n as am,o as bo,p as om,q as im,s as lm,v as cm,w as es,N as Va,x as dm}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 um(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 Os=um();function yi(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 mm(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function vi(e){return Array.isArray(e)?[...e]:[]}function Yl(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?vi(e.messages):t.messages,activeModal:n?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...r?{messages:vi(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function fr(e,t){const r=mm(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:Yl(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 Xl(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 wi(e){return!!e&&typeof e=="object"&&"text"in e}function go(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:wi(o)?String(o.text||""):"").join(r):wi(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Fs(e){return go(e,{normalizeWhitespace:!0})}const Jl=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}),Ql=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function ji(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 Zl(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 pm(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 Zn(e){if(!e||typeof e!="object")return"";const t=e,r=pm(Fs(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 fm(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=Zn(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:Zn(e[0]),last:Zn(e[e.length-1])}}function Ga(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function qa(e,t,r){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Ga(e)&&Ga(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)qa(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"&&qa(n[l],a[l],r)}function br(e,t){return Array.isArray(e)?e.map(r=>br(r,t)):!e||typeof e!="object"?e:Ga(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?fm(a,t):br(a,t)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,br(n,t)]))}function hm(e,t){try{const r=new WeakSet;return qa(e,t,r),JSON.stringify(br(e,r))===JSON.stringify(br(t,r))}catch{return!1}}function Ya(e,t,r){return hm(e,t)?(e._lastUpdate=r,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function ec(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function xm(e,t,r){t[r]!==void 0&&(e[r]=t[r])}function ki(e,t,r,n){var c;const a=(c=t.chats)!=null&&c.length?t.chats:e.chats,o=Xl(e.childSessions,t.childSessions,{preserveMissing:n}),l=Yl(t.activeChat,e.activeChat);return Zl(e,t,{...e,...t,chats:a,childSessions:o,activeChat:l,_lastUpdate:r})}function bm(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=Xl(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"])xm(n,t,l);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(n.machineNickname=t.machineNickname),t.versionMismatch===!0&&(n.versionMismatch=!0),n}function gm(e,t,r,n){const a=bm(e,t,n),o=Object.keys(a).length>0?Zl(e,t,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Ya(e,o,r)}function ym(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=ec(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 vm(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 wm(e,t,r,n,a){return e.transport?r.has(t)&&!n.has(t)?!0:a.has(t):!1}function jm(e,t,r){var u,f;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(x=>({...x,_lastUpdate:n}));const o=new Map;for(const x of t)o.set(x.id,x);const{incomingIds:l,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=ym(e);for(const x of e){const w=o.get(x.id);if(!w){o.set(x.id,{...x,_lastUpdate:n});continue}const b=ji(x),p=ji(w),g=ec(x),y=!a.has(g);if(b>p){const j=ki(w,x,n,y);o.set(x.id,Ya(w,j,n));continue}if(b<p){o.set(x.id,gm(w,x,n,y));continue}const h=x.timestamp||n,M=w._lastUpdate||w.timestamp||0;if(h>=M){const j=ki(w,x,n,y);o.set(x.id,Ya(w,j,n));continue}(u=x.chats)!=null&&u.length&&!((f=w.chats)!=null&&f.length)&&o.set(x.id,{...w,chats:x.chats})}for(const[x,w]of o){const b=w.daemonId||x.split(":")[0];if(!c.has(b))continue;if(a.has(b)&&m.has(b)&&!l.has(x)){o.delete(x);continue}const p=n-(w._lastUpdate||w.timestamp||0);vm(w,b,p,l,a,d)&&o.delete(x)}for(const[x,w]of o){const b=w.daemonId||x.split(":")[0];if(wm(w,b,c,d,o))continue;n-(w._lastUpdate||w.timestamp||0)>3e5&&w.status!=="online"&&o.delete(x)}return Array.from(o.values())}function km(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 Sm({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 f=i.useCallback((y,h)=>{n(M=>{let j=!1;const v=M.map(A=>A.id!==y||A.chats===h?A:(j=!0,{...A,chats:h}));return j?v:M})},[]),x=i.useCallback((y,h)=>{n(M=>{const j=M.length===0?y:jm(y,M,h),v=!km(M,j);return v&&Os.record({kind:"dashboard.entries_applied",payload:{incoming:yi(y),next:yi(j)}}),v?j:M})},[]),w=i.useCallback(()=>o(!0),[]),b=i.useMemo(()=>({injectEntries:x,markLoaded:w,getIdes:()=>u.current}),[x,w]),p=t,g=i.useMemo(()=>({ides:r,updateRouteChats:f,initialLoaded:a,toasts:l,setToasts:c,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,connectionRetryStatuses:p==null?void 0:p.connectionRetryStatuses,userName:d,setUserName:m}),[r,f,a,l,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,p==null?void 0:p.connectionRetryStatuses,d]);return s.jsx(Ql.Provider,{value:b,children:s.jsx(Jl.Provider,{value:g,children:e})})}function ls(){return i.useContext(Jl)}function Nr(){return i.useContext(Ql)}function tc(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 f=a(c),x=new AbortController,w=setTimeout(()=>x.abort(),15e3);try{const b=await fetch(f,{...d,headers:m,signal:x.signal});if(b.status===401)throw n==null||n(),new Error("Unauthorized");if(!b.ok){const p=await b.json().catch(()=>({error:b.statusText}));throw new Error(p.error||`API Error: ${b.status}`)}return b.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 Nm=tc({baseUrl:"http://localhost:3847"}),Cm=i.createContext(Nm);function Im({client:e,children:t}){return s.jsx(Cm.Provider,{value:e,children:t})}const Mm={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},sc=i.createContext(Mm);function Am({value:e,children:t}){return s.jsx(sc.Provider,{value:e,children:t})}function kt(){return i.useContext(sc)}function Tm(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 _m(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Lm(e){return e?Tm([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),_m(e.content)]):""}const ze={size:18};function rc({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 yo({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 as({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 nc({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 Rm({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 Pm({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 ac({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 Dm({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 $n({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 oc({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 Em({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 Jt({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 _t({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 vo({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 $m({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 ks({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 Cr({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 Ws({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 rs({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 Bm({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 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("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 wo({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 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("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Om({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 jo({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 Fm({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 ko({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 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("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 Wm({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 Km({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 Hm({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 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("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 Bn({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 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("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 Vm({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 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("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 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("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 Ym({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 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("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 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("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 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("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 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("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}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("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 tp({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 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:"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 So="adhdev_chat_activity_visible",Si=new Set(["hidden","debug","internal"]),Ni=new Set(["visible","user","chat"]),rp=new Set(["debug","trace","internal"]),np=new Set(["tool_call","terminal_command","runtime_activity"]),ap=new Set(["runtime_status","provider_chrome","control"]),op=new Set(["thought","tool","terminal"]);function dc(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Ts(e){return typeof e=="string"?e.trim().toLowerCase():""}function ea(e,t,r){return e[r]??(t==null?void 0:t[r])}function Ci(e,t,r){const n=e;return r.some(a=>n[a]===!0||(t==null?void 0:t[a])===!0)}function ip(e,t){const r=Ts(e.kind);return r||(t==="tool"?"tool":"standard")}function ta(e,t,r){const n=dc(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 lp(e){const t=e.content;return Array.isArray(t)&&t.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function No(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=dc(e),r=Ts(e.role),n=ip(e,r),a=Ts(ea(e,t,"visibility")),o=Ts(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),l=Ts(ea(e,t,"audience")),c=Ts(ea(e,t,"source")),d=Si.has(a)||Si.has(o)||rp.has(l)||Ci(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),m=Ni.has(a)||Ni.has(o)||l==="chat"||Ci(e,t,["userFacing"]),u=op.has(n)||np.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:ta(e,n,c)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:ta(e,n,c)};if((r==="system"||n==="system")&&lp(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(ap.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:ta(e,n,c)};const f=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:f?"chat":"internal",isUserFacing:f,isActivityFacing:!1,isInternal:!f,role:r,kind:n,label:f?"Chat":"Internal"}}function cp(e){return(Array.isArray(e)?e:[]).filter(t=>No(t).isUserFacing)}function uc(e){return(Array.isArray(e)?e:[]).filter(t=>No(t).isActivityFacing)}function dp(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 Ii(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(So))==="1"}catch{return!1}}function up(e,t=typeof localStorage<"u"?localStorage:void 0){try{t==null||t.setItem(So,e?"1":"0")}catch{}}const mc=[Vu,{singleTilde:!1}],pc=[mc,Gu,qu],mp=[mc],Co=200,pp=80,Mi=650,er=new Map;function wn(e,t){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(t||""):!0}function fp(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}:${Lm(n)}`}function hp(e,t,r,n){return e||!t?!1:wn(r,n)}function xp({scrollTop:e,scrollHeight:t,clientHeight:r,topThresholdPx:n=pp,bottomThresholdPx:a=Co}){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 bp(e){return xp({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function hr(e,t=Co){return!!e&&e.fromBottom>=t}function gp(e,t){return wn(e,t)?!hr(e):!0}function yp({hasSelection:e,userScrolledUp:t,hasChatContentChanged:r=!0}){return!(e||t||!r)}function vp({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:r}){return e?!1:r||!t}function sa(e,t){const r=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(r)?r:t.top}function fc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function wp(e,t,r){return Number(e.receivedAt||r[jn(e,t)]||0)||0}function hc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function jp(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function tr(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 ra(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 Ai(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):hc(e)?s.jsx(xo,{remarkPlugins:pc,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function sr({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:Ai(String(r.text||""),t)},`text-${n}`);if(r.type==="image"){const a=ra(r),o=r.alt||r.description||tr(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=ra(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",tr(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=ra(r),o=r.title||r.name||r.alt||tr(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||tr(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=tr(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}),Ai(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 jn(e,t){const r=e,n=go(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 kp=i.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(xo,{remarkPlugins:mp,children:t.text}),s.jsx("span",{className:"action-time",children:fc(t.timestamp)})]})},(e,t)=>e.log===t.log),Sp=i.memo(function({message:t,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:l,onToggleTextExpanded:c}){var S,k,K;const d=(t.role||"").toLowerCase(),m=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),f=No(t),x=jp(t.content)?t.content:null,w=!!(x!=null&&x.some(L=>L.type!=="text")),b=go(t.content,{joiner:`
|
|
6
|
+
`});if(f.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const L=f.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&&x?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(sr,{parts:x,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:b})]})}if(u==="thought"){const L=typeof((S=t.meta)==null?void 0:S.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":f.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Hm,{size:13}),s.jsx("span",{children:L})]}),s.jsx("div",{className:"chat-msg-body",children:b})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":f.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&&x?s.jsx("div",{className:"tool-text w-full",children:s.jsx(sr,{parts:x,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:b})]});if(u==="terminal"){const L=(k=t.meta)!=null&&k.isRunning?"⏳":"✅",N=typeof((K=t.meta)==null?void 0:K.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":f.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:L}),s.jsx("span",{children:N})]}),w&&x?s.jsx("div",{className:"chat-msg-body",children:s.jsx(sr,{parts:x,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:b})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:w&&x?s.jsx(sr,{parts:x,renderAsPreformatted:!1}):b.slice(0,100)});const p=t.meta,y=(typeof(p==null?void 0:p.renderMode)=="string"?p.renderMode.trim():"")==="preformatted",h=b,M=!1,j=h,v=y,A=!v&&hc(j),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:(h||w||m)&&s.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${h||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:fc(r)})]}),(h||w)&&s.jsx("div",{className:"chat-markdown",children:w&&x?s.jsx(sr,{parts:x,renderAsPreformatted:v}):v?s.jsx("pre",{className:"chat-preformatted",children:j}):A?s.jsx(xo,{remarkPlugins:pc,children:j}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:j})}),M]})})},(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),Np=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:f,onLoadMore:x,isLoadingMore:w,hasMoreHistory:b,hiddenLiveCount:p=0,loadError:g,scrollToBottomRequestNonce:y,isVisible:h=!0},M){const j=i.useRef(null),v=i.useRef(null),A=i.useRef(null),T=i.useRef(0),S=i.useRef(""),k=i.useRef(""),K=i.useRef(!1),L=i.useRef(null),N=i.useRef(!1),P=i.useRef(null),B=i.useRef(!1),[D,C]=i.useState(new Set),[I,E]=i.useState({showTop:!1,showBottom:!1}),R=i.useRef(!1),$=i.useRef(!1),z=i.useRef(h),F=i.useRef(h),me=i.useRef(null);F.current=h;const ie=()=>{const le=j.current;return le?le.scrollHeight-le.scrollTop-le.clientHeight<Co:!0},ee=i.useCallback(()=>{const le=j.current,pe=le?bp(le):{showTop:!1,showBottom:!1};E(ne=>ne.showTop===pe.showTop&&ne.showBottom===pe.showBottom?ne:pe)},[]),ce=i.useCallback((le="auto")=>{var ne;const pe=j.current;pe&&(pe.scrollTo({top:pe.scrollHeight,behavior:le}),(ne=pe.ownerDocument.defaultView)==null||ne.requestAnimationFrame(()=>ee()))},[ee]),je=i.useCallback((le="auto")=>{var ne;const pe=j.current;pe&&(pe.scrollTo({top:0,behavior:le}),(ne=pe.ownerDocument.defaultView)==null||ne.requestAnimationFrame(()=>ee()))},[ee]),Ne=i.useCallback(()=>{var Ce;const le=j.current,pe=(Ce=window.getSelection)==null?void 0:Ce.call(window);if(!le||!pe||pe.rangeCount===0||pe.isCollapsed){B.current=!1;return}const ne=pe.anchorNode,Ie=pe.focusNode;B.current=!!(ne&&Ie&&le.contains(ne)&&le.contains(Ie))},[]),q=i.useMemo(()=>{const le=cp(t),pe=uc(t);return dp(le,pe,u)},[t,u]),ge=q.length===t.length?m:void 0,he=fp(q,ge),we=i.useCallback(()=>{const le=j.current;if(!le||!c||!F.current)return;const pe={top:le.scrollTop,fromBottom:Math.max(0,le.scrollHeight-le.scrollTop-le.clientHeight),messageFingerprint:he};me.current={contextKey:c,snapshot:pe},er.set(c,pe)},[c,he]),xe=i.useCallback((le="auto")=>{L.current!=null&&cancelAnimationFrame(L.current),L.current=requestAnimationFrame(()=>{L.current=null,ce(le)})},[ce]),Se=i.useCallback(()=>{R.current=!1,N.current=!0,$.current=!0,P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{N.current=!1,P.current=null},Mi)},[]);i.useEffect(()=>{const le=!K.current,pe=k.current!==c;if(k.current=c,le||pe){K.current=!0;const Ie=c?er.get(c):null,Ce=!!Ie&&wn(Ie,he);R.current=Ce?hr(Ie):!1,N.current=gp(Ie,he),B.current||(Ce?requestAnimationFrame(()=>{const _e=j.current;_e&&(sa(_e,Ie),R.current=hr(Ie),ee(),$.current=!0)}):xe("auto")),T.current=q.length,S.current=he;return}q.length>T.current;const ne=he!==S.current;yp({hasSelection:B.current,userScrolledUp:R.current,hasChatContentChanged:ne})&&xe("auto"),T.current=q.length,S.current=he},[he,c,q.length,xe,ee]),i.useEffect(()=>{y&&(Se(),B.current||xe("auto"))},[Se,xe,y]),i.useEffect(()=>{const le=z.current;le&&!h&&we(),F.current=h,z.current=h;const pe=c?er.get(c):null;if(hp(le,h,pe,he)){if(!pe)return;R.current=hr(pe),N.current=!1,B.current||requestAnimationFrame(()=>{const ne=j.current;ne&&(sa(ne,pe),ee())});return}},[h,c,he,Se,we,xe,ee]),i.useEffect(()=>()=>{const le=me.current;le&&er.set(le.contextKey,le.snapshot),L.current!=null&&cancelAnimationFrame(L.current),P.current!=null&&window.clearTimeout(P.current)},[]),i.useEffect(()=>{const le=v.current,pe=j.current;if(!le||!pe)return;const ne=()=>{P.current!=null&&window.clearTimeout(P.current),P.current=window.setTimeout(()=>{N.current=!1,P.current=null},Mi)},Ie=new ResizeObserver(()=>{ee();const Ce=N.current;vp({hasSelection:B.current,userScrolledUp:R.current,contextAutoScrollActive:Ce})&&(xe("auto"),Ce&&ne())});return Ie.observe(le),pe!==le&&Ie.observe(pe),()=>{Ie.disconnect(),P.current!=null&&(window.clearTimeout(P.current),P.current=null)}},[xe,c,ee]),i.useImperativeHandle(M,()=>({scrollToBottom:(le="smooth")=>{ce(le)}}),[ce]),i.useEffect(()=>{const le=j.current;if(!le)return;let pe;const ne=()=>{we(),clearTimeout(pe),pe=setTimeout(()=>{R.current=!ie(),ee()},50)};return le.addEventListener("scroll",ne,{passive:!0}),()=>{le.removeEventListener("scroll",ne),clearTimeout(pe)}},[we,ee]),i.useEffect(()=>(document.addEventListener("selectionchange",Ne),()=>document.removeEventListener("selectionchange",Ne)),[Ne]);const J=i.useRef(0),fe=i.useRef(!1);i.useEffect(()=>{const le=j.current;if(!le||!fe.current||J.current===0)return;const pe=le.scrollHeight-J.current;pe>0&&(le.scrollTop=pe),ee(),we(),J.current=0,fe.current=!1},[q.length,we,ee]),i.useEffect(()=>{if($.current||!c)return;const le=er.get(c),pe=j.current;if(!(!le||!pe)){if(!wn(le,he)){ce("auto"),$.current=!0;return}sa(pe,le),R.current=hr(le),ee(),$.current=!0}},[c,he,q.length,ce,ee]);const ae=()=>{const le=j.current;le&&(J.current=le.scrollHeight),fe.current=!0,x==null||x()},ue=()=>{R.current=!0,je("smooth"),we()},oe=()=>{Se(),ce("smooth"),we()},de=i.useMemo(()=>{const le=q.map((Ce,_e)=>({type:"message",data:Ce,index:_e,ts:wp(Ce,_e,d)}));if(!r||r.length===0)return le;const pe=[...r].sort((Ce,_e)=>Ce.timestamp-_e.timestamp).map((Ce,_e)=>({type:"action",data:Ce,index:_e,ts:Ce.timestamp})),ne=[];let Ie=0;for(const Ce of le){for(;Ie<pe.length&&Ce.ts>0&&pe[Ie].ts<Ce.ts;)ne.push(pe[Ie++]);ne.push(Ce)}for(;Ie<pe.length;)ne.push(pe[Ie++]);return ne},[q,r,d]),Q=p>0||!!b,ve=p>0?`↑ Show ${Math.min(p,80)} earlier messages${p>80?` (${p} hidden)`:""}`:g?`↻ ${g}`:"↑ Load older messages";return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:j,"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..."}),Q&&!w&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:ae,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${g&&p===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:ve})}),de.length===0&&!Q&&(f||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),de.map(le=>{if(le.type==="action"){const Me=le.data;return s.jsx(kp,{log:Me},`action-${le.index}`)}const pe=le.data,ne=le.index,Ie=jn(pe,ne),Ce=pe.receivedAt||d[Ie],_e=`${c}-${Ie}`,H=D.has(_e);return s.jsx(Sp,{message:pe,receivedAt:Ce,agentName:n,userName:a,isCliMode:o,isTextExpanded:H,onToggleTextExpanded:()=>C(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:A})]})}),(I.showTop||I.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[I.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"}),I.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:oe,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),Cp=i.memo(Np,(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),Ip="modulepreload",Mp=function(e){return"/"+e},Ti={},Ap=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=Mp(d),d in Ti)return;Ti[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":Ip,m||(f.as="script"),f.crossOrigin="",f.href=d,c&&f.setAttribute("nonce",c),document.head.appendChild(f),m)return new Promise((x,w)=>{f.addEventListener("load",x),f.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 _i=!1;const xc=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([]),f=i.useRef(!1),x=i.useRef(!1),w=i.useRef(!1),b=i.useRef(!1),p=()=>{const g=c.current;if(g){f.current&&(g.clear(),f.current=!1);for(const y of u.current)g.write(y.data,y.onProcessed);u.current=[],x.current&&(g.fit(),x.current=!1),w.current&&(g.bumpResize(),w.current=!1),b.current&&(g.scrollToTop(),b.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=[],f.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],f.current=!0)},resize:(g,y)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(g,y)},fit:()=>{c.current?c.current.fit():x.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():w.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():b.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&&p()},[d]),i.useEffect(()=>{let g=!1;return Ap(()=>import("./terminal-D46M5EWH.js"),__vite__mapDeps([0,1,2])).then(y=>{_i||(_i=!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"}})});xc.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 Li({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 Tp({cursorPos:e,viewportRef:t,imgRef:r}){var h;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(h=t.current)==null?void 0:h.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,f,x,w;d>m?(u=a.width,f=a.width/d,x=0,w=(a.height-f)/2):(f=a.height,u=a.height*d,x=(a.width-u)/2,w=0);const b=a.left-o.left+x+u*e.nx,p=a.top-o.top+w+f*e.ny,g=Math.max(8,Math.min(o.width-8,b)),y=Math.max(8,Math.min(o.height-8,p));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 _p({inputMode:e,onToggleInputMode:t,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:l,setImeText:c,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:f,mobileFillZoom:x,onZoomOut:w,onZoomReset:b,onZoomIn:p,transportType:g,screenshotUsage:y,lastActionStatus:h}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:M=>M.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(M=>!M),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:M=>M.stopPropagation(),onChange:M=>c(M.target.value),onKeyDown:M=>{d(M)},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(M=>!M),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`}),h&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:h})]})]}),a&&s.jsxs("div",{onTouchStart:M=>M.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<=(f?x:1)+.01?f?"FILL":"FIT":`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:M=>{M.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:M=>{M.stopPropagation(),b()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:f?"FILL":"FIT"}),s.jsx("button",{onClick:M=>{M.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Lp({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 Rp(){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 Ri(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(!Rp())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,Ri(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,Ri(t[l])]))}),r.current=t})}function Pp({containerRef:e,viewportRef:t,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:l,panXRef:c,panYRef:d,setPanX:m,setPanY:u,setZoom:f,lastWheelTimeRef:x,onAction:w,setLastActionStatus:b,spawnRippleFromNormalized:p,clampPan:g,isMobile:y,mobileFillZoom:h}){const[M,j]=i.useState(null),v=i.useRef(null),A=i.useRef(null),T=i.useRef(null),S=i.useRef(!1),k=i.useRef(null),K=i.useRef(0),L=i.useRef(null),N=i.useRef(1),P=i.useRef({x:0,y:0}),B=i.useRef(!1),D=i.useRef(n),C=i.useRef(w),I=30,E=550,R=18,$=60,z=400,F=12,me=()=>{if(v.current)return;const ce={nx:.5,ny:.5};v.current=ce,j(ce)};return i.useEffect(()=>{D.current=n,n==="mouse"&&me()},[n]),i.useEffect(()=>{C.current=w},[w]),i.useEffect(()=>{const ce=e.current;if(!ce)return;const je=xe=>{if(!r.current)return null;const Se=r.current.getBoundingClientRect();return!Se.width||!Se.height?null:{nx:Math.max(0,Math.min(1,(xe.clientX-Se.left)/Se.width)),ny:Math.max(0,Math.min(1,(xe.clientY-Se.top)/Se.height))}},Ne=(xe,Se)=>{if(!r.current)return{dnx:0,dny:0};const J=r.current,fe=J.getBoundingClientRect(),ae=J.naturalWidth||fe.width,ue=J.naturalHeight||fe.height,oe=ae/ue,de=fe.width/fe.height;let Q,ve;return oe>de?(Q=fe.width,ve=fe.width/oe):(ve=fe.height,Q=fe.height*oe),{dnx:xe/Q,dny:Se/ve}},q=(xe,Se,J)=>{if(J<=1.05)return;const fe=-(xe-.5)*100,ae=-(Se-.5)*100,ue=g(fe,ae,J);(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 Se=t.current;if(Se&&xe.target instanceof Node&&Se.contains(xe.target))xe.preventDefault();else return;if(xe.touches.length===1){const J=xe.touches[0];A.current={x:J.clientX,y:J.clientY,time:Date.now()},T.current={x:J.clientX,y:J.clientY},B.current||(S.current=!1),k.current=setTimeout(()=>{if(!S.current&&!B.current)if(S.current=!0,D.current==="mouse"){const fe=v.current||{nx:.5,ny:.5};b("Right Click"),p(fe.nx,fe.ny,"right"),C.current("input_click",{...fe,button:"right"}).catch(()=>{})}else{const fe=je(J);fe&&(b("Right Click"),p(fe.nx,fe.ny,"right"),C.current("input_click",{...fe,button:"right"}).catch(()=>{}))}},500);return}if(xe.touches.length===2){k.current&&clearTimeout(k.current),S.current=!0,B.current=!0;const J=xe.touches[1].clientX-xe.touches[0].clientX,fe=xe.touches[1].clientY-xe.touches[0].clientY;L.current=Math.sqrt(J*J+fe*fe),N.current=l.current,P.current={x:(xe.touches[0].clientX+xe.touches[1].clientX)/2,y:(xe.touches[0].clientY+xe.touches[1].clientY)/2}}},he=xe=>{const Se=t.current;if(Se&&xe.target instanceof Node&&Se.contains(xe.target)&&xe.preventDefault(),xe.touches.length===1&&T.current){const J=xe.touches[0],fe=J.clientX-T.current.x,ae=J.clientY-T.current.y;if(!S.current&&A.current){const ue=J.clientX-A.current.x,oe=J.clientY-A.current.y;Math.sqrt(ue*ue+oe*oe)>8&&(S.current=!0,k.current&&clearTimeout(k.current))}if(S.current)if(D.current==="mouse"){const ue=Ne(fe,ae),oe=v.current||{nx:.5,ny:.5},de=Math.max(0,Math.min(1,oe.nx+ue.dnx)),Q=Math.max(0,Math.min(1,oe.ny+ue.dny));v.current={nx:de,ny:Q},j({nx:de,ny:Q}),b(`Cursor: ${Math.round(de*100)}%, ${Math.round(Q*100)}%`),q(de,Q,l.current);const ve=Date.now();ve-x.current>=30&&(x.current=ve,C.current("input_mouseMoved",{nx:de,ny:Q}).catch(()=>{}))}else if(l.current>1){const ue=t.current;if(ue){const oe=ue.clientWidth,de=ue.clientHeight,Q=c.current+fe/oe*100,ve=d.current+ae/de*100,le=g(Q,ve,l.current);m(le.x),u(le.y),c.current=le.x,d.current=le.y}}else{const ue=je(J);if(ue){const oe=Date.now();oe-x.current>=40&&(x.current=oe,b("Scroll"),C.current("input_wheel",{nx:ue.nx,ny:ue.ny,deltaX:Math.round(-fe*2.5),deltaY:Math.round(-ae*2.5)}).catch(()=>{}))}}T.current={x:J.clientX,y:J.clientY};return}if(xe.touches.length===2&&L.current!==null){const J=xe.touches[1].clientX-xe.touches[0].clientX,fe=xe.touches[1].clientY-xe.touches[0].clientY,ue=Math.sqrt(J*J+fe*fe)/L.current,oe=(xe.touches[0].clientX+xe.touches[1].clientX)/2,de=(xe.touches[0].clientY+xe.touches[1].clientY)/2,Q=oe-P.current.x,ve=de-P.current.y,le=Math.abs(ue-1)>.03;if(D.current==="mouse"){if(le){const pe=Math.max(o,Math.min(5,N.current*ue));f(pe),l.current=pe}else if(Math.abs(Q)>2||Math.abs(ve)>2){const pe=v.current||{nx:.5,ny:.5},ne=Date.now();ne-x.current>=30&&(x.current=ne,b("Scroll"),C.current("input_wheel",{nx:pe.nx,ny:pe.ny,deltaX:Math.round(-Q*3),deltaY:Math.round(-ve*3)}).catch(()=>{}))}}else{const pe=Math.max(o,Math.min(5,N.current*ue));f(pe),l.current=pe;const ne=t.current;if(ne&&pe>1){const Ie=ne.clientWidth,Ce=ne.clientHeight,_e=c.current+Q/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}}P.current={x:oe,y:de}}},we=xe=>{var Se;if(k.current&&clearTimeout(k.current),L.current=null,xe.touches.length===1&&B.current){const J=xe.touches[0];A.current={x:J.clientX,y:J.clientY,time:Date.now()},T.current={x:J.clientX,y:J.clientY},S.current=!0;return}if(xe.touches.length===0){if(B.current){B.current=!1,S.current=!1;return}if(xe.changedTouches.length===1){const J=xe.changedTouches[0],fe=Date.now(),ae=fe-(((Se=A.current)==null?void 0:Se.time)||0),ue=A.current?J.clientX-A.current.x:0,oe=A.current?J.clientY-A.current.y:0,de=Math.sqrt(ue*ue+oe*oe);if(D.current==="mouse"){if(ae<I||ae>E||de>R){S.current=!1;return}const Q=v.current||je(J);Q&&(b(`Click: ${Math.round(Q.nx*100)}%, ${Math.round(Q.ny*100)}%`),p(Q.nx,Q.ny,"left"),C.current("input_click",{...Q}).catch(()=>{}))}else{if(S.current){S.current=!1;return}if(ae<$||ae>z||de>F){S.current=!1;return}const Q=je(J);if(!Q)return;fe-K.current<300?(b("Double tap"),p(Q.nx,Q.ny,"double"),C.current("input_click",{...Q,clickCount:2}).catch(()=>{}),K.current=0):(b(`Tap: ${Math.round(Q.nx*100)}%, ${Math.round(Q.ny*100)}%`),p(Q.nx,Q.ny,"left"),C.current("input_click",{...Q}).catch(()=>{}),K.current=fe)}}S.current=!1}};return ce.addEventListener("touchstart",ge,{passive:!1}),ce.addEventListener("touchmove",he,{passive:!1}),ce.addEventListener("touchend",we,{passive:!1}),()=>{ce.removeEventListener("touchstart",ge),ce.removeEventListener("touchmove",he),ce.removeEventListener("touchend",we),k.current&&clearTimeout(k.current)}},[e,t,r,o,l,c,d,m,u,f,x,b,p,g]),{cursorPos:M,cursorPosRef:v,handleToggleInputMode:()=>{a(ce=>{const je=ce==="touch"?"mouse":"touch";return je==="mouse"&&me(),je})},handleZoomReset:()=>{const ce=y?h:1;f(ce),l.current=ce,m(0),u(0),c.current=0,d.current=0}}}function bc({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),[f,x]=i.useState(""),[,w]=i.useState(!1),[b,p]=i.useState([]),g=i.useRef(0),[y,h]=i.useState(!1),[M,j]=i.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[A,T]=i.useState(v?"mouse":"touch"),[S,k]=i.useState(1),K=i.useRef(!1),[L,N]=i.useState(1),[P,B]=i.useState(0),[D,C]=i.useState(0);_r("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:A,zoom:L,panX:P,panY:D,isMenuOpen:y,isImeOpen:M});const I=i.useRef(0),E=i.useRef(L),R=i.useRef(P),$=i.useRef(D);i.useEffect(()=>{E.current=L},[L]),i.useEffect(()=>{R.current=P},[P]),i.useEffect(()=>{$.current=D},[D]),i.useEffect(()=>{var ae;(ae=l.current)==null||ae.focus()},[]);const z=r==="connected",F=n,me=z?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",ie=z?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!v||K.current||!F)return;const ae=d.current,ue=c.current;if(!ae||!ue)return;const oe=()=>{const de=ue.clientWidth,Q=ue.clientHeight,ve=ae.naturalWidth,le=ae.naturalHeight;if(!ve||!le||!de||!Q)return;const pe=Math.min(de/ve,Q/le),Ie=Math.max(de/ve,Q/le)/pe;Ie>1.01&&(k(Ie),N(Ie),E.current=Ie),K.current=!0};ae.complete&&ae.naturalWidth?oe():ae.addEventListener("load",oe,{once:!0})},[F,v]);const ee=.5;i.useEffect(()=>{L<=ee&&(B(0),C(0))},[L,ee]);const ce=(ae,ue,oe)=>{if(oe<=ee)return{x:0,y:0};const de=(oe-1)/(2*oe)*100,Q=(oe-1)/(2*oe)*100;return{x:Math.max(-de,Math.min(de,ae)),y:Math.max(-Q,Math.min(Q,ue))}},je=(ae,ue)=>{if(!d.current)return null;const oe=d.current.getBoundingClientRect();return!oe.width||!oe.height?null:{nx:Math.max(0,Math.min(1,(ae-oe.left)/oe.width)),ny:Math.max(0,Math.min(1,(ue-oe.top)/oe.height))}},Ne=(ae,ue,oe)=>{const de=c.current;if(!de)return;const Q=de.getBoundingClientRect(),ve=++g.current;p(le=>[...le,{id:ve,x:ae-Q.left,y:ue-Q.top,type:oe}]),setTimeout(()=>p(le=>le.filter(pe=>pe.id!==ve)),600)},q=(ae,ue,oe)=>{const de=d.current,Q=c.current;if(!de||!Q)return;const ve=de.getBoundingClientRect(),le=Q.getBoundingClientRect(),pe=de.naturalWidth||ve.width,ne=de.naturalHeight||ve.height,Ie=pe/ne,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 Ke=ve.left-le.left+Me+_e*ae,Ve=ve.top-le.top+Ae+H*ue,Xe=++g.current;p(Ye=>[...Ye,{id:Xe,x:Ke,y:Ve,type:oe}]),setTimeout(()=>p(Ye=>Ye.filter(tt=>tt.id!==Xe)),600)},ge=async ae=>{var oe;const ue=je(ae.clientX,ae.clientY);if(ue){u(`Click: ${Math.round(ue.nx*100)}%, ${Math.round(ue.ny*100)}%`),Ne(ae.clientX,ae.clientY,"left"),(oe=l.current)==null||oe.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}`)}}},he=async(ae,ue,oe,de=0)=>{try{await e("input_key",{type:oe?"char":"keyDown",key:ae,code:ue,text:oe?ae:void 0,unmodifiedText:oe?ae:void 0,modifiers:de})}catch(Q){t(`❌ Key error: ${Q.message||Q}`)}},we=async ae=>{if(ae.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ae.key)&&ae.preventDefault();let oe=0;ae.altKey&&(oe|=1),ae.ctrlKey&&(oe|=2),ae.metaKey&&(oe|=4),ae.shiftKey&&(oe|=8),u(`Key: ${ae.key}`),await he(ae.key,ae.code,ae.key.length===1,oe)},xe=async ae=>{if(ae.key==="Enter"){if(ae.nativeEvent.isComposing)return;if(f){const ue=f;x(""),u(`IME Sent: ${ue}`);try{const oe=await e("input_type",{text:ue});oe!=null&&oe.success||t(`❌ IME error: ${oe==null?void 0:oe.error}`)}catch(oe){t(`❌ IME error: ${oe.message}`)}}else u("Key: Enter"),await he("Enter","Enter",!1)}};i.useEffect(()=>{const ae=l.current;if(!ae)return;const ue=oe=>{var de;if((de=d.current)!=null&&de.contains(oe.target)){oe.preventDefault();const Q=Date.now();if(Q-I.current<40)return;I.current=Q;const ve=je(oe.clientX,oe.clientY);if(!ve)return;u(`Scroll: ${Math.round(oe.deltaY)}`),e("input_wheel",{nx:ve.nx,ny:ve.ny,deltaX:Math.round(oe.deltaX),deltaY:Math.round(oe.deltaY)}).catch(()=>{})}};return ae.addEventListener("wheel",ue,{passive:!1}),()=>ae.removeEventListener("wheel",ue)},[e]);const{cursorPos:Se,handleToggleInputMode:J,handleZoomReset:fe}=Pp({containerRef:l,viewportRef:c,imgRef:d,inputMode:A,setInputMode:T,minZoom:ee,zoomRef:E,panXRef:R,panYRef:$,setPanX:B,setPanY:C,setZoom:N,lastWheelTimeRef:I,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:q,clampPan:ce,isMobile:v,mobileFillZoom:S});return s.jsxs("div",{ref:l,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:we,onContextMenu:ae=>ae.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:[F?s.jsx("img",{ref:d,src:F,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${L}) translate(${P}%, ${D}%)`,transformOrigin:"center center",cursor:A==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:ge,onContextMenu:ae=>ae.preventDefault(),onDragStart:ae=>ae.preventDefault()}):s.jsx(Lp,{waitingLabel:me,waitingHint:ie,transportType:o}),A==="mouse"&&F&&s.jsx(Tp,{cursorPos:Se,viewportRef:c,imgRef:d}),b.map(ae=>{const oe={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ae.type];return s.jsxs("div",{style:{position:"absolute",left:ae.x,top:ae.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${oe}, 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(${oe}, 0.9)`,boxShadow:`0 0 12px rgba(${oe}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ae.id)})]}),s.jsx(_p,{inputMode:A,onToggleInputMode:J,isImeOpen:M,setIsImeOpen:j,isMenuOpen:y,setIsMenuOpen:h,imeText:f,setImeText:x,handleImeSubmit:xe,isConnActive:z,zoom:L,isMobile:v,mobileFillZoom:S,onZoomOut:()=>N(ae=>Math.max(.5,ae-.25)),onZoomReset:fe,onZoomIn:()=>N(ae=>Math.min(5,ae+.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 On(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 gc=e=>On(e);function Dp(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function Ys(e){const 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 Ep(e){const t=new Map,r=(n,a)=>{n&&t.set(n,{sessionId:n,...Dp(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 kn(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 Fn(e,t,r){const n=kn(e,t),a=Ys(e),o=a.isReconnecting,l=a.isConnecting,c=a.isGenerating,d=a.isWaiting,m=n.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=n.inboxBucket==="working"||c,x=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:x,requiresAction:m,isWorking:u,isReconnecting:o,isConnecting:l,isGenerating:c,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":x?"task_complete":"idle"}}function $p(e,t,r){return Fn(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function yc({activeConv:e,onModalButton:t}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Ys(e).isWaiting||!e.modalButtons)return null;const o=c=>{r||(n(c),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(Cr,{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),f=/^(reject|deny|delete|remove|abort)/.test(m),x=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":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!x?"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)"}:f?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:x?"⏳ ...":l(c)},d)})})]})]})}const Io="adhdev_controls_bar_visible",Xa="adhdev:controlsbarvisibilitychange";function na(e){if(!e)return!1;try{return e.getItem(Io)==="1"}catch{return!1}}function Bp(e,t){if(t)try{t.setItem(Io,e?"1":"0")}catch{}}function Op(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Xa,{detail:{visible:e}}))}function Mo(){const[e,t]=i.useState(()=>typeof window>"u"?!1:na(window.localStorage)),r=i.useRef(e),n=i.useCallback((l,c=!0)=>{r.current=l,t(l),typeof window<"u"&&Bp(l,window.localStorage),c&&Op(l)},[]);i.useEffect(()=>{const l=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:na(window.localStorage);r.current=u,t(u)},c=d=>{if(d.key!==Io)return;const m=na(window.localStorage);r.current=m,t(m)};return window.addEventListener(Xa,l),window.addEventListener("storage",c),()=>{window.removeEventListener(Xa,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 Fp=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Wp(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function vt(e,t){if(Wp(t==null?void 0:t.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":Fp.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 Sn(e){return vt(e)==="generating"}function Pi(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 Kp(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 aa(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Wn(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 Hp(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 Up(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function zp(e){return Hp(e.trim().replace(/\.local$/i,""))}function Vp(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function vc(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&&!Up(l));if(r&&r!=="Unknown")return zp(r);const n=t.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:t.fallbackLabel||"Machine"}function Tt(e,t={}){return Vp(e)||vc(e,t)}function wc(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 jc(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 Ss(e,t){return wc(e).join(" · ")}function Ir(e){return e.transport==="pty"}function Es(e){return e.transport==="acp"}function Gp(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 Di(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 qp(e,t=[],r=[]){var d,m,u,f;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(x=>Pi(x.status,{activeModal:x.activeModal})||Sn(x.status));if(a)return vt(a.status,{activeModal:a.activeModal});const o=r.find(x=>Pi(x.status,{activeModal:x.activeModal})||Sn(x.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:(f=r[0])==null?void 0:f.activeModal});return c!=="idle"?c:"idle"}function Yp(e){return vt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Xp(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 Jp(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 Qp(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&&Jp(t.receivedAt)||0}function Zp(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function Ja(e){return Math.max(Zp(e),Qp(e.activeChat))}function ef(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 Ao(e,t){return ef(Ja(e),Ja(t),Tt(e,{fallbackId:e.id}),Tt(t,{fallbackId:t.id}),e.id,t.id)}const kc="adhdev_notification_prefs",Ei={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function tf(){try{const e=localStorage.getItem(kc);if(e){const t=JSON.parse(e);return{...Ei,...t}}}catch{}return{...Ei}}function sf(e){try{localStorage.setItem(kc,JSON.stringify(e))}catch{}}let qt=tf(),ln=[];function rf(){ln.forEach(e=>e())}function nf(e){qt={...qt,...e},sf(qt),rf()}function af(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return ln.push(r),()=>{ln=ln.filter(n=>n!==r)}},[]);const t=i.useCallback(r=>{nf(r)},[]);return[{...qt},t]}function gr(e){if(!qt.globalEnabled)return!1;switch(e){case"disconnect":return qt.disconnectAlert;case"completion":return qt.completionAlert;case"approval":return qt.approvalAlert;case"browser":return qt.browserNotifications;default:return!0}}const of={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Sc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Nc(){return"Notification"in window&&Notification.permission==="granted"}let cs=null;function lf(e){return e!==!1}async function cf(){if(cs!==null)return cs;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return cs=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(cs=!!await e.pushManager.getSubscription(),cs):(cs=!1,!1)}catch{return cs=!1,!1}}function Qa(e,t,r){if(Nc())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 df(e,t={}){const r={...of,...t},n=i.useRef(new Map),a=i.useRef(0),[o,l]=i.useState(null);i.useEffect(()=>{let d=!1;return cf().then(m=>{d||l(m)}),()=>{d=!0}},[]);const c=i.useCallback((d,m,u)=>{const f=Date.now();f-a.current<r.throttleMs||(a.current=f,Qa(d,m,u))},[r.throttleMs]);i.useEffect(()=>{var d;if(!(!r.enabled||!Nc())&&gr("browser")&&!lf(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),f=vt(m.status,{activeModal:m.activeModal}),x=m.name||m.id;if(r.onApproval&&gr("approval")&&f==="waiting_approval"&&u!=="waiting_approval"){const w=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${x} — Approval needed`,w.slice(0,120),`approval-${m.id}`)}r.onComplete&&gr("completion")&&Sn(u)&&f==="idle"&&c(`✅ ${x} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&f==="error"&&u!=="error"&&c(`⚠️ ${x} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,f)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const uf=/^(run|approve|accept|yes|allow|always)/,mf=/^(run|approve|accept|yes|allow|always|proceed|save)/,pf=/^(reject|deny|delete|remove|abort|cancel|no)/;function To(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function ff(e){const t=To(e).toLowerCase();return uf.test(t)?"primary":pf.test(t)?"danger":"default"}function hf(e){return mf.test(To(e).toLowerCase())?"approve":"reject"}function xf(e){return e.map((t,r)=>({label:To(t),variant:ff(t),action:hf(t),button:t,buttonIndex:r}))}function bf(e,t,r){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function gf(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 yf{constructor(){Ze(this,"dedupMap",new Map);Ze(this,"DEDUP_WINDOW_MS",5e3);Ze(this,"DEDUP_MAX_SIZE",50);Ze(this,"DEDUP_CLEANUP_AGE_MS",1e4);Ze(this,"toastCallbacks",[]);Ze(this,"statusEventCallbacks",[]);Ze(this,"resolveActionFn",null);Ze(this,"viewRequestRespondFn",null);Ze(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 b;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 p of this.statusEventCallbacks)p(t);const d=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=lt(m);const f=this.resolveOwningDaemon(t);if(f){const p=Tt(f,{fallbackId:f.id});p&&(u=!m||m==="adhdev-daemon"?p:`${p}/${u}`)}let x="",w="info";if(t.event==="agent:generating_completed"){const p=t.duration?` (${t.duration}s)`:"";x=`✅ ${u} agent task completed${p}`,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(x=`⚡ ${u} approval needed`,w="warning",(b=t.modalButtons)!=null&&b.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(t);if(!p)return;const g=this.resolveActionFn,y=xf(t.modalButtons).map(j=>({label:j.label,variant:j.variant,onClick:()=>{g(p,"resolve_action",{action:j.action,button:j.button,buttonIndex:j.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),h=bf(u,t.modalMessage,x),M=Date.now();this.emitToast({id:M,message:h,type:w,timestamp:M,targetKey:n||p,actions:y,duration:15e3}),x=""}}else if(t.event==="monitor:long_generating"){const p=t.elapsedSec?` (${Math.round(t.elapsedSec/60)}m)`:"";x=`⚠️ ${u} agent is taking a long time${p}`,w="warning",gr("browser")&&!document.hasFocus()&&Qa(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const p=t.requesterName||"A team member",g=t.requestId,y=t.orgId;if(x=`👁️ ${p} wants to view your session`,w="warning",g&&y&&this.viewRequestRespondFn){const h=Date.now(),M=gf(y,g,this.viewRequestRespondFn,(j,v)=>console.error(`[EventManager] ${j} view request failed:`,v));this.emitToast({id:h,message:x,type:w,timestamp:h,actions:M,duration:3e4}),x=""}gr("browser")&&!document.hasFocus()&&Qa("👁️ View Request",`${p} wants to view your session`,`view-request-${g}`)}else t.event==="team:view_request_approved"?(x="✅ View request approved",w="success"):t.event==="team:view_request_rejected"&&(x=`❌ ${t.targetName||"Team member"} declined your view request`,w="warning");if(x){const p=Date.now();this.emitToast({id:p,message:x,type:w,timestamp:p,targetKey:n||t.daemonId,duration:5e3})}}}const ot=new yf,$i=new Map;function Nn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $s(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Kn(e){return Nn(e)?Nn(e.result)?e.result:e:null}function vf(e){const t=Kn(e);return!t||!Nn(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Vr(e){const t=Kn(e);return!t||!Nn(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function rr(e){const t=Kn(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Gr(e){const t=Kn(e);return!!t&&t.success===!1}function wf(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 jf(e,t){return e&&$s(e.currentValue)?e.currentValue:t}function kf(e,t){return $s(t)?$s(e)?typeof e=="string"&&e.trim()==="":!0:!1}function Sf(e,t){var o,l;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if($s(c))return c}const n=(o=t.controlValues)==null?void 0:o[e];if($s(n))return n;const a=(l=t.defaultValues)==null?void 0:l[e];return $s(a)?a:void 0}function cn(e,t){return e.options||t[e.id]||[]}const Nf={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 Cf(e,t,r){var n;return((n=Nf[t])==null?void 0:n.has(r.id))===!0}function _o(e,t){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!Cf(t.hostIdeType,t.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function oa(e,t){return{value:t}}function If(e,t,r){var a;return r?((a=cn(e,t).find(o=>o.value===r))==null?void 0:a.label)||r:""}const Mf={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function Af({routeId:e,sessionId:t,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:l}){const{sendCommand:c}=kt(),d=`${e}:${t||n}`,m=Mf[n]||"#94a3b8",[u,f]=i.useState({}),x=i.useRef({}),w=i.useRef(l);x.current=u,w.current=l;const b=i.useRef(0),p={};for(const I of o||[])I.defaultValue!==void 0&&(p[I.id]=I.defaultValue);const g={...p,...l||{},...Date.now()<b.current?u:{}};i.useEffect(()=>{l&&Date.now()>b.current&&f({})},[l]);const[y,h]=i.useState($i.get(d)||{}),[M,j]=i.useState(null),[v,A]=i.useState(null),T=i.useCallback(async(I,E={})=>{const R={...E,...t&&{targetSessionId:t}};return await c(e,I,R)},[e,t,c]),S=i.useCallback(async(I,E={})=>{const R=t?{targetSessionId:t}:{agentType:n,...r?{ideType:r}:{}};return await T("invoke_provider_script",{...R,scriptName:I,...E})},[T,n,r,t]),k=i.useCallback((I,E,R)=>{const $=jf(R,E);f(z=>({...z,[I.id]:$})),wf(R==null?void 0:R.effects)},[]),K=i.useCallback((I,E)=>{f(R=>{const $={...R};return E===void 0?delete $[I.id]:$[I.id]=E,$}),b.current=0},[]);if(!o||o.length===0)return null;const L=_o(o,{hostIdeType:r,providerType:n});if(L.length===0)return null;const N=async I=>{if(M===I.id){j(null);return}if(cn(I,y).length>0){j(I.id);return}if(I.dynamic&&I.listScript){A(I.id);try{const R=await S(I.listScript,{}),$=vf(R);if(!$){const me=rr(R);me&&ot.showToast(me,"warning");return}const z=$.options;h(me=>{const ie={...me,[I.id]:z};return $i.set(d,ie),ie});const F=Sf(I.id,{localOverrideUntil:b.current,localValues:x.current,controlValues:w.current,defaultValues:p});if(kf(F,$.currentValue)){const me=$.currentValue;f(ie=>({...ie,[I.id]:me}))}j(I.id)}catch(R){const $=R instanceof Error?R.message:`Could not load ${I.label}`;ot.showToast($,"warning")}finally{A(null)}}},P=async(I,E)=>{j(null);const R=(l==null?void 0:l[I.id])??p[I.id];f($=>({...$,[I.id]:E})),b.current=Date.now()+5e3;try{if(!I.setScript)return;const $=await S(I.setScript,oa(I,E)),z=Vr($);if(z&&!z.ok||Gr($))throw new Error((z==null?void 0:z.error)||rr($)||`Could not update ${I.label}`);k(I,E,z)}catch($){K(I,R);const z=$ instanceof Error?$.message:`Could not update ${I.label}`;ot.showToast(z,"warning")}},B=async I=>{const E=cn(I,y).map(ie=>ie.value);if(E.length===0)return;const R=String(g[I.id]||""),z=(E.indexOf(R)+1)%E.length,F=E[z];if(typeof F!="string")return;const me=(l==null?void 0:l[I.id])??p[I.id];f(ie=>({...ie,[I.id]:F})),b.current=Date.now()+5e3;try{if(!I.setScript)return;const ie=await S(I.setScript,oa(I,F)),ee=Vr(ie);if(ee&&!ee.ok||Gr(ie))throw new Error((ee==null?void 0:ee.error)||rr(ie)||`Could not update ${I.label}`);k(I,F,ee)}catch(ie){K(I,me);const ee=ie instanceof Error?ie.message:`Could not update ${I.label}`;ot.showToast(ee,"warning")}},D=async I=>{const R=!g[I.id],$=(l==null?void 0:l[I.id])??p[I.id];f(z=>({...z,[I.id]:R})),b.current=Date.now()+5e3;try{if(!I.setScript)return;const z=await S(I.setScript,oa(I,R)),F=Vr(z);if(F&&!F.ok||Gr(z))throw new Error((F==null?void 0:F.error)||rr(z)||`Could not update ${I.label}`);k(I,R,F)}catch(z){K(I,$);const F=z instanceof Error?z.message:`Could not update ${I.label}`;ot.showToast(F,"warning")}},C=async I=>{if(!I.invokeScript)return;if(I.confirmMessage){const R=[I.confirmTitle,I.confirmMessage,I.confirmLabel].filter(z=>typeof z=="string"&&z.trim().length>0);if(!window.confirm(R.join(`
|
|
30
|
+
|
|
31
|
+
`)))return}const E=(l==null?void 0:l[I.id])??p[I.id];try{const R=await S(I.invokeScript),$=Vr(R);if($&&!$.ok||Gr(R))throw new Error(($==null?void 0:$.error)||rr(R)||`Could not run ${I.label}`);$&&k(I,E??!0,$)}catch(R){K(I,E);const $=R instanceof Error?R.message:`Could not run ${I.label}`;ot.showToast($,"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(I=>{const E=String(g[I.id]||""),R=If(I,y,E),$=M===I.id,z=v===I.id,F=cn(I,y),me="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(I.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${me} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${m}55`:"var(--border-default)",background:$?`${m}10`:"var(--surface-tertiary)",color:E?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void N(I),title:I.label,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z?"Loading…":R||I.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),$&&F.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>j(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:I.label}),F.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===E?`${m}14`:"transparent",color:ie.value===E?"var(--text-primary)":"var(--text-secondary)",borderLeft:ie.value===E?`2px solid ${m}`:"2px solid transparent"},title:ie.description||ie.label,onMouseEnter:ee=>{ee.currentTarget.style.background=`${m}10`},onMouseLeave:ee=>{ee.currentTarget.style.background=ie.value===E?`${m}14`:"transparent"},onClick:()=>void P(I,ie.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:ie.label}),ie.value===E&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},ie.value))]})]})]},I.id);case"cycle":return s.jsxs("button",{type:"button",className:`${me} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:E?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void B(I),title:`Click to cycle: ${F.map(ie=>ie.label).join(" → ")}`,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:R||I.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},I.id);case"toggle":return s.jsxs("button",{type:"button",className:`${me} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:E?`${m}44`:"var(--border-default)",background:E?`${m}14`:"var(--surface-tertiary)",color:E?m:"var(--text-muted)"},onClick:()=>void D(I),"aria-pressed":!!E,children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),I.label]},I.id);case"action":return s.jsxs("button",{type:"button",className:`${me} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void C(I),children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:I.resultDisplay==="inline"&&E?`${I.label}: ${E}`:I.label})]},I.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:E?"var(--text-primary)":"var(--text-muted)"},children:[I.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:I.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:E?`${I.label}: ${E}`:I.label})]},I.id);default:return null}})]})})}function Tf({isActive:e=!0,isCliTerminal:t=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:c,controlValues:d}){const{isVisible:m}=Mo(),u=_o(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(Af,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:u,controlValues:d})})}const nr=5,Cc=10*1024*1024;function _f({hasDraft:e,isBusy:t=!1}){return!e||t}function Lf(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 Rf(e){if(e.size>Cc)return null;const t=await Lf(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 Pf(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Ic=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:f}){const x=i.useRef(null),w=i.useRef(null),[b,p]=i.useState(""),[g,y]=i.useState([]),[h,M]=i.useState(null),[j,v]=i.useState(!1),A=i.useRef(!1),{isVisible:T,toggleVisibility:S}=Mo(),k=Pf(f),K=!!b.trim()||g.length>0;i.useEffect(()=>{p(""),y([]),M(null)},[t]),i.useEffect(()=>{var I;c&&((I=x.current)==null||I.focus({preventScroll:!0}))},[t,c]);const L=i.useCallback(async I=>{M(null);const E=Array.from(I).filter(ie=>ie.type.startsWith("image/"));if(E.length===0)return;const R=nr-g.length;if(R<=0){M(`Max ${nr} images`);return}const $=E.slice(0,R);if($.filter(ie=>ie.size>Cc).length>0){M("Image too large (max 10 MB)");return}const me=(await Promise.all($.map(Rf))).filter(ie=>ie!==null);y(ie=>[...ie,...me])},[g.length]),N=i.useCallback(I=>{y(E=>E.filter((R,$)=>$!==I))},[]),P=i.useCallback(async()=>{const I=b.trim();if(!I&&g.length===0||a||A.current)return;A.current=!0;const E=g.length>0?[...g]:void 0;try{await l(I,E)!==!1&&(p(""),y([]),M(null))}finally{A.current=!1}},[b,g,a,l]),B=i.useCallback(I=>{k&&(I.preventDefault(),v(!0))},[k]),D=i.useCallback(()=>v(!1),[]),C=i.useCallback(I=>{k&&(I.preventDefault(),v(!1),I.dataTransfer.files.length>0&&L(I.dataTransfer.files))},[k,L]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",j?"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:B,onDragLeave:D,onDrop:C,children:[g.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:g.map((I,E)=>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:I.previewUrl,alt:I.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>N(E),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 ${I.name}`,children:"✕"})]},E))}),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:()=>{S(),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"})]})}),k&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:w,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:I=>{I.target.files&&L(I.target.files),I.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var I;return(I=w.current)==null?void 0:I.click()},disabled:g.length>=nr,title:g.length>=nr?`Max ${nr} 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:x,type:"text",placeholder:o||(k&&g.length>0?"Add a message (optional)...":`Send message to ${r}...`),value:b,onChange:I=>p(I.target.value),onPaste:I=>{if(k&&I.clipboardData.files.length>0&&Array.from(I.clipboardData.files).some($=>$.type.startsWith("image/"))){I.preventDefault(),L(I.clipboardData.files);return}const E=I.clipboardData.getData("text");E&&p(R=>R+E),I.preventDefault()},onKeyDown:I=>{if(I.key==="Enter"){if(I.nativeEvent.isComposing){I.preventDefault();return}I.preventDefault(),P()}},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:()=>{P()},disabled:_f({hasDraft:K,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${K&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:K&&!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:K?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(h||k&&j)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${h?"text-red-400":"text-[var(--accent-primary)]"}`,children:h||"Drop image here"}),o&&!h&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})}),at=e=>e.transport==="pty",Xs=(e,t)=>at(e)?e.mode||"terminal":"chat",Mc=(e,t)=>at(e)&&Xs(e)==="terminal",st=e=>e.transport==="acp",Df=180;function os(e){return e.streamSource!=="agent-stream"}function Ms(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Ac(e){return e.machineName||""}function Lr(e){return Ms(e)}function zt(e){return e.agentType||""}function Cn(e){return e.hostIdeType||""}function Lo(e){return e.displayPrimary||e.agentName||"Agent"}function Tc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Ef(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function _c(e){const t=Ef(e),r=Fs(t==null?void 0:t.content),n=Fs(e.lastMessagePreview);return r||n||""}function $f(e,t=Df){const r=Fs(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 Bf(e){return $f(_c(e)||e.displaySecondary||"")}function Lc(e){return[e.displaySecondary,Ac(e)].filter(Boolean)}function Ks(e){return e.agentName||lt(zt(e))}function Of(e){var t,r;if(!os(e)){const n=(r=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:r.trim();if(n)return n}return lt(Cn(e)||zt(e))}function Rc(e){return os(e)?e.sessionId:e.nativeSessionId}function Bi(e){return os(e)?"native":e.tabKey}function Ff(e){return e.sessionId}function Wf(e,t){if(t)return os(e)||!t.childSessions?t:t.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||t}function Kf(e,t){const r=zt(e),n=os(e),a=at(e)||st(e),o=n?a?Ks(e)||(t==null?void 0:t.cliName)||lt(Cn(e)||r):t!=null&&t.type?lt(t.type):lt(Cn(e)||r):Ks(e);return{isNativeConversation:n,isCli:at(e),isAcp:st(e),isCliTerminal:Mc(e),providerType:r,displayLabel:o,targetEntry:Wf(e,t)}}function fs(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:at(e)||st(e)?{agentType:zt(e)}:e.streamSource==="agent-stream"?{agentType:zt(e)}:t}function Hs(e){return e?Lr(e):""}function ar(e,t){e(r=>[...r,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Ro(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Hf(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 Pc(){return"select_session"}function Uf(){return"open_panel"}function zf({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function Vf(e,t,r=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<r:!1}function Oi(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function In(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Po(e){return e instanceof Error?e.message:String(e||"")}function Fi(e){const t=Po(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function Wi(e,t){const r=Po(t);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Gf(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 Hn({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),f=i.useRef(null);i.useEffect(()=>{m(null)},[t==null?void 0:t.tabKey]);const x=i.useCallback(async(g,y)=>{if(!t||u.current)return!1;const h=g.trim(),M=Ro(t);if(zf({hasMessage:!!h,blockedMessage:M,sendInFlight:u.current}))return M&&m(M),!1;const j=Date.now(),v={tabKey:t.tabKey,message:h,timestamp:j};if(Vf(f.current,v))return m(null),!0;u.current=!0,c(!0),m(null),f.current=v;try{const A=Hs(t);if(!A)return f.current=Oi(f.current,v),m("Unable to send message right now."),!1;const T=await e(A,"send_chat",Gf(h,y,t)),S=In(T);if(S!=null&&S.deduplicated)return m(null),!0;if((S==null?void 0:S.sent)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Send failed");return m(null),!0}catch(A){const T=Po(A);return T.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",T):console.warn("Send blocked/failed",A),f.current=Oi(f.current,v),m(Hf(A)),!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]),b=i.useCallback(async g=>{if(t)try{const h=(t.modalButtons||[]).indexOf(g),M=g.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),j=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(M),v=Hs(t);if(!v)return;const A=await e(v,"resolve_action",{button:g,action:j?"approve":"reject",...h>=0&&{buttonIndex:h},...fs(t)}),T=In(A);T.success||r(S=>[...S,{routeId:t.tabKey,text:Wi(g,T==null?void 0:T.error),timestamp:Date.now()}])}catch(y){Fi(y)||console.error("[ModalButton] Error:",y),r(h=>[...h,{routeId:t.tabKey,text:Fi(y)?Wi(g,y):`❌ **${g}** error`,timestamp:Date.now()}])}},[t,e,r]),p=i.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,Uf(),{...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:x,handleRelaunch:w,handleModalButton:b,handleFocusAgent:p}}const qf=10,Yf=8e3,Xf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function Jf(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 Za(e,t="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Xf.test(t)&&e.trim())return"[REDACTED:secret-field]";const n=Jf(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=>Za(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,Za(a,n,r+1)]))}function or(e,t){return Array.isArray(e)?e.slice(-t):[]}function Qf(e,t=Date.now()){const r=e&&t-e.firstAt<=Yf,n=r?e.count+1:1;return n>=qf?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:t},shouldCollect:!1}}function Dc(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:or(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:or(t.messages,10),visibleMessagesTail:or(e.visibleMessages,5),historyMessagesTail:or(e.chatTailState.historyMessages,5),actionLogsTail:or(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 Za(r)}function Ec(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 $c(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 Bc(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 ia(e,t){return`${e}:${t}`}function Zf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function ir(e,t){Zf()&&console.debug(`[subscription-manager] ${e}`,t)}class eh{constructor(){Ze(this,"active",new Map);Ze(this,"retryTimers",new Map)}subscribe(t,r,n,a,o){var u;const l=ia(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 f={daemonId:r,request:n,handlers:new Set([a])};this.active.set(l,f),ir("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 f=this.active.get(l);if(!f||(f.handlers.delete(a),f.handlers.size>0))return;this.active.delete(l);const x={type:"unsubscribe",topic:n.topic,key:n.key};ir("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(w=t.sendData)==null||w.call(t,r,x)};return m.initialSendAccepted=d,m}publish(t){const r=ia(t.topic,t.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=t,Os.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),Os.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=ia(t,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(t){var r;ir("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);ir("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;ir("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 Xt=new eh;function th(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 sh(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 la(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function rh(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function nh(e){rh()&&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 Mn(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}=sh(d),f=th(o,n),x=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"),b=m.filter(g=>g.kind==="agent"&&g.transport==="pty"),p=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},...x&&{machine:x,platform:x.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=f.get(g.id),h=fr(g,y),M=(u.get(g.id)||[]).map(j=>fr(j,f.get(j.id)));r.push({id:`${n}:ide:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,status:h.cdpConnected?"online":"detected",daemonId:n,instanceId:la(n,g.id),workspace:h.workspace,terminals:0,childSessions:M,agents:M.map(j=>({id:j.id,name:j.providerName||j.providerType,type:j.providerType,status:j.status})),activeChat:h.activeChat,chats:[],cdpConnected:h.cdpConnected,...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},...h.messageInput!==void 0&&{messageInput:h.messageInput},timestamp:c})}for(const g of b){const y=f.get(g.id),h=fr(g,y);r.push({id:`${n}:cli:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:la(n,g.id),cliName:h.providerName||h.providerType,mode:h.mode||(y==null?void 0:y.mode)||"terminal",workspace:h.workspace||"",activeChat:h.activeChat,...h.resume!==void 0&&{resume:h.resume},...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},...h.messageInput!==void 0&&{messageInput:h.messageInput},timestamp:c,_isCli:!0})}for(const g of p){const y=f.get(g.id),h=fr(g,y);r.push({id:`${n}:acp:${g.id}`,sessionId:g.id,providerSessionId:g.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:h.parentId,sessionKind:h.kind,transport:h.transport,sessionCapabilities:h.capabilities,type:h.providerType,agentType:h.providerType,status:h.status||"running",daemonId:n,instanceId:la(n,g.id),cliName:h.providerName||h.providerType,mode:"chat",workspace:h.workspace||"",activeChat:h.activeChat,...h.runtimeKey!==void 0&&{runtimeKey:h.runtimeKey},...h.runtimeDisplayName!==void 0&&{runtimeDisplayName:h.runtimeDisplayName},...h.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:h.runtimeWorkspaceLabel},...h.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:h.runtimeWriteOwner},...h.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:h.runtimeAttachedClients},...h.lastMessagePreview!==void 0&&{lastMessagePreview:h.lastMessagePreview},...h.lastMessageRole!==void 0&&{lastMessageRole:h.lastMessageRole},...h.lastMessageAt!==void 0&&{lastMessageAt:h.lastMessageAt},...h.lastMessageHash!==void 0&&{lastMessageHash:h.lastMessageHash},lastUpdated:h.lastUpdated,unread:h.unread,lastSeenAt:h.lastSeenAt,inboxBucket:h.inboxBucket,completionMarker:h.completionMarker,seenCompletionMarker:h.seenCompletionMarker,surfaceHidden:h.surfaceHidden,...h.controlValues!==void 0&&{controlValues:h.controlValues},...h.providerControls!==void 0&&{providerControls:h.providerControls},...h.summaryMetadata!==void 0&&{summaryMetadata:h.summaryMetadata},...h.settings!==void 0&&{settings:h.settings},...h.messageInput!==void 0&&{messageInput:h.messageInput},timestamp:c,_isAcp:!0})}return nh(r),r}const ah=15e3,oh=15e3,ih=6e4,lh=1200,Ki=12,ch=8e3,dh=4e3,ca=new Map,da=new Map,qr=new Set,yr=new Map;function uh(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 Hi(e,t){const r=yr.get(e);!r||r.size===0||(yr.delete(e),r.forEach(n=>n(t)))}function mh(e,t){return new Promise(r=>{const n=yr.get(e)||new Set;yr.set(e,n);const a=l=>{clearTimeout(o),n.delete(a),n.size===0&&yr.delete(e),r(l)},o=setTimeout(()=>a(!1),t);n.add(a)})}function Rr(){const{sendCommand:e,sendData:t}=kt(),{injectEntries:r,getIdes:n}=Nr();return i.useCallback(async(a,o)=>{if(!a)return;const l=(o==null?void 0:o.minFreshMs)??ih,c=da.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=ca.get(a);if(d)return d;const m=(async()=>{if(t&&!qr.has(a)){const p=Xt.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},g=>{const y=n(),h=y.find(j=>j.id===a),M=Mn(g.status,{daemonId:a,existingDaemon:h,existingEntries:y,timestamp:g.timestamp});M.length>0&&r(M),da.set(a,Date.now()),Hi(a,!0)});if(p.initialSendAccepted?qr.add(a):qr.delete(a),!(o!=null&&o.force)&&p.initialSendAccepted&&await mh(a,lh))return}const u=await e(a,"get_status_metadata"),f=uh(u);if(!f)return;const x=n(),w=x.find(p=>p.id===a),b=Mn(f,{daemonId:a,existingDaemon:w,existingEntries:x,timestamp:f.timestamp||Date.now()});b.length>0&&r(b,{authoritativeDaemonIds:[a]}),da.set(a,Date.now()),Hi(a,!0)})().finally(()=>{ca.delete(a)});return ca.set(a,m),m},[n,r,e,t])}function ph(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}const fh=60,hh=50;function Oc(e={}){return e.isCliLike?hh:fh}function xh(e={}){return Oc(e)}function It(e){return(typeof e=="string"?e.trim():"")||void 0}function Yt(e,t){const r=It(t);return r?`${e}:${r}`:void 0}function ns(e,t,r){const n=Yt(t,r),a=It(r);n&&e.push(n),a&&e.push(a)}function Ps(e){const t=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),t.push(n));return t}function Fc(e){return It(e.providerSessionId)||It(e.sessionId)||It(e.tabKey)||It(e.routeId)}function Do(e){return Ps([It(e.providerSessionId),It(e.sessionId)])}function Bs(e){const t=[];return ns(t,"provider",e.providerSessionId),ns(t,"session",e.sessionId),ns(t,"tab",e.tabKey),ns(t,"route",e.routeId),Ps(t)}function bh(e){const t=[];return It(e.providerSessionId)?(ns(t,"provider",e.providerSessionId),Ps(t)):It(e.sessionId)?(ns(t,"session",e.sessionId),Ps(t)):It(e.tabKey)?(ns(t,"tab",e.tabKey),Ps(t)):It(e.routeId)?(ns(t,"route",e.routeId),Ps(t)):[]}function Eo(e){return Yt("provider",e.providerSessionId)||Yt("session",e.sessionId)||Yt("tab",e.tabKey)||Yt("route",e.routeId)||"unknown:"}function Pr(e){return Do(e)[0]}function gh(e){const t=It(e.providerSessionId),r=It(e.sessionId),n=It(e.tabKey),a=It(e.routeId),o=[Yt("provider",t),Yt("session",r),Yt("tab",n),Yt("route",a)].filter(d=>typeof d=="string"),l=Bs({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),c=Eo({providerSessionId:t,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:t,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:Fc({providerSessionId:t,sessionId:r,tabKey:n,routeId:a}),historySessionId:Pr({providerSessionId:t,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:l}}function eo(e,t){const r=gh(e);return bh(t).some(n=>r.lookupKeys.includes(n))}const Dr=60,yh=1e3,$o=12e4,vh=new Set(["generating","waiting_approval","starting","streaming","working"]),Ui=new Map;function Wc(e,t){return`${e}::${t}`}function to(e=Dr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:wh([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function wh(e,t=Dr){return{tailLimit:t}}function zi(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 jh{constructor(t){Ze(this,"manager");Ze(this,"sendData");Ze(this,"daemonId");Ze(this,"sessionId");Ze(this,"historySessionId");Ze(this,"subscriptionKey");Ze(this,"fallbackRecentCount");Ze(this,"snapshot");Ze(this,"transportSubscription",null);Ze(this,"listeners",new Set);Ze(this,"retainCount",0);Ze(this,"loadHistoryPromise",null);Ze(this,"pendingDisconnectTimer",null);this.manager=t.manager||Xt,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=to(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:yh}))}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};zi(this.snapshot.liveMessages)===zi(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:n},this.emit())}}function Kc(e){const t=Wc(e.daemonId,e.sessionId),r=Ui.get(t);if(r)return r.updateOptions(e),r;const n=new jh(e);return Ui.set(t,n),n}function kh(e,t){return{...e,loadHistoryPage:t}}function Sh(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||e.historySessionId.localeCompare(t.historySessionId)}function Nh(e,t={}){const r=String(e.status||"").trim().toLowerCase();if(vh.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??$o)),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 Ch(e=$o){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Ih(e,t={}){const r=new Set,n=[];for(const a of e){if(!Nh(a,t))continue;const o=Lr(a),l=a.sessionId||"";if(!o||!l)continue;const c=Wc(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(Sh),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function Mh(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:Kc({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]),[f,x]=i.useState(()=>(u==null?void 0:u.getSnapshot())||to(m));i.useEffect(()=>{if(!u){x(to(m));return}u.retain(),x(u.getSnapshot());const b=u.subscribe(p=>{x(p)});return()=>{b(),u.release()}},[u,m]);const w=i.useCallback(async()=>{!u||!o||!l||await u.loadHistoryPage(async({offset:b,excludeRecentCount:p})=>{const g=e.agentType,y=await n(o,"chat_history",{agentType:g,offset:b,limit:30,targetSessionId:l,historySessionId:c,excludeRecentCount:p}),h=y&&typeof y=="object"&&"result"in y?y.result||{}:y||{};return{messages:Array.isArray(h.messages)?h.messages:[],hasMore:h.hasMore===!0}})},[e.agentType,u,o,c,n,l]);return i.useMemo(()=>kh(f,w),[w,f])}function Ah(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)??$o)),l=Ch(o),[c,d]=i.useState(0);i.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(f=>f+1)},l);return()=>{clearInterval(u)}},[e.length,n,l]);const m=i.useMemo(()=>Ih(e,{recentActivityMs:o}),[e,o,c]);i.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(f=>Kc({...f,sendData:r,tailLimit:a}));return u.forEach(f=>{f.retain()}),()=>{u.forEach(f=>f.release())}},[m.signature,n,r,a])}function Th(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Vi(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 _h(e,t){if(e.length===0)return[];if(t.some(Vi))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const o=e[a];if(!o||!Vi(o))continue;const l=String(o.role||"").toLowerCase();n.has(l)||(n.add(l),r.unshift(o))}return r}function Lh(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=_h(o,l),d=c.length>0?[...c,...l]:l;return t.length===0?d:[...t,...d]}function Rh(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Ph(e){return Rh(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Dh(e,t,r=`${t}s`){return`${e} ${e===1?t:r}`}function Eh(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function $h(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Hc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function Uc(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 Bh(e){return Hc(e)?!1:e.inboxBucket==="task_complete"&&Uc(e).length>0}function Gi(e){return e.branch||"detached HEAD"}function Oh(e){if(e.error)return`${Gi(e)} · Git error: ${e.error}`;const t=[Gi(e)];return e.changedFiles>0?t.push(Dh(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 Fh(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Oh(t)}`}function Wh(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function Kh(e,t={}){if(t.enabled===!1)return[];if(!$h(e))return[];const r=Hc(e)?"working":Bh(e)?"complete":null;if(!r)return[];const n=r==="complete"?Uc(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Eh(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:Fh(r,e.git),timestamp:Wh(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 Hh=60;function so({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:f=!0}){var Se,J,fe,ae,ue,oe,de;const x=i.useRef(new Map),w=i.useRef(void 0),b=Rr(),{sendCommand:p}=kt(),{isVisible:g}=Mo();_r("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const y=St.useMemo(()=>Ys(e),[e.status,e.connectionState]),h=i.useMemo(()=>Kf(e,t),[e,t]),M=i.useMemo(()=>{var Q;return _o((Q=h.targetEntry)==null?void 0:Q.providerControls,{hostIdeType:e.hostIdeType,providerType:h.providerType})},[e.hostIdeType,h.providerType,(Se=h.targetEntry)==null?void 0:Se.providerControls]),j=Oc({isCliLike:h.isCli||h.isAcp}),v=xh({isCliLike:h.isCli||h.isAcp}),A=Mh(e,{enabled:f&&!!e.sessionId,tailLimit:v}),[T,S]=i.useState(j),[k,K]=i.useState(()=>Ii()),L=e.tabKey,N=A.historyMessages,P=A.hasMoreHistory,B=A.historyError,D=Th(e,A),C=uc(D).length;i.useEffect(()=>{S(j)},[j,L]);const I=Math.max(0,D.length-T),E=Lo(e),R=Lr(e),$=Ph(e),z=Ro(e),F=a||z,me=!!z,[ie,ee]=i.useState(!1);i.useEffect(()=>{const Q=h.targetEntry;R&&(!Q||Q.providerControls===void 0||Q.controlValues===void 0)&&b(R,{minFreshMs:3e4}).catch(()=>{})},[R,h.isAcp,(J=h.targetEntry)==null?void 0:J.providerControls,(fe=h.targetEntry)==null?void 0:fe.controlValues,b]);const ce=i.useCallback(async()=>{if(!ie){if(D.length>T){S(Q=>Math.min(D.length,Q+Hh));return}ee(!0);try{await A.loadHistoryPage()}finally{ee(!1)}}},[A,ie,D.length,T]),{allMessages:je,receivedAtMap:Ne}=i.useMemo(()=>{const Q=Lh({historyMessages:N,liveMessages:D,visibleLiveCount:T}),ve=Kh(e),le=ve.length>0?[...Q,...ve]:Q,pe={};return le.forEach((ne,Ie)=>{const Ce=`${e.tabKey}:${jn(ne,Ie)}`;let _e=ph(ne)||x.current.get(Ce)||0;_e||(_e=Date.now(),x.current.set(Ce,_e)),pe[jn(ne,Ie)]=_e}),{allMessages:le,receivedAtMap:pe}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,I,N,D,T]),q=i.useMemo(()=>c.filter(Q=>Q.routeId===e.tabKey).sort((Q,ve)=>Q.timestamp-ve.timestamp),[c,e.tabKey]),ge=i.useCallback(async()=>{var Ie,Ce;if(!R)return;const Q=Dc({activeConv:e,visibleMessages:je,actionLogs:c,controls:(Ie=h.targetEntry)==null?void 0:Ie.providerControls,controlValues:(Ce=h.targetEntry)==null?void 0:Ce.controlValues,visibleBarControlCount:M.length,chatTailState:{liveMessages:A.liveMessages,hasLiveSnapshot:A.hasLiveSnapshot,hasMoreHistory:P,historyError:B,historyMessages:N},ui:{controlsVisible:g,visibleLiveCount:T,activityVisible:k,activityCount:C,hiddenLiveCount:I,isInputActive:u,isVisible:f}}),ve=await p(R,"get_chat_debug_bundle",{agentType:h.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:Q}),le=In(ve),pe=Bc(le),ne=await $c(pe);ne==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ot.showToast(Ec(le,{locatorCopyStatus:ne}),ne==="failed"?"warning":"success")},[e,c,C,je,g,A.hasLiveSnapshot,A.liveMessages,h.providerType,(ae=h.targetEntry)==null?void 0:ae.controlValues,(ue=h.targetEntry)==null?void 0:ue.providerControls,R,P,I,N,u,f,B,p,k,M.length,T]),he=i.useCallback(()=>{K(Q=>{const ve=!Q;return up(ve),ve})},[]);i.useEffect(()=>{const Q=ve=>{ve.key===So&&K(Ii())};return window.addEventListener("storage",Q),()=>window.removeEventListener("storage",Q)},[]);const we=i.useCallback(()=>{const Q=Qf(w.current);w.current=Q.state,Q.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(D.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")&&ee(!1),e.status==="not_monitored"&&$)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(Ws,{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(ks,{size:14})," Open ",E," 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"&&$)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(ic,{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(ks,{size:14})," Open ",E," 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!P&&N.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,$,o,P,N.length,l,ie,D.length,E,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 ${k?"chat-activity-toggle-active":""}`,onClick:he,"aria-pressed":k,title:"Show tool, terminal, and runtime activity rows",children:[s.jsx("span",{className:"chat-activity-toggle-dot"}),"Activity",C>0&&s.jsx("span",{className:"chat-activity-toggle-count",children:C})]})}),s.jsx(Cp,{messages:je,actionLogs:q,agentName:Ks(e)||E||"Agent",userName:d,isCliMode:h.isCli||h.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:Ne,lastMessageHash:e.lastMessageHash,showActivityMessages:k,onLoadMore:ce,isLoadingMore:ie,hasMoreHistory:P,hiddenLiveCount:I,loadError:B??void 0,emptyState:xe,scrollToBottomRequestNonce:m,isVisible:f}),s.jsx(Tf,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:h.providerType,displayLabel:h.displayLabel,controls:(oe=h.targetEntry)==null?void 0:oe.providerControls,controlValues:(de=h.targetEntry)==null?void 0:de.controlValues,isActive:u,isCliTerminal:h.isCliTerminal}),!h.isCliTerminal&&s.jsx(Ic,{contextKey:e.tabKey,panelLabel:E,isSending:n,isBusy:me,statusMessage:F,onSend:r,isActive:u,showControlsToggle:M.length>0,onControlsToggle:we,messageInput:e.messageInput})]})}let zc=ls;function Vc(){return zc()}class Uh{constructor(){Ze(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 Gc=new Uh;class zh{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 ft=new zh;function Vh(e){e.dashboardWS&&(Gc=e.dashboardWS),e.connectionManager&&(ft=e.connectionManager),e.useDaemonsHook&&(zc=e.useDaemonsHook)}const Gh=.5,qh=1.25;function ut(e){return Lo(e)}function Ns(e){return Lc(e).join(" · ")}function qc(e){const t=_c(e);return t||(e.title?e.title:Ns(e)||"No messages yet")}function Yc(e,t){const{isReconnecting:r,isConnecting:n}=Ys(e);return r?"Reconnecting…":n?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function Yh(e,t){const r=["Chat",...Lc(e)];return t!=null&&t.timestampLabel&&r.push(t.timestampLabel),r.filter(Boolean).join(" · ")}function hs(e){return Yc(e)||Ns(e)}function Xh(e){return`${ut(e)} · ${qc(e)}`}function Jh(e){const t=Cn(e),r=t?lt(t):Ks(e);return`${ut(e)} — ${r||"Agent"}`}function Qh(e){return Ks(e)||"CLI"}function Xc(e){return Tc(e)}function Jc(e){return e?`Remote · ${ut(e)||e.workspaceName||"Session"}`:"Remote"}function Zh({activeConv:e,clearToken:t=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:l=!0,isInputActive:c=!0}){var se;ls();const{sendPtyInput:d}=kt(),[m,u]=i.useState(!1),f=i.useRef(!1);f.current=m;const[x,w]=i.useState("Runtime terminal unavailable"),[b,p]=i.useState(!1),[g,y]=i.useState(null),[h,M]=i.useState(!1),[j,v]=i.useState(!1),[A,T]=i.useState(1),[S,k]=i.useState(!1),[K,L]=i.useState({width:0,height:0}),[N,P]=i.useState({width:0,height:0}),[B,D]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[C,I]=i.useState(null),E=i.useRef(null),R=i.useRef(null),$=i.useRef(!1),z=i.useRef(!1),F=i.useRef(l),me=i.useRef(0),ie=i.useRef(!1),ee=i.useRef(""),ce=i.useRef(null),je=i.useRef(!1),Ne=i.useRef(!1),q=i.useRef(null),ge=i.useRef(null),he=i.useRef(null),we=32*1024,xe=()=>{var W,G,te,re;return((G=(W=E.current)==null?void 0:W.ownerDocument)==null?void 0:G.defaultView)||((re=(te=R.current)==null?void 0:te.ownerDocument)==null?void 0:re.defaultView)||window},Se=W=>{const G=xe();return{ownerWindow:G,frameId:G.requestAnimationFrame(W)}},J=()=>{const W=q.current;if(W){try{W.ownerWindow.cancelAnimationFrame(W.frameId)}catch{}q.current=null}},fe=()=>{const W=ge.current;if(W){try{W.ownerWindow.clearTimeout(W.timeoutId)}catch{}ge.current=null}},ae=()=>{const W=he.current;if(W){try{W.ownerWindow.clearTimeout(W.timeoutId)}catch{}he.current=null}},ue=()=>{l&&q.current===null&&(q.current=Se(()=>{tt()}))},oe=e.tabKey,de=e.sessionId||"",Q=e.daemonId||((se=e.routeId)==null?void 0:se.split(":")[0])||e.routeId||"",ve=Ro(e),le=m?o||ve:x,pe=Gh,ne=qh,Ie=.05,Ce=()=>{const W=N.width,G=N.height;if(!Number.isFinite(K.width)||K.width<=0||!Number.isFinite(K.height)||K.height<=0||!Number.isFinite(W)||W<=0||!Number.isFinite(G)||G<=0)return 1;const te=K.width/W,re=K.height/G;return Number(Math.min(ne,Math.max(pe,Math.min(te,re))).toFixed(2))},_e=Ce(),H=$.current&&A>_e,Me=Number.isFinite(N.width)&&N.width>0?Math.max(K.width,Math.round(N.width*A)):K.width,Ae=Number.isFinite(N.height)&&N.height>0?Math.max(K.height,Math.round(N.height*A)):K.height,Ke=()=>{Se(()=>{const W=R.current;W&&(W.scrollLeft=0,W.scrollTop=W.scrollHeight-W.clientHeight)})},Ve=()=>{var W,G;me.current=0,ie.current=!1,ee.current="",ce.current=null,je.current=!1,Ne.current=!1,$.current||(z.current=!1,T(1)),q.current!==null&&J(),u(!1),w("Runtime terminal unavailable"),ae(),fe(),y(null),I(null),k(!1),p(!1),M(!1),v(!1),(G=(W=r.current)==null?void 0:W.reset)==null||G.call(W)},Xe=()=>{var W,G;me.current=0,ie.current=!1,ee.current="",ce.current=null,je.current=!1,Ne.current=!1,q.current!==null&&J(),u(!0),w(""),ae(),fe(),y(null),I(null),k(!1),p(!1),M(!1),v(!1),(G=(W=r.current)==null?void 0:W.reset)==null||G.call(W)},Ye=()=>{Ne.current&&(Ne.current=!1,Se(()=>{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=ee.current;if(!W)return;const G=W.slice(0,we);ee.current=W.slice(G.length);const te=r.current;if(!te){ee.current=G+ee.current,ue();return}te.write(G,()=>{if(ee.current.length>0){ue();return}Ye()})},ct=W=>{W&&(ee.current+=W,ue())},mt=(W,G=0,te,re,ke={})=>{var Oe,Re,Fe,Ue;const Ee=!!ke.force;!Ee&&G>0&&me.current>=G||!Ee&&G===0&&ie.current||(me.current=G,G>0&&M(!0),u(!0),w(""),typeof te=="number"&&typeof re=="number"&&te>0&&re>0&&((Re=(Oe=r.current)==null?void 0:Oe.resize)==null||Re.call(Oe,te,re)),ee.current="",(Ue=(Fe=r.current)==null?void 0:Fe.reset)==null||Ue.call(Fe),W?ct(W):Ye())};i.useEffect(()=>{Ve()},[de]),i.useEffect(()=>{var G;if(!de)return;const W=((G=ft.onRuntimeEvent)==null?void 0:G.call(ft,de,te=>{if(!(!te||te.sessionId!==de)){if(te.type==="runtime_snapshot"){if(!l){ce.current={text:te.text||"",seq:te.seq||0,cols:te.cols,rows:te.rows,force:!!te.force};return}mt(te.text||"",te.seq||0,te.cols,te.rows,{force:!!te.force});return}if(te.type==="session_output"){ie.current=!0,typeof te.seq=="number"&&(me.current=Math.max(me.current,te.seq),te.seq>0&&M(!0)),f.current||u(!0),f.current||w(""),typeof te.data=="string"&&ct(te.data);return}if(te.type==="session_cleared"){if(!l){je.current=!0,ee.current="",ce.current=null;return}Xe();return}if(te.type==="session_io_error"){const re=typeof te.error=="string"&&te.error?te.error:typeof te.reason=="string"&&te.reason?te.reason:"unknown error";u(!1),w(`Runtime input failed: ${re}`);return}}},Q))||(()=>{});return()=>{W()}},[Q,de,r,l]);const pt=async(W={})=>{var G;if(!Q||!de)return{success:!1,error:"daemonId and sessionId are required"};W.preserveStatus||w(W.loadingMessage||"Loading runtime terminal...");try{const te=await((G=ft.requestRuntimeSnapshot)==null?void 0:G.call(ft,Q,de,{sinceSeq:W.sinceSeq,force:W.force}));return te&&te.success===!1?(W.preserveStatus||(u(!1),w(`Runtime terminal unavailable: ${te.error}`)),te):te||{success:!0}}catch(te){const re=(te==null?void 0:te.message)||String(te);return W.preserveStatus||(u(!1),w(`Runtime terminal unavailable: ${re}`)),{success:!1,error:re}}},O=async W=>{var Ee,Oe;const G=((Ee=E.current)==null?void 0:Ee.ownerDocument)||document,te=G.defaultView||window,re=(Oe=te.navigator)==null?void 0:Oe.clipboard;if(re!=null&&re.writeText&&te.isSecureContext)try{return await re.writeText(W),!0}catch{}let ke=null;try{return ke=G.createElement("textarea"),ke.value=W,ke.setAttribute("readonly","true"),ke.style.position="fixed",ke.style.left="-9999px",ke.style.top="0",G.body.appendChild(ke),ke.focus(),ke.select(),G.execCommand("copy")}catch{return!1}finally{ke==null||ke.remove()}},be=W=>{fe(),I(W);const G=xe();ge.current={ownerWindow:G,timeoutId:G.setTimeout(()=>{ge.current=null,I(te=>te===W?null:te)},2200)}},Te=W=>{ae(),y(W);const G=xe();he.current={ownerWindow:G,timeoutId:G.setTimeout(()=>{he.current=null,y(te=>te===W?null:te)},2200)}},Be=async()=>{var ke,Ee,Oe,Re;const W=((Ee=(ke=r.current)==null?void 0:ke.getSelection)==null?void 0:Ee.call(ke))||"",G=((Re=(Oe=r.current)==null?void 0:Oe.getVisibleText)==null?void 0:Re.call(Oe))||"",te=W.trimEnd()||G.trimEnd();if(!te){be("Nothing to copy");return}if(!await O(te)){be("Copy failed");return}be(W.trimEnd()?"Copied selection":"Copied visible terminal")},qe=W=>{if(!m||!l)return;((d==null?void 0:d(Q,de,W))??!1)||be("Terminal input failed")},V=async()=>{if(b)return;p(!0),y("Loading older terminal output..."),Ne.current=!0;const W=await pt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(W==null?void 0:W.success)===!1){Ne.current=!1,y(`Older terminal output unavailable: ${W.error}`);return}v(!0),Te("Older terminal output loaded"),Se(()=>{var G;(G=r.current)==null||G.bumpResize()})};i.useEffect(()=>{var G,te;if(!de)return;Q&&((G=ft.getState)==null?void 0:G.call(ft,Q))==="connected"&&pt();const W=(te=ft.onStateChange)==null?void 0:te.call(ft,(re,ke)=>{re!==Q||ke!=="connected"||pt()});return()=>{W==null||W()}},[Q,de,r]),i.useEffect(()=>{t&&Ve()},[t,oe,r]),i.useEffect(()=>{var re,ke;const W=E.current,G=(ke=(re=W==null?void 0:W.ownerDocument)==null?void 0:re.defaultView)==null?void 0:ke.ResizeObserver;if(!W||!G)return;const te=new G(Ee=>{const Oe=Ee[0];if(!Oe)return;const{width:Re,height:Fe}=Oe.contentRect;L(Ue=>{const Le=Math.round(Re),Qe=Math.round(Fe);return Ue.width===Le&&Ue.height===Qe?Ue:{width:Le,height:Qe}})});return te.observe(W),()=>te.disconnect()},[]),i.useEffect(()=>{if($.current)return;const W=Ce();!Number.isFinite(W)||W<=0||T(G=>z.current?W<G-Ie?W:G:(z.current=!0,W))},[N.height,N.width,K.height,K.width]),i.useEffect(()=>{H&&Ke()},[H,Ae,Me]),i.useEffect(()=>{var te;const W=F.current;if(F.current=l,!l)return;W||v(!1),je.current&&(je.current=!1,Xe());const G=ce.current;G&&(ce.current=null,mt(G.text,G.seq,G.cols,G.rows,{force:!!G.force})),Q&&de&&((te=ft.getState)==null?void 0:te.call(ft,Q))==="connected"&&pt(),ee.current&&q.current===null&&ue(),Se(()=>{var re;(re=r.current)==null||re.bumpResize()})},[Q,l,de]),i.useEffect(()=>()=>{q.current!==null&&J(),fe(),ae()},[]),i.useEffect(()=>{const W=re=>{var Ee;const ke=re.detail;ke!=null&&ke.sessionId&&ke.sessionId!==de||m&&((Ee=r.current)==null||Ee.bumpResize())},G=xe(),te=G===window?[window]:[window,G];for(const re of te)re.addEventListener("adhdev:fit-cli-terminal",W);return()=>{for(const re of te)re.removeEventListener("adhdev:fit-cli-terminal",W)}},[m,de,r]);const X=m&&h&&!j&&(B.atTop||!B.canScroll)||b||!!g;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:E,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:()=>{V()},disabled:!de||b,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:b?"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:[C&&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:C}),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:()=>k(W=>!W),disabled:!m,"aria-label":"Open terminal control keys","aria-expanded":S,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),S&&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:()=>k(!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:()=>{$.current=!0,T(W=>{const G=Math.max(_e,Number((W-.1).toFixed(2)));return G>_e&&Ke(),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:()=>{$.current=!0,T(W=>{const G=Math.min(ne,Number((W+.1).toFixed(2)));return G>_e&&Ke(),G})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:R,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:N.width>0?`${N.width}px`:"100%",height:N.height>0?`${N.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:A},children:s.jsx(xc,{ref:r,readOnly:!m||!l,sizingMode:"measured",onViewportMetrics:P,onScrollMetrics:D,onInput:W=>{!m||(d==null||d(Q,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:x})]}),s.jsx(Ic,{contextKey:e.tabKey,panelLabel:ut(e),isSending:a,isBusy:!!ve,statusMessage:le,onSend:async W=>ve?!1:n(W),isActive:c&&l,showControlsToggle:!1,animateVisibility:!1})]})}const ex=5e3,tx=12e3;function sx(e){return e==="disconnected"||e==="reconnecting"}function rx({wsStatus:e,showReconnected:t,loginUrl:r,onReconnect:n,reconnectDelayMs:a=ex,reconnectActionDelayMs:o=tx}){const l=sx(e),[c,d]=i.useState(()=>!l||a<=0),[m,u]=i.useState(()=>!l||o<=0),f=i.useRef(!1);i.useEffect(()=>{if(!l){d(!1);return}if(f.current=!1,a<=0){f.current=!0,d(!0);return}d(!1);const v=setTimeout(()=>{f.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 x=l?c:e==="offline"||e==="auth_failed",w=!!(n&&e!=="auth_failed"&&(!l||m)),b=i.useMemo(()=>!t||e!=="connected"?!1:a<=0||f.current,[a,t,e]),p=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)"},h={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},M="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",j={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:M,style:j,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[p],border:y[p],color:h[p]},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"})]})}),b&&s.jsx("div",{className:M,style:j,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 nx({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 Bo({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(jo,{size:n}):s.jsx(Jt,{size:n})})}const Ht="New session",Qc="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 ax(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 ox(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 ix(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 Us({git:e,className:t="",compact:r=!1}){const n=ax(e),a=ox(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 ${ix(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 lx({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 qi({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Yi({notification:e,shortcutIndex:t,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const l=On(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 cx({activeConv:e,wsStatus:t,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:l,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:f,onShowAllHidden:x,onResetPanelsToMain:w,inboxOpen:b,onInboxOpenChange:p,hiddenOpen:g,onHiddenOpenChange:y,onOpenNewSession:h,onOpenDashboardGuide:M,guideNudgeVisible:j=!1,actionShortcuts:v,notifications:A,notificationUnreadCount:T,onOpenNotification:S,onMarkNotificationRead:k,onMarkNotificationUnread:K,onDeleteNotification:L,onOpenGitDialog:N,onOpenMeshGraph:P}){var Se;const{ides:B,p2pStates:D={}}=ls(),C=!!e&&at(e)&&!st(e),I=!!e&&st(e),E=!!(e!=null&&e.daemonId)&&typeof((Se=e==null?void 0:e.settings)==null?void 0:Se.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,R=c||(e?Mc(e)?"terminal":"chat":null),[$,z]=i.useState(!1),F=i.useRef(null),me=i.useRef(null),ie=B.filter(J=>J.type==="adhdev-daemon"),ee=lx({wsStatus:t,isConnected:r,daemonCount:ie.length,p2pStates:D}),ce=ee.subtitle,je=ee.tone==="connected"?"#22c55e":ee.tone==="limited"?"#eab308":"#ef4444",Ne=ee.tone==="connected"?"0 0 4px #22c55e80":ee.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",q=i.useMemo(()=>A.filter(J=>!J.readAt),[A]),ge=i.useMemo(()=>A.filter(J=>!!J.readAt),[A]),he=i.useMemo(()=>q.slice(0,9),[q]),we=T;i.useEffect(()=>{if(!b)return;const J=fe=>{var ae;(ae=F.current)!=null&&ae.contains(fe.target)||p(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[b,p]),i.useEffect(()=>{if(!g)return;const J=fe=>{var ae;(ae=me.current)!=null&&ae.contains(fe.target)||y(!1)};return document.addEventListener("mousedown",J),()=>document.removeEventListener("mousedown",J)},[g,y]),i.useEffect(()=>{if(!g&&!b)return;const J=fe=>{if(!fe.altKey)return;const ae=fe.code.match(/^Digit([1-9])$/);if(!ae)return;const ue=Number(ae[1])-1,oe=g?u[ue]:void 0,de=b?he[ue]:void 0;if(!(!oe&&!de)){if(fe.preventDefault(),fe.stopPropagation(),oe){f==null||f(oe),y(!1);return}de&&(S(de),p(!1))}};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[u,g,b,he,y,p,S,f]);const xe=J=>{if(!J)return;const fe=n.find(ae=>ae.tabKey===J);fe&&(m==null||m(fe))};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(Jt,{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:ee.title,"aria-label":ee.title,className:"header-title-status-dot",style:{background:je,boxShadow:Ne}}),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:Ne}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ce&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ce]}),h&&s.jsx("button",{type:"button",onClick:h,className:"btn btn-secondary btn-sm ml-2",title:`${Ht}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":Ht,children:s.jsx(cc,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[M&&s.jsxs("button",{type:"button",onClick:M,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:"?"}),j&&s.jsx("span",{children:"Guide"})]}),e&&(C||I||!st(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:Ns(e)||ut(e),children:ut(e)}),N&&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:()=>N(e.daemonId,e.workspacePath),children:s.jsx(Us,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Us,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),E&&P&&s.jsxs("button",{type:"button",onClick:()=>P(e),className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",title:"Open live repo mesh graph",children:[s.jsx(rs,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(C||I)&&l&&s.jsxs(s.Fragment,{children:[C&&d&&R&&s.jsx(Bo,{mode:R,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:I?"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(vo,{size:14})}),!C&&!st(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:s.jsx(_t,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:F,children:[s.jsxs("div",{className:`dashboard-header-hidden${$?" is-drop-target":""}`,ref:me,onDragEnter:J=>{J.dataTransfer.types.includes("text/tab-key")&&(J.preventDefault(),z(!0))},onDragOver:J=>{J.dataTransfer.types.includes("text/tab-key")&&(J.preventDefault(),J.dataTransfer.dropEffect="move",z(!0))},onDragLeave:J=>{J.currentTarget.contains(J.relatedTarget)||z(!1)},onDrop:J=>{const fe=J.dataTransfer.getData("text/tab-key");J.preventDefault(),z(!1),xe(fe)},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(wo,{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(qi,{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&&x&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{x(),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(qi,{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(J=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{f==null||f(J),y(!1)},children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:ut(J)}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(J)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(J)+1]}):null,Ns(J)]})]},J.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!b),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[s.jsx(Bn,{size:16}),we>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:we})]}),b&&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(J=>s.jsx(Yi,{notification:J,shortcutIndex:he.indexOf(J)>=0?he.indexOf(J)+1:void 0,onOpen:()=>S(J),onMarkRead:()=>k(J.id),onMarkUnread:()=>K(J.id),onDelete:()=>L(J.id)},J.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(J=>s.jsx(Yi,{notification:J,onOpen:()=>S(J),onMarkRead:()=>k(J.id),onMarkUnread:()=>K(J.id),onDelete:()=>L(J.id)},J.id))]}),A.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 dx(e,t){return String(e||"")!==String(t||"")}function ux(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&&!wc(l.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
42
|
+
`).includes(a)))}function mx(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 Zc(e,t={}){return mx(ux(e,t),t.sortMode||"recent")}function An(e){return e?"Resume saved history":"Start fresh"}function Oo(e){return e?"Resuming saved history…":"Starting fresh…"}function px(){return"Start fresh"}function ed(e,t=!1){return e==="cli"?An(t):e==="ide"?"Start IDE":"Start ACP session"}function td(e,t=!1){return e==="cli"?Oo(t):e==="ide"?"Starting IDE…":"Starting ACP session…"}function fx(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function hx(){return"Open saved history"}function xx(){return"Saved History"}function Fo(){return"Use saved history when you want continuity in the same provider conversation."}function bx(){return"No saved history found yet."}function gx(){return"Refresh saved history"}function yx(){return"Refreshing saved history…"}function xs(e,t){return e==="start-fresh"?`Start fresh with ${t}?`:`Restart ${t}?`}function bs(e){return e==="start-fresh"?"Review the provider and target folder before starting fresh.":e==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function zs(e){return e==="start-fresh"?"Start fresh":"Restart"}function Vs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Wo(e){return`Resume saved history with ${e}?`}function Ko(){return"Review or change the target workspace before resuming saved history."}function vx(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 Ho({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:f,onSwitchSession:x,onRefreshHistory:w,onResumeSavedSession:b}){var L;const p=t.find(N=>N.id===e.routeId),g=(p==null?void 0:p.chats)||[],y=(L=p==null?void 0:p.activeChat)==null?void 0:L.id,h=at(e)&&!st(e),[M,j]=i.useState(()=>Nt()),v=c||M,A=String(d||"").trim(),T=N=>{if(m){m(N);return}j(N)},S=i.useMemo(()=>a.map(N=>{const P=String(N.workspace||"").trim();return N.canResume||P||!A?N:{...N,workspace:A,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[A,a]),k=i.useMemo(()=>Zc(S,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[S,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.workspaceQuery]),K=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:h?xx():"Chat History"}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Jh(e)}),h&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Fo()})]}),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:[!h&&s.jsx("button",{onClick:f,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"}),h?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:N=>T({...v,textQuery:N.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:N=>T({...v,workspaceQuery:N.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:N=>T({...v,modelQuery:N.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:N=>T({...v,sortMode:N.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:N=>T({...v,resumableOnly:N.target.checked})}),"Resume-ready only"]})]}),k.map(N=>{const P=e.providerSessionId===N.providerSessionId,B=P||!N.canResume||!!l,D=N.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{B||!b||b(N)},disabled:B,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${P?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${B?"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 ${P?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:N.title||"Untitled Session"}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:N.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:vx(N.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:N.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:[N.workspace||"Workspace unknown",D?" · selected workspace":"",Ss(N.summaryMetadata)?` · ${Ss(N.summaryMetadata)}`:"",N.messageCount>0?` · ${N.messageCount} msgs`:""]}),s.jsx("div",{className:"shrink-0",children:P?"ACTIVE":N.canResume?D?"RESUME IN SELECTED WORKSPACE":l===N.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},N.id)})]}):g.map(N=>s.jsxs("div",{onClick:()=>{x(e.routeId,N.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${y===N.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===N.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:N.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:[N.id.substring(0,12),"..."]}),y===N.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},N.id)),(h&&!o&&k.length===0||!h&&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(Um,{size:32})}),s.jsx("div",{className:"text-[13px]",children:h?a.length>0?"No saved history matches these filters.":bx():"No recent chat sessions found."})]}),h&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:yx()})})]}),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})," ",h?gx():"Refresh History"]})})})]})]});return typeof document>"u"?K:Sr.createPortal(K,document.body)}const Xi={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Done"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Attention"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",label:"Update"}};function sd({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=Xi[n.type]||Xi.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 wx=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function jx(e){const t=e.workspace||"";if(!t)return"";const r=t.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:t}function kx(e){return e.sessionId||e.instanceId||e.agentType}function ua(e,t){return t||e||"unknown"}function rd(e=[]){const t={};for(const r of e)r.type==="adhdev-daemon"&&(t[r.id]=Tt(r,{fallbackId:r.id}));return t}function nd(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 Uo(e,t={}){return Sx(e,nd(e,t))}function Sx(e,t={}){var f,x,w,b,p;const r=[],n=t.machineName,a=t.connectionState,o=jx(e),l=e.workspace||"",c=Gp(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,h;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:((h=g.activeChat)==null?void 0:h.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=wx(e);if(u){const g=e.sessionId||e.instanceId,y=(f=e.settings)==null?void 0:f.meshCoordinatorFor,h=(x=e.settings)==null?void 0:x.meshNodeFor,M=y?" (Coordinator)":h?" (Mesh Node)":"",j=c+M,v=(w=e.activeChat)==null?void 0:w.activeModal,A=v&&Array.isArray(v.buttons)&&v.buttons.length>0,T=qp(e.activeChat,[{status:e.status,activeModal:(b=e.activeChat)==null?void 0:b.activeModal}],e.agents||[]),S=e.activeChat||{title:"",messages:[]};let k=S.title&&String(S.title).trim()?String(S.title).trim():"";const K=(p=e.activeChat)==null?void 0:p.id,L=e.chats;if(K&&Array.isArray(L)&&L.length>0){const D=L.find(C=>C.id===K||C.id&&String(C.id)===String(K));D!=null&&D.title&&String(D.title).trim()&&(k=String(D.title).trim())}const N=(at(e)||st(e),e.type),P=(at(e)||st(e))&&Di(k,j,N)?"":k,B=S.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:j,agentType:N,status:T,title:P,messages:B,resume:e.resume,hostIdeType:!at(e)&&!st(e)?e.type:void 0,workspaceName:o,workspacePath:l,git:e.git,displayPrimary:P||o||(at(e)?e.mode==="chat"?j:`Terminal${M}`:j),displaySecondary:at(e)&&o?j:d,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:A?v.buttons:void 0,modalMessage:A?v.message:void 0,streamSource:"native",tabKey:ua(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,h=Yp(g),M=kx(g),j=`${e.id}:${M}`,v=g.title&&String(g.title).trim()||"",A=Di(v,g.agentName,g.agentType)?"":v,T=g.messages||[];(g.transport==="cdp-webview"||g.sessionId||g.providerSessionId||T.length>0||y||A||!["idle","panel_hidden","disconnected","not_monitored"].includes(h))&&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:h,title:A,messages:T,hostIdeType:e.type,workspaceName:o,workspacePath:l,git:g.git||e.git,displayPrimary:A||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:ua(g.sessionId||g.instanceId,j),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:ua(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function ad(e){return String(e.type||e.id||"").trim()}function Nx(e){var t;return e.category!=="cli"||!ad(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 Cx(e){var n;const t=new Set,r=[];for(const a of e||[]){if(!Nx(a))continue;const o=ad(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 Un(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 ro(e,t){const r=new Set(t.map(n=>n.type));return Un(e).filter(n=>r.has(n))}function Ix(e){return e.map(t=>t.type)}function Mx(e,t){const r=Un(e),n=t.trim();return!n||r.includes(n)?r:[...r,n]}function Ax(e,t){return Un(e).filter(r=>r!==t)}function Ji(e,t,r){const n=Un(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 Qi({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 Zi({value:e,availableProviders:t,onChange:r,disabled:n=!1,saveButton:a}){const[o,l]=i.useState(""),c=i.useMemo(()=>new Map(t.map(x=>[x.type,x])),[t]),d=i.useMemo(()=>ro(e,t),[e,t]),m=e.length-d.length,u=t.filter(x=>!d.includes(x.type)),f=()=>{o&&(r(Mx(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((x,w)=>{const b=c.get(x);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]}),(b==null?void 0:b.icon)&&s.jsx("span",{"aria-hidden":"true",children:b.icon}),s.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:x}),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:b?`${b.label} · ${b.statusLabel}`:x})]}),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(Ji(d,x,"up")),children:s.jsx(Qi,{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(Ji(d,x,"down")),children:s.jsx(Qi,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(Ax(d,x)),children:"Remove"})]})]},x)})}),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:x=>l(x.target.value),disabled:n||u.length===0,children:[s.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(x=>s.jsxs("option",{value:x.type,children:[x.label," (",x.type,")"]},x.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:f,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 Tx(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 od(e,t){const r=Tx(e);return{daemonId:r.daemonId,payload:{...t,...r.targetSessionId&&!t.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const id=[{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:"🏄"}],ld=[{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:"🧩"}],cd=[{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:"🟠"}],_x=id,Lx=ld,Rx=cd;function Qt(...e){return Yu(Xu(e))}function Px({icon:e,title:t,subtitle:r,badge:n,actions:a,className:o}){return s.jsxs("div",{className:Qt("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 vr({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(Px,{icon:e,title:t,subtitle:r,badge:n,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Qt("mx-auto flex w-full flex-col gap-4",o,l),children:c})})]})}const no="adhdev:themechange";function Dx(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function _s(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ls(e){return e==="system"?Dx():e}function dd(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function dn(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(no,{detail:{preference:e,theme:t}}))}function Ex(){const e=_s(),t=Ls(e);dd(t),dn(e,t)}function Js(){const[e,t]=i.useState(_s),[r,n]=i.useState(()=>Ls(_s()));i.useEffect(()=>{dd(r)},[r]),i.useEffect(()=>{const l=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),dn("system",m)}};return l.addEventListener("change",c),()=>l.removeEventListener("change",c)},[e]),i.useEffect(()=>{const l=d=>{const m=d.detail||{},u=m.preference,f=m.theme;t(u==="dark"||u==="light"||u==="system"?u:_s()),n(f==="dark"||f==="light"?f:Ls(_s()))},c=d=>{if(d.key!=="theme")return;const m=_s(),u=Ls(m);t(m),n(u)};return window.addEventListener(no,l),window.addEventListener("storage",c),()=>{window.removeEventListener(no,l),window.removeEventListener("storage",c)}},[]);const a=i.useCallback(l=>{const c=Ls(l);t(l),n(c);try{localStorage.setItem("theme",l)}catch{}dn(l,c)},[]),o=i.useCallback(()=>{t(l=>{const c=l==="dark"?"light":l==="light"?"system":"dark",d=Ls(c);n(d);try{localStorage.setItem("theme",c)}catch{}return dn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const el={dark:"Dark",light:"Light",system:"System"};function $x({collapsed:e}){const{preference:t,cycleTheme:r}=Js(),n=t==="dark"?s.jsx(Vm,{size:16}):t==="light"?s.jsx(zm,{size:16}):s.jsx(Gm,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${el[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:n}),!e&&s.jsx("span",{className:"text-xs",children:el[t]})]})}function ma(e,t){return e?typeof e=="function"?e(t):e:null}function Bx({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),[f,x]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),w=()=>u(!0),b=()=>u(!1),p=()=>{x(M=>{const j=!M;try{localStorage.setItem(d,j?"1":"0")}catch{}return j})},g=i.useMemo(()=>({collapsed:f,mobileMenuOpen:m,openMobileMenu:w,closeMobileMenu:b,toggleCollapsed:p}),[f,m]),y=M=>`nav-item${M.active?" active":""} cursor-pointer ${f?"justify-center py-2.5 px-0":""}${M.className?` ${M.className}`:""}`,h=M=>s.jsxs("div",{className:y(M),id:`nav-${M.id}`,onClick:()=>{M.onSelect(),b()},title:f?M.title??(typeof M.label=="string"?M.label:void 0):M.title,children:[s.jsx("span",{className:"nav-icon",children:M.icon}),!f&&M.label]},M.id);return s.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${f?" 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:b,onKeyDown:M=>M.key==="Escape"&&b()}),s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${f?"justify-center gap-0":""}`,children:ma(t,g)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:b,children:s.jsx(jt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(h)}),n.map(M=>s.jsxs("div",{className:M.className??"border-t border-border-subtle pt-2 mt-2",children:[!f&&M.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:M.title}):null,M.items.map(h)]},M.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(h),ma(o,g),s.jsx($x,{collapsed:f}),ma(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:Qt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",n&&"border-l-[3px]",a),style:n?{borderLeftColor:n}:void 0,children:[(e||r)&&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 Tn({icon:e,title:t,description:r,action:n,className:a}){return s.jsxs("div",{className:Qt("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 Ox={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"},Fx={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ds({variant:e,children:t,onDismiss:r,className:n}){return s.jsxs("div",{className:Qt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Ox[e],n),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Fx[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 At({label:e,hint:t,children:r,className:n}){return s.jsxs("div",{className:Qt("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 lr(e){const{className:t,...r}=e;return s.jsx("input",{...r,className:Qt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const Wx={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"},Kx={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Hx({status:e,label:t,className:r}){const n=t||e;return s.jsxs("span",{className:Qt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Wx[e],r),children:[s.jsx("span",{className:Qt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Kx[e])}),n]})}function ms({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 Ux({onPrefChange:e}){const[t,r]=af(),[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(ms,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Bn,{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(ms,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_t,{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:()=>{Sc().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(ms,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qm,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:l=>o("completionAlert",l)}),s.jsx(ms,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ym,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:l=>o("approvalAlert",l)}),s.jsx(ms,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ws,{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 _n(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:null}function zx(e,t){const r=_n(e),n=_n(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 ud(e,t){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!t?!1:r!==t}function wr(e,t){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!t||r===t||zx(r,t)>=0)return!1;const n=_n(r),a=_n(t);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Vx(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function pa(e,t){return e instanceof Error?e.message:t}function Gx({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(Tn,{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(Yx,{ide:l,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},l.id))})}function tl({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 Sr.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 qx(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[..._x,...Lx,...Rx].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 Yx({ide:e,allIdes:t,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var B,D;const[o,l]=i.useState("idle"),[c,d]=i.useState(""),[m,u]=i.useState(null),[f,x]=i.useState("idle"),[w,b]=i.useState(""),p=e.version||null,g=((B=e.machine)==null?void 0:B.platform)||((D=e.system)==null?void 0:D.platform)||"",y=Tt(e,{fallbackId:e.id}),h=g==="win32"?"🪟":g==="darwin"?"🍎":"🐧",M=t.filter(C=>C.daemonId===e.id&&C.transport==="cdp-page"),j=t.filter(C=>C.daemonId===e.id&&C.transport==="pty"),v=t.filter(C=>C.daemonId===e.id&&C.transport==="acp"),A=e.p2p,T=async()=>{if(r){l("upgrading"),d("Starting upgrade...");try{const C=Vx(await r(e.id,"daemon_upgrade",{}));C.alreadyLatest?(l("done"),d(`Already on v${C.version||"latest"}.`)):C.upgraded||C.success?(l("done"),d(`Upgrade to v${C.version||"latest"} started. Daemon is restarting...`)):(l("error"),d(C.error||"Upgrade failed"))}catch(C){l("error"),d(pa(C,"Connection lost during upgrade"))}}},S=async()=>{if(u(null),!!n){x("loading");try{await n(e.id),x("done"),b("Machine disconnected.")}catch(C){x("error"),b(pa(C,"Failed to disconnect"))}}},k=async()=>{if(u(null),!!a){x("loading");try{await a(e.id),x("done"),b("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(C){x("error"),b(pa(C,"Failed to revoke token"))}}},K="0.9.81",L=ud(e,K),N=wr(e,K),P=M.length+j.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:h}),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),"…"]}),p&&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",p,!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${K}`,children:o==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${N?"↑ Update now":`↑ Update${` to v${K}`}`}`}),n&&s.jsx("button",{onClick:()=>u("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&s.jsx("button",{onClick:()=>u("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),s.jsx(Hx,{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:[A&&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 ${A.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${A.state==="connecting"||A.state==="new"?"animate-pulse":""}`,style:A.state==="connecting"||A.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",A.state==="connected"?"connected":A.state==="connecting"||A.state==="new"?"connecting...":A.state||"off"]}),A.peers!==void 0&&A.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",A.peers," peer",A.peers!==1?"s":"",")"]})]}),A&&P>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),P>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[M.map(C=>{const I=qx(C.type),E=C.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:I.icon}),s.jsx("span",{children:I.name}),E!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${E?"bg-green-400":"animate-pulse"}`,style:E?void 0:{background:"var(--status-warning)"},title:E?"CDP connected":"CDP connecting..."})]},C.id)}),j.map(C=>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:C.cliName||"CLI"})]},C.id)),v.map(C=>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:C.cliName||"ACP"})]},C.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"||f==="error"?"text-red-400":o==="done"||f==="done"?"text-green-400":"text-text-muted"}`,children:w||c})]}),m==="disconnect"&&s.jsx(tl,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
|
|
43
|
+
|
|
44
|
+
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
45
|
+
|
|
46
|
+
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:S,onCancel:()=>u(null)}),m==="revoke"&&s.jsx(tl,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
|
|
47
|
+
|
|
48
|
+
This will:
|
|
49
|
+
• Immediately disconnect the machine
|
|
50
|
+
• Delete the machine registration
|
|
51
|
+
• Require restarting ADHDev on that machine
|
|
52
|
+
|
|
53
|
+
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:k,onCancel:()=>u(null)})]})}const Xx=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Jx(){const{preference:e,setPreference:t}=Js();return s.jsx("div",{className:"flex gap-2",children:Xx.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 Qx(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 Zx(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function fa(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function sl(e){const{r:t,g:r,b:n}=Zx(e);return .2126*fa(t)+.7152*fa(r)+.0722*fa(n)}function rl(e,t){const r=sl(e),n=sl(t),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function md(e){const t=Qx(e);if(!t)return"#111827";const r="#111827",n="#ffffff";return rl(t,r)>=rl(t,n)?r:n}const ao={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},oo={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},eb=[{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"}}}],pd="adhdev-chat-theme",fd="adhdev-chat-theme-custom";function un(){if(typeof window>"u")return"ember";try{return localStorage.getItem(pd)||"ember"}catch{return"ember"}}function Ot(e){try{const t=localStorage.getItem(fd);if(t){const r=JSON.parse(t);return{...e==="dark"?ao:oo,...r[e]}}}catch{}return e==="dark"?ao:oo}function Yr(e,t){try{localStorage.setItem(fd,JSON.stringify({dark:e,light:t}))}catch{}}function Rt(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 Ln(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 tb={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function jr(e,t){var a;const r=(a=tb[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",Ln(r,24)),n.style.setProperty("--accent-on-primary",md(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Ln(r,18)})`),n.style.setProperty("--border-accent",Rt(r,.35)),n.style.setProperty("--nav-active-bg",Rt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Rt(r,.06)}`)}function gs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Rt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Rt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Rt(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",Rt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Rt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Ln(e.accentColor,30)),t.style.setProperty("--accent-on-primary",md(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Ln(e.accentColor,40)})`),t.style.setProperty("--border-accent",Rt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Rt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Rt(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 ${Rt(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 zo(){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 sb(e){try{localStorage.setItem(pd,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ys()?"dark":"light";gs(Ot(t))}else zo(),jr(e,ys()?"dark":"light")}function rb(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=un();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ys()?"dark":"light";gs(Ot(t))}else zo(),jr(e,ys()?"dark":"light")}function ys(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function 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 cr({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 nb({dark:e,onColorsChange:t}){const r=e?"dark":"light",[n,a]=i.useState(()=>Ot(r));i.useEffect(()=>{a(Ot(r))},[r]);const o=i.useCallback((l,c)=>{a(d=>{const m={...d,[l]:c},f=Ot(r==="dark"?"light":"dark");return r==="dark"?Yr(m,f):Yr(f,m),gs(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(cr,{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(cr,{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(cr,{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(cr,{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(cr,{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?ao:oo,d=Ot(e?"light":"dark");e?Yr(l,d):Yr(d,l),a(l),gs(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 ab(){const[e,t]=i.useState(un),[r,n]=i.useState(!0),[a,o]=i.useState(()=>Ot("dark"));i.useEffect(()=>{n(ys());const d=new MutationObserver(()=>{const f=ys();n(f);const x=un();x==="custom"?gs(Ot(f?"dark":"light")):jr(x,f?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const f=ys();n(f);const x=un();x==="custom"?gs(Ot(f?"dark":"light")):jr(x,f?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?gs(Ot(r?"dark":"light")):(zo(),jr(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o(Ot(r?"dark":"light"))},[r]);const l=d=>{t(d),sb(d)},c=[...eb,{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,f=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:f},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(nb,{dark:r,onColorsChange:d=>o(d)})]})}const Vo="adhdev_mobileDashboardMode_v1",io="adhdev:mobile-dashboard-mode-change";function Go(){try{return localStorage.getItem(Vo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function ob(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Go())},r=a=>{const o=a.detail;t(o)},n=a=>{a.key&&a.key!==Vo||t()};return window.addEventListener(io,r),window.addEventListener("storage",n),()=>{window.removeEventListener(io,r),window.removeEventListener("storage",n)}}function ib(e){try{localStorage.setItem(Vo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(io,{detail:e}))}function lb(){const[e,t]=i.useState(!0);return i.useEffect(()=>{t(Go()==="chat")},[]),s.jsx(ms,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Jt,{size:15})," Mobile Inbox (Chat Mode)"]}),description:e?"Use the chat-first mobile inbox layout. This keeps mobile closer to a messaging app.":"Use the full workspace layout on phones and tablets.",checked:e,onChange:r=>{t(r),ib(r?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const ha=new Map,nl=new Map;function cb(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 db(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 hd(){const{sendCommand:e}=kt(),{injectEntries:t,getIdes:r}=Nr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??oh,l=nl.get(n)||0;if(!(a!=null&&a.force)&&l>0&&Date.now()-l<o)return;const c=ha.get(n);if(c)return c;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=cb(m);if(!u)return;const f=r().find(w=>w.id===n),x=db(f,n,u.machine,u.timestamp||Date.now());t([x]),nl.set(n,Date.now())})().finally(()=>{ha.delete(n)});return ha.set(n,d),d},[r,t,e])}function ub(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 mb(e,t){const{sendData:r}=kt(),{injectEntries:n,getIdes:a}=Nr(),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=>Xt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const f=a().find(w=>w.id===d),x=ub(f,d,u);n([x])}));return()=>{c.forEach(d=>d())}},[o,a,n,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,r])}function pb(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=Xt.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)},dh):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 fb(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function xd(e){const{sendData:t}=kt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=fb(e);if(!a||!e.sessionId||!t){n({});return}const o=Xt.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}),Os.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 bd="adhdev_hiddenTabs",gd="adhdev_autoHiddenMeshTabs";function hb(){try{const e=localStorage.getItem(bd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function ds(e){try{localStorage.setItem(bd,JSON.stringify([...e]))}catch{}}function xb(){try{const e=localStorage.getItem(gd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function al(e){try{localStorage.setItem(gd,JSON.stringify([...e]))}catch{}}function xr(e){return Eo(e)}function zn(e,t){return Bs(t).some(r=>e.has(r))}function bb(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 gb(e,t,r=new Set){return e.filter(n=>{if(!bb(n))return!1;const a=xr(n);return r.has(a)?!1:!zn(t,n)})}function yb(){const[e,t]=i.useState(hb),[r,n]=i.useState(xb),a=i.useCallback(x=>{const w=xr(x);t(b=>{const p=new Set(b);return p.has(w)?p.delete(w):p.add(w),ds(p),p})},[]),o=i.useCallback(x=>{const w=xr(x);t(b=>{if(b.has(w))return b;const p=new Set(b);return p.add(w),ds(p),p})},[]),l=i.useCallback(x=>{const w=xr(x);t(b=>{if(b.has(w))return b;const p=new Set(b);return p.add(w),ds(p),p}),n(b=>{if(b.has(w))return b;const p=new Set(b);return p.add(w),al(p),p})},[]),c=i.useCallback(x=>{const w=xr(x);t(b=>{if(!b.has(w))return b;const p=new Set(b);return p.delete(w),ds(p),p}),n(b=>{if(b.has(w))return b;const p=new Set(b);return p.add(w),al(p),p})},[]),d=i.useCallback(()=>{t(x=>{if(x.size===0)return x;const w=new Set;return ds(w),w})},[]),m=i.useCallback((x,w)=>{t(b=>{const p=new Set(b);for(const g of w)p.add(g);return ds(p),p})},[]),u=i.useCallback((x,w)=>{t(b=>{const p=new Set(b);for(const g of w)p.delete(g);return ds(p),p})},[]),f=i.useCallback(x=>zn(e,x),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:l,showTarget:c,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:f}}function yd(e){return e instanceof Error?e.message:String(e||"")}function vd(e){const t=yd(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 wd(e){const t=yd(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function jd({conversation:e,mode:t,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!at(e)||st(e))return;const o=Xs(e);if(o===t)return;const l=e.sessionId;l&&a(c=>({...c,[l]:t}));try{await n(Ms(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:zt(e),mode:t})}catch(c){const d=wd(c);l&&!d&&a(m=>{const u={...m};return o===kd(r,l)?delete u[l]:u[l]=o,u}),vd(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function ol(e,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 vb(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=ol(a,t),l=Array.isArray(a.childSessions)?a.childSessions.map(d=>ol(d,t)):a.childSessions,c=l!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:l}:{}}):a});return r?n:e}function kd(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 wb(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))kd(t,a)===o&&(delete n[a],r=!0);return r?n:e}function jb({visibleConversations:e,clearedTabs:t,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{Sc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:Xc(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return df(a),i.useEffect(()=>{if(Object.keys(t).length===0)return;const l=setTimeout(()=>{r(c=>{const d=Date.now(),m={};for(const[u,f]of Object.entries(c))d-f<5e3&&(m[u]=f);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 il(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 vs(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=il(t==null?void 0:t.receivedAt)||il(t==null?void 0:t.timestamp)||0;return Math.max(r,n)}function lo(e,t=0){return vs(e)||e.lastUpdated||t||0}function Sd(e){return vs(e)||e.lastUpdated||0}function Nd(e,t,r=Sd){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 co(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 kb(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!co(e)&&!e.title.trim()}function Sb(e){return e.length===0?null:[...e].sort((t,r)=>{const n=Number(co(r))-Number(co(t));if(n!==0)return n;const a=r.messages.length-t.messages.length;return a!==0?a:Nd(t,r)})[0]||null}function Ft(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=Sb(a);return n?o&&kb(n)?o:n:o||r[0]||null}function Nb(e){const t=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!t||r.startsWith(`${t}:`)?r:`${t}:${r}`}function Cb(e){const t=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of t){const a=Nb(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 xa(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 Ib(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 ll(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],r=t[t.length-1],n=r?Ib(Fs(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 Mb(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||""),ll(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||""),ll(r.activeChat)].join(":"))].join("|")}function Ab(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 Tb(e,t){const r=new Map;for(const n of e){const a=t.get(n.routeId)||n;for(const o of Bs({routeId:n.routeId}))r.set(o,a);for(const o of Bs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Bs({tabKey:n.tabKey}))r.set(o,n)}return r}function _b(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function Lb(e){const t=_b(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=Fs(t.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Rb({ides:e,connectionStates:t,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>Cb(e),[e]),o=i.useMemo(()=>rd(e),[e]),l=i.useRef([]),c=i.useRef([]),d=i.useRef([]),m=i.useRef(new Map),u=i.useRef(new Map),f=i.useMemo(()=>{const j=new Map,v=[];for(const k of a){const{connectionState:K="new",machineName:L}=nd(k,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),N=Mb(k),P=m.current.get(k.id);if(P&&P.ide===k&&P.sourceSignature===N&&P.connectionState===K&&P.machineName===L){j.set(k.id,P),v.push(...P.conversations);continue}const B=Uo(k,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),D={ide:k,sourceSignature:N,connectionState:K,machineName:L,conversations:B};j.set(k.id,D),v.push(...B)}m.current=j;const A=new Map,T=k=>{const K=Lb(k),L=u.current.get(k.tabKey);if(L&&L.signature===K)return A.set(k.tabKey,L),L.timestamp;const N={signature:K,timestamp:Sd(k)||(L==null?void 0:L.timestamp)||0};return A.set(k.tabKey,N),N.timestamp},S=[...v].sort((k,K)=>Nd(k,K,T));return u.current=A,S},[a,t,o]),x=i.useMemo(()=>{const j=Ab(f,r);return xa(l.current,j)?l.current:(l.current=j,j)},[f,r]),w=i.useMemo(()=>{const j=new Map,v=Array.from(new Set(x.map(A=>A.routeId)));for(const A of v){const T=Ft(x,A);T&&j.set(A,T)}return j},[x]),b=i.useMemo(()=>{const j=new Map;for(const v of x){const A=w.get(v.routeId),T=v.streamSource==="native"&&A?A:v;for(const S of Bs({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))j.set(S,T)}return j},[x,w]),p=i.useMemo(()=>Tb(x,w),[x,w]),g=i.useCallback(j=>{if(j)return b.get(j)},[b]),y=i.useCallback(j=>{if(j)return p.get(j)},[p]),h=i.useMemo(()=>{const j=x.filter(v=>!zn(n,v));return xa(c.current,j)?c.current:(c.current=j,j)},[x,n]),M=i.useMemo(()=>{const j=h.map(v=>v.tabKey);return xa(d.current,j)?d.current:(d.current=j,j)},[h]);return{chatIdes:a,conversations:x,visibleConversations:h,visibleTabKeys:M,resolveConversationBySessionId:g,resolveConversationByTarget:y}}function Pb({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 Db({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=Gc.on("status_event",o=>{ot.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=l=>{var p;const c=l.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||c.daemonId;if(!u)return;const f=Number(c.buttonIndex),x=c.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[f])||"Approve",w=String(x).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),b=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(w);t(u,"resolve_action",{action:b?"approve":"reject",button:x,...Number.isFinite(f)&&{buttonIndex:f},...(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 Eb="adhdev_dashboardLayout_v1",$b="adhdev_dashboardDockview_v1",Bb="adhdev_dashboardDockviewHiddenRestore_v1",dr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function qo(e,t){try{const r=localStorage.getItem(e);return r?JSON.parse(r):t}catch{return t}}function Ob(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Cd(e){return`${Eb}:${e}`}function Fb(e){const t=Cd(e);return qo(t,null)}function Wb(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=Cd(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Id(e){return`${$b}:${e}`}function Kb(e){const t=Id(e);return qo(t,null)}function Hb(e,t){try{const r=Id(e);if(!t){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Md(e){return`${Bb}:${e}`}function Ub(e){const t=Md(e);return qo(t,{})}function zb(e,t){try{const r=Md(e);if(Object.keys(t).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Vb(){return{groupAssignments:[...dr.groupAssignments],focusedGroup:dr.focusedGroup,groupActiveTabIds:{...dr.groupActiveTabIds},groupTabOrders:{...dr.groupTabOrders},groupSizes:[...dr.groupSizes]}}function Gb(e,t){return e?e.length===t.length&&e.every((r,n)=>r===t[n]):t.length===0}function qb(){const[e]=i.useState(()=>Ob(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([]),[f,x]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[w,b]=i.useState(!1),p=i.useCallback(()=>{if(w)return;const k=Fb(e)??Vb();r(new Map(k.groupAssignments)),a(k.focusedGroup),l(k.groupActiveTabIds),d(k.groupTabOrders),u(k.groupSizes),b(!0)},[w,e]);i.useEffect(()=>{w&&Wb(e,{groupAssignments:[...t.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:m})},[w,e,t,n,o,c,m]),i.useEffect(()=>{const k=window.matchMedia("(max-width: 767px)"),K=L=>x(L.matches);return k.addEventListener("change",K),()=>k.removeEventListener("change",K)},[]);const g=i.useCallback(k=>{r(k)},[]),y=i.useCallback(k=>{a(k)},[]),h=i.useCallback(k=>{l(k)},[]),M=i.useCallback(k=>{d(k)},[]),j=i.useCallback(k=>{u(k)},[]),v=i.useCallback(k=>{y(k)},[y]),A=i.useCallback((k,K)=>{l(L=>(L[k]??null)===(K??null)?L:{...L,[k]:K})},[]),T=i.useCallback((k,K)=>{d(L=>{const N=L[k];return Gb(N,K)?L:{...L,[k]:K}})},[]),S=i.useCallback((k,K)=>{const L=K.get(k)??0;return A(L,k),v(L),L},[v,A]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:g,focusedGroup:n,updateFocusedGroup:y,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:h,setGroupActiveTab:A,groupTabOrders:c,updateGroupTabOrders:M,setGroupTabOrder:T,groupSizes:m,updateGroupSizes:j,isMobile:f,hasHydratedStoredLayout:w,hydrateStoredLayout:p,focusConversationTab:S}}function Yb(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const r=e[0],n=Do(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Xb({urlActiveTab:e,conversations:t,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:l,setSearchParams:c,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:f,handleRefreshHistory:x}){const w=i.useRef(!1),b=i.useRef(!1),p=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,b.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),c(h=>{const M=new URLSearchParams(h);return M.delete("activeTab"),M},{replace:!0}))},[e,t,r,n,a,o,l,c]),i.useEffect(()=>{if(!(b.current||a)&&t.length!==0){if(!e){o(),b.current=!0;return}if(w.current){b.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(b.current||a)&&(o(),b.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,a,o]),i.useEffect(()=>{if(!d){g.current=!1;return}if(!m||g.current||u)return;const y=f.find(h=>h.id===m.routeId);y&&(!y.chats||y.chats.length===0||Yb(y.chats,m))&&(g.current=!0,x())},[d,m,u,f,x])}function ba(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=Do(t);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Ad({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 b=>{try{await e("standalone","launch_ide",{ideType:b,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),f=i.useCallback(async(b,p)=>{try{const g=b||(t==null?void 0:t.daemonId)||"",y=await e(g,"switch_chat",{id:p,sessionId:p,...fs(t)}),h=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||h==="switched"||h==="switched-by-title")return;h===!1||h==="not_found"?ar(a,"⚠️ Session tab not found — try refreshing history"):typeof h=="string"&&h.startsWith("error:")?ar(a,`⚠️ Switch error: ${h}`):ar(a,"⚠️ Session switch failed")}catch(g){console.error("Switch failed",g),ar(a,`❌ Switch failed: ${g.message||"connection error"}`)}},[t,e,a]),x=i.useCallback(async()=>{if(!(!t||l)){c(!0);try{const b=Hs(t);await e(b,"new_chat",{...fs(t)}),o(p=>({...p,[t.tabKey]:Date.now()}))}catch(b){console.error("New chat failed",b)}finally{c(!1)}}},[t,l,e,o]),w=i.useCallback(async()=>{var b,p;if(!(!t||d)){m(!0);try{const g=Hs(t),y=async()=>e(g,"list_chats",{forceExpand:!0,...fs(t)});let h=await y(),M=(h==null?void 0:h.chats)||((b=h==null?void 0:h.result)==null?void 0:b.chats);ba(M,t)&&(await new Promise(j=>setTimeout(j,450)),h=await y(),M=(h==null?void 0:h.chats)||((p=h==null?void 0:h.result)==null?void 0:p.chats)),h!=null&&h.success&&Array.isArray(M)&&(n(t.routeId,M),ba(M,t)&&!ba(r,t)&&ar(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:f,handleNewChat:x,handleRefreshHistory:w}}function Jb(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 Qb(e,t){return e.length!==t.length?!1:e.every((r,n)=>r===t[n])}function cl(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 dl(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 Zb(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 eg(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 ul(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 ml(e){return Array(e).fill(100/e)}function tg({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),f=i.useMemo(()=>Xr(e,m),[e,m]),x=f.assignments,w=i.useMemo(()=>c?1:f.groupCount,[f.groupCount,c]),b=w>1,p=i.useCallback((v,A)=>{t(T=>{const S=new Map(Xr(T,m).assignments);return A===0?S.delete(v):S.set(v,A),S}),n(T=>({...T,[A]:v})),r(A)},[t,m,n,r]),g=i.useCallback(v=>{t(A=>{const T=Xr(A,m).assignments,S=new Map;for(const[k,K]of T)K!==v&&(K>v?S.set(k,K-1):S.set(k,K));return S}),l(A=>{if(A.length<=1)return[];const T=[...A];T.splice(v,1);const S=T.reduce((k,K)=>k+K,0);return S>0?T.map(k=>k/S*100):[]}),r(0)},[t,m,l,r]),y=i.useCallback((v,A)=>{A.preventDefault();const T=u.current;if(!T)return;const S=A.clientX,k=T.offsetWidth,K=o.length===w?[...o]:ml(w),L=P=>{const D=(P.clientX-S)/k*100,C=[...K];C[v]=Math.max(15,K[v]+D),C[v+1]=Math.max(15,K[v+1]-D),l(C)},N=()=>{document.removeEventListener("mousemove",L),document.removeEventListener("mouseup",N),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",N)},[o,w,l]),h=i.useCallback((v,A,T)=>{if(w>=4)return;const S=T==="left"?A:A+1;t(k=>{const K=Xr(k,m).assignments,L=new Map;for(const N of d){const P=K.get(N.tabKey)??0,B=P>=S?P+1:P;B>0&&L.set(N.tabKey,B)}return S>0&&L.set(v,S),L}),l(k=>{const K=k.length===w?[...k]:ml(w),L=K[A]??100/w,N=Math.max(15,L/2),P=Math.max(15,L/2),B=[...K];B[A]=N,B.splice(S,0,P);const D=B.reduce((C,I)=>C+I,0);return B.map(C=>C/D*100)}),n(k=>{const K=ul(k,S);return K[S]=v,K}),a(k=>{const K=ul(k,S);return K[S]=[v],K}),r(S)},[w,t,m,d,l,n,a,r]);i.useEffect(()=>{Jb(e,x)||t(x)},[e,x,t]),i.useEffect(()=>{const{mapping:v,usedGroups:A}=f;n(T=>{const S=dl(T,v);return cl(T,S)?T:S}),a(T=>{const S=dl(T,v);return cl(T,S)?T:S}),r(T=>{const S=c?0:Zb(T,A,v);return T===S?T:S}),l(T=>{const S=c?[]:eg(T,A,f.groupCount);return Qb(T,S)?T:S})},[f,c,n,a,r,l]);const M=i.useMemo(()=>{const v=Array.from({length:w},()=>[]);for(const A of d){const T=x.get(A.tabKey)??0,S=Math.min(T,w-1);v[S].push(A)}return v},[d,x,w]),j=i.useCallback(()=>{t(new Map),r(0)},[t,r]);return{containerRef:u,normalizedGroupAssignments:x,numGroups:w,isSplitMode:b,groupedConvs:M,moveTabToGroup:p,closeGroup:g,handleResizeStart:y,splitTabRelative:h,clearAllSplits:j}}function ga(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 sg(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 Yo(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=ga(t.channel)||ga(e.updateChannel)||ga(e.releaseChannel)||void 0,n=sg(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 Rs(e,t=null){return Yo(e).targetVersion||t}function Td(e){return Yo(e).channel||null}function _d(e){const t=Yo(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 rg({ides:e,sendDaemonCommand:t}){const r="0.9.81",n=i.useMemo(()=>e.filter(f=>f.type!=="adhdev-daemon"?!1:ud(f,Rs(f,r))).sort((f,x)=>Number(wr(x,Rs(x,r)))-Number(wr(f,Rs(f,r)))),[r,e]),a=i.useMemo(()=>n.some(f=>wr(f,Rs(f,r))),[r,n]),o=i.useMemo(()=>n.map(f=>Rs(f,r)).find(f=>typeof f=="string"&&f.trim().length>0)||r,[r,n]),[l,c]=i.useState(!1),[d,m]=i.useState({}),u=i.useCallback(async f=>{var w,b;const x=e.find(p=>p.id===f);if(x){m(p=>({...p,[f]:"upgrading"}));try{const p=await t(f,"daemon_upgrade",_d(x));(w=p==null?void 0:p.result)!=null&&w.upgraded||(b=p==null?void 0:p.result)!=null&&b.success?m(g=>({...g,[f]:"done"})):m(g=>({...g,[f]:"error"}))}catch{m(p=>({...p,[f]:"error"}))}}},[e,t]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:l,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const Ld=80;function mn(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function ng(e){return{...e,createdAt:mn(e.createdAt),updatedAt:mn(e.updatedAt,e.createdAt),lastEventAt:mn(e.lastEventAt,e.updatedAt||e.createdAt)}}function ag(e){const t=Eo(e);return t==="unknown:"?e.id:t}function og(e){return[e.type,Fc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function ig(e,t=Ld){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=ag(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 lg(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=Fn(a,t),c=l.inboxBucket==="needs_attention"?"needs_attention":l.inboxBucket==="task_complete"&&l.unread?"task_complete":null;if(!c)continue;const d=mn(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=og({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(ng({id:m,dedupKey:m,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Tc(a),preview:Bf(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return ig(n)}function cg(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function dg(e){const{conversations:t,liveSessionInboxState:r,maxItems:n=Ld}=e,a=i.useMemo(()=>lg(t,r).slice(0,Math.max(0,n)),[t,r,n]),o=i.useMemo(()=>cg(a),[a]);return{notifications:a,unreadCount:o}}function ug({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 mg=i.createContext(null);function Rd(){return i.useContext(mg)}function Vn(...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 pg(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 Gn(e,t=[]){if(e==="win32"){for(const r of t){if(typeof r!="string")continue;const n=pg(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 fg(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 hg(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=hg(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 xg(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 Pd(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:xg(r.template||"",{...t,serverName:r.serverName||"adhdev-mesh"})}}function bg(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 is(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Dd(e){return Pr(e)||e.tabKey||e.routeId||null}function Ed(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=Ft(e.conversations,n)||e.conversations.find(l=>l.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return t||r||n||null}function ss(e){return String(e||"").trim()}function $d(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Rn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function gg(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function yg(e,t){const r=ss(e.providerSessionId),n=ss(e.targetSessionId),a=t.find(o=>{const l=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(ss).filter(Boolean);return!!(r&&l.includes(r)||n&&l.includes(n))});return a?a.tabKey:n||r||null}function vg(e,t,r){if(t.event!=="agent:generating_completed")return null;const n=$d(t.daemonId);if(n&&n!==e.machineId)return null;const a=ss(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=ss(e.resumeSessionId),l=ss(e.launchedSessionId),c=ss(t.providerSessionId),d=ss(t.targetSessionId);if(o&&o!==c&&o!==d||l&&l!==c&&l!==d)return null;const m=Rn(e.workspacePath);if(m){const u=Rn(t.workspaceName);if(u&&!gg(u,m))return null}return yg(t,r)}function pl(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function wg({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=Rn(n.workspacePath),m=e.find(f=>{var g,y,h,M;if(!f||f.type==="adhdev-daemon"||$d(f.daemonId||f.id)!==n.machineId||(Ir(f)?"cli":Es(f)?"acp":"ide")!==n.kind)return!1;const b=String(f.agentType||f.type||"");if(n.providerType&&b!==n.providerType)return!1;if(n.resumeSessionId)return String(f.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const j=String(n.launchedSessionId||"");return[f.providerSessionId,f.sessionId,f.instanceId,f.id].map(A=>String(A||"")).filter(Boolean).includes(j)}if(d){const j=Rn(f.workspace||f.runtimeWorkspaceLabel);return j?j===d:!1}return Number(f.lastUpdated||f._lastUpdate||f.timestamp||((M=(h=(y=(g=f.activeChat)==null?void 0:g.messages)==null?void 0:y.at)==null?void 0:h.call(y,-1))==null?void 0:M.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=Ed({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=vg(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 jg({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const l=Rd(),c=i.useCallback(async(p,g)=>qn(e,p,g),[e]),d=i.useCallback(async(p,g)=>{if(!g.trim())return{ok:!1,error:"Choose a workspace path first."};try{const y=await e(p,"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(p,g,y)=>{var h;try{const M={ideType:g,enableCdp:!0};(h=y==null?void 0:y.workspacePath)!=null&&h.trim()&&(M.workspace=y.workspacePath.trim());const j=await e(p,"launch_ide",M);return!(j!=null&&j.success)&&(j==null?void 0:j.success)!==void 0?{ok:!1,error:(j==null?void 0:j.error)||"Could not launch IDE"}:(t({machineId:p,kind:"ide",providerType:g,workspacePath:(y==null?void 0:y.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(M){return{ok:!1,error:M instanceof Error?M.message:"Could not launch IDE"}}},[e,t]),u=i.useCallback(async(p,g,y,h)=>{var j,v,A;const M=Date.now();try{const T={cliType:y};(j=h==null?void 0:h.workspacePath)!=null&&j.trim()?T.dir=h.workspacePath.trim():h!=null&&h.workspaceId&&(T.workspaceId=h.workspaceId),(v=h==null?void 0:h.resumeSessionId)!=null&&v.trim()&&(T.resumeSessionId=h.resumeSessionId.trim()),Array.isArray(h==null?void 0:h.cliArgs)&&h.cliArgs.length>0&&(T.cliArgs=h.cliArgs),(A=h==null?void 0:h.initialModel)!=null&&A.trim()&&(T.initialModel=h.initialModel.trim());const S=await e(p,"launch_cli",T),k=(S==null?void 0:S.result)||S,K=(k==null?void 0:k.sessionId)||(k==null?void 0:k.id);return S!=null&&S.success&&K?(t({machineId:p,kind:g,providerType:y,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,launchedSessionId:K,startedAt:M}),{ok:!0}):S!=null&&S.success?(t({machineId:p,kind:g,providerType:y,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:M}),{ok:!0}):{ok:!1,error:(S==null?void 0:S.error)||(k==null?void 0:k.error)||`Could not launch ${g.toUpperCase()} session`}}catch(T){return pl(T)?(t({machineId:p,kind:g,providerType:y,workspacePath:(h==null?void 0:h.workspacePath)||null,resumeSessionId:(h==null?void 0:h.resumeSessionId)||null,startedAt:M}),{ok:!0}):{ok:!1,error:T instanceof Error?T.message:`Could not launch ${g.toUpperCase()} session`}}},[r,e,t]),f=i.useCallback(async p=>{var g;if(l!=null&&l.listMeshes)return l.listMeshes(p);if(!p)return[];try{const y=await e(p,"list_meshes",{}),h=(y==null?void 0:y.result)??y;if((h==null?void 0:h.success)===!1)throw new Error((h==null?void 0:h.error)||"Could not load meshes");return(Array.isArray(h==null?void 0:h.meshes)?h.meshes:Array.isArray((g=h==null?void 0:h.result)==null?void 0:g.meshes)?h.result.meshes:[]).map(j=>{var v;return{id:String((j==null?void 0:j.id)||""),name:String((j==null?void 0:j.name)||(j==null?void 0:j.id)||"Untitled mesh"),repoIdentity:(j==null?void 0:j.repoIdentity)||(j==null?void 0:j.repo_identity)||null,workspace:Array.isArray(j==null?void 0:j.nodes)&&j.nodes.length>0?String(((v=j.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(j==null?void 0:j.nodes)?j.nodes.length:void 0,status:(j==null?void 0:j.status)||null}}).filter(j=>j.id)}catch(y){throw console.error("List meshes failed",y),y}},[l,e]),x=i.useCallback(async(p,g,y)=>{if(!g.trim())return{ok:!1,error:"Choose a mesh first."};if(l!=null&&l.launchMeshCoordinator)return l.launchMeshCoordinator(p,g,y);const h=Date.now();try{const M={meshId:g.trim()};y.trim()&&(M.cliType=y.trim());const j=await e(p,"launch_mesh_coordinator",M),v=(j==null?void 0:j.result)??j;if((v==null?void 0:v.success)===!1||(j==null?void 0:j.success)===!1){const T=String((v==null?void 0:v.code)||(j==null?void 0:j.code)||""),S=bg((v==null?void 0:v.meshCoordinatorSetup)||(v==null?void 0:v.manualSetup)||(j==null?void 0:j.meshCoordinatorSetup)||(j==null?void 0:j.manualSetup));return{ok:!1,error:(v==null?void 0:v.error)||(j==null?void 0:j.error)||"Could not launch mesh coordinator",code:T||void 0,manualSetup:S}}const A=(v==null?void 0:v.sessionId)||(v==null?void 0:v.id);return A?r(A):t({machineId:p,kind:"cli",providerType:(v==null?void 0:v.cliType)||y.trim()||void 0,workspacePath:(v==null?void 0:v.workspace)||null,startedAt:h}),{ok:!0}}catch(M){return pl(M)?(t({machineId:p,kind:"cli",providerType:y.trim()||void 0,startedAt:h}),{ok:!0}):{ok:!1,error:M instanceof Error?M.message:"Could not launch mesh coordinator"}}},[l,r,e,t]),w=i.useCallback(async(p,g)=>{if(!p||!g)return[];try{const y=await e(p,"list_saved_sessions",{providerType:g,kind:"cli",limit:30}),h=(y==null?void 0:y.result)??y;return Array.isArray(h==null?void 0:h.sessions)?h.sessions:[]}catch(y){return console.error("List saved sessions failed",y),[]}},[e]),b=i.useCallback(async p=>{await jd({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:f,handleLaunchMeshCoordinator:x,handleListMachineSavedSessions:w,setActiveCliViewMode:b}}function kg(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 Sg(e,t,r=Date.now()){return!e||!kg(t)?null:{tabKey:e,nonce:r}}function Ng({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),f=i.useMemo(()=>{var g,y;if(!e){if(c){const h=t.find(M=>M.tabKey===c);if(h)return h}return r[0]}const p=n[a];if(p){const h=t.find(M=>M.tabKey===p);if(h)return h}return((g=o[a])==null?void 0:g[0])||((y=o[0])==null?void 0:y[0])},[t,c,a,n,o,e,r]),x=i.useCallback(p=>{d(p)},[]),w=i.useCallback(p=>{d(p.tabKey),l(g=>{const y=new URLSearchParams(g),h=Ff(p);return h?y.set("activeTab",h):y.delete("activeTab"),y},{replace:!0})},[l]),b=i.useCallback((p,g)=>{const y=Sg(p,g);y&&u(y)},[]);return{activeConv:f,openDesktopConversation:w,requestScrollToBottom:b,scrollToBottomRequest:m,setDesktopActiveTab:x}}function Cg(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 Ig(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 Mg({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=kn(e,r),f=Ig({tabKey:e.tabKey,historySessionId:Pr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:vs(e),liveState:u}),x=f.autoReadKey,w=Cg({autoReadKey:x,shouldMarkSeen:f.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!f.shouldMarkSeen){w.shouldCancelPending&&m(),a.current=x;return}if(!w.shouldSchedule)return;w.shouldCancelPending&&m();const b=()=>{if(document.visibilityState!=="visible"||a.current===x)return;a.current=x,o.current=null,l.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const g=f.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:g,completionMarker:f.completionMarker}).catch(()=>{})};if(o.current=w.nextPendingKey,document.visibilityState==="visible"){l.current=setTimeout(b,1500);const g=()=>{document.visibilityState!=="visible"&&l.current&&(clearTimeout(l.current),l.current=null)};d.current=g,document.addEventListener("visibilitychange",g);return}const p=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(b,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,t,r,n]),i.useEffect(()=>()=>{l.current&&clearTimeout(l.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function ya(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 Ag({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:l,setClearedTabs:c,setSearchParams:d}){var I;const[m,u]=i.useState(!1),[f,x]=i.useState([]),[w,b]=i.useState(()=>Nt()),[p,g]=i.useState(!1),[y,h]=i.useState(null),M=i.useRef(null),j=i.useMemo(()=>r||t||e,[e,r,t]),v=!!j&&at(j)&&!st(j),A=i.useMemo(()=>{if(!j||!v)return null;const E=j.daemonId||j.routeId||"",R=zt(j),$=ya(j);return`${E}:${R}:${j.providerSessionId||""}:${$}`},[j,v]),T=i.useMemo(()=>!j||!v?"":ya(j),[j,v]),{isCreatingChat:S,isRefreshingHistory:k,handleSwitchSession:K,handleNewChat:L,handleRefreshHistory:N}=Ad({sendDaemonCommand:a,activeConv:j,chats:(I=n.find(E=>E.id===(j==null?void 0:j.routeId)))==null?void 0:I.chats,updateRouteChats:o,setToasts:l,setClearedTabs:c}),P=i.useCallback(()=>{u(!0)},[]),B=i.useCallback(()=>{u(!1)},[]),D=i.useCallback(async()=>{if(!(!j||!v||p)){g(!0);try{const E=j.daemonId||j.routeId,R=zt(j),$=ya(j),z=await a(E,"list_saved_sessions",{agentType:R,providerType:R,kind:"cli",limit:50,...j.providerSessionId?{providerSessionId:j.providerSessionId}:{},...$?{workspace:$}:{}}),F=(z==null?void 0:z.result)??z;x(Array.isArray(F==null?void 0:F.sessions)?F.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),x([])}finally{g(!1)}}},[j,p,v,a]);i.useEffect(()=>{if(!m){M.current=null;return}if(!v){M.current=null,x([]),g(!1);return}!A||p||M.current!==A&&(M.current=A,D())},[D,m,p,v,A]);const C=i.useCallback(async E=>{if(!j||!v||!E.providerSessionId||!E.workspace)return;const R=j.daemonId||j.routeId,$=zt(j);try{h(E.providerSessionId);const z=await a(R,"launch_cli",{cliType:$,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:jc(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),F=(z==null?void 0:z.result)??z,me=typeof(F==null?void 0:F.sessionId)=="string"?F.sessionId:typeof(F==null?void 0:F.id)=="string"?F.id:"";me&&d(ie=>{const ee=new URLSearchParams(ie);return ee.set("activeTab",me),ee},{replace:!0}),B()}catch(z){console.error("Resume saved session failed",z)}finally{h(null)}},[B,j,v,a,d]);return{historyModalOpen:m,openHistoryModal:P,closeHistoryModal:B,historyTargetConv:j,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:S,isHistoryRefreshingHistory:k,handleHistorySwitchSession:K,handleHistoryNewChat:L,handleHistoryRefresh:N,savedHistorySessions:f,savedHistoryFilters:w,setSavedHistoryFilters:b,missingWorkspaceResumePath:T,isSavedHistoryLoading:p,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:D,handleResumeSavedHistorySession:C}}function Tg({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}){const[d,m]=i.useState(null),[u,f]=i.useState(null),x=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 h=d!=null&&d.tabKey?o.find(M=>M.tabKey===d.tabKey):a?o.find(M=>M.tabKey===a):null;return(h==null?void 0:h.routeId)===y?h:Ft(o,y)},[o,d,a]),b=i.useMemo(()=>{if(w)return l.find(y=>y.id===w.routeId)},[l,w]);i.useEffect(()=>{x&&(m({routeId:x.routeId,tabKey:Bi(x)}),f(x),r({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,r,x]);const p=i.useCallback(y=>{y&&(m({routeId:y.routeId,tabKey:Bi(y)}),f(y))},[]),g=i.useCallback(()=>{m(null),f(null)},[]);return{remoteDialogConv:w,remoteDialogIdeEntry:b,remoteDialogActiveConv:u,setRemoteDialogActiveConv:f,openRemoteDialog:p,closeRemoteDialog:g}}function _g({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:x,setRemoteDialogActiveConv:w,openRemoteDialog:b,closeRemoteDialog:p}=Tg({isMobile:e,location:t,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}),[g,y]=i.useState(!1),[h,M]=i.useState(null),j=i.useCallback(async T=>{const S=T||d;!S||!at(S)&&!st(S)||(M(S),y(!0))},[d]),v=i.useCallback(()=>{y(!1),M(null)},[]),A=i.useCallback(async T=>{const S=h||d;if(!S||!at(S)&&!st(S)){v();return}y(!1);try{const k=zt(S),K=S.routeId||S.daemonId||"";await m(K,"stop_cli",{cliType:k,targetSessionId:S.sessionId,mode:T})}catch(k){console.error("Stop CLI failed:",k)}finally{M(null)}},[d,v,h,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:f,remoteDialogActiveConv:x,setRemoteDialogActiveConv:w,openRemoteDialog:b,closeRemoteDialog:p,cliStopDialogOpen:g,cliStopTargetConv:h,requestCliStop:j,cancelCliStop:v,confirmCliStop:A}}function Bd({conversation:e,className:t="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var M,j;const l=qs(),c=Ms(e),d=o?null:Ac(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),x=Ks(e),w=Of(e),b=(M=e.settings)==null?void 0:M.meshNodeFor,p=e.meshQueueStats,g=(j=e.settings)==null?void 0:j.meshCoordinatorFor;if(!m&&!u&&!f&&!d&&!b&&!p)return null;const y=i.useCallback(()=>{if(n){n();return}c&&l("/dashboard",{state:{openMachineId:c}})},[c,l,n]),h=i.useCallback(()=>{if(r){r();return}const v=Dd(e);v&&l(is(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:h,title:w,children:[s.jsx(_t,{size:12}),s.jsx("span",{children:w})]}):s.jsxs("span",{className:"conversation-meta-chip",title:w,children:[s.jsx(_t,{size:12}),s.jsx("span",{children:w})]})),u&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Ws,{size:12}),s.jsx("span",{children:x})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:x,children:[s.jsx(Ws,{size:12}),s.jsx("span",{children:x})]}),d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:d,children:[s.jsx(as,{size:12}),s.jsx("span",{children:d})]}):s.jsxs("span",{className:"conversation-meta-chip",title:d,children:[s.jsx(as,{size:12}),s.jsx("span",{children:d})]})),b&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(as,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),g&&p&&s.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[s.jsx(Bm,{size:12}),s.jsxs("span",{children:[p.pending," Pending"]})]})]})}function va(e,t=!0){return(e??!0)&&t}const Xo=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:f,isFocusingAgent:x,actionLogs:w,userName:b,scrollToBottomRequestNonce:p,isInputActive:g=!0,isVisible:y=!0}){const h=n,M=!n,j=va(y,h),v=va(y,M),A=va(y),T=xd(t),S=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(yc,{activeConv:S,onModalButton:l}),s.jsx(Bd,{conversation:S,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),S.transport!=="pty"&&S.transport!=="acp"&&S.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(Cr,{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,S.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:h?"visible":"hidden",pointerEvents:h?"auto":"none"},children:s.jsx(Zh,{activeConv:S,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:j,isInputActive:g&&j})}),s.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:M?"visible":"hidden",pointerEvents:M?"auto":"none"},children:s.jsx(so,{activeConv:S,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:w,userName:b,scrollToBottomRequestNonce:p,isInputActive:g&&v,isVisible:v})})]}):s.jsx(so,{activeConv:S,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:f,isFocusingAgent:x,actionLogs:w,userName:b,scrollToBottomRequestNonce:p,isInputActive:g&&A,isVisible:A})]})},(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 Lg({selectedConversation:e,isAcp:t,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:l,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:f,onOpenHistory:x,onOpenRemote:w,onOpenMeshGraph:b,onStopCli:p,cliViewMode:g,onSetCliViewMode:y,handleSendChat:h,handleFocusAgent:M,handleModalButton:j,handleRelaunch:v}){var L;const A=i.useRef(null),T=at(e)&&!t,S=T&&g==="terminal",k=!!e.daemonId&&typeof((L=e.settings)==null?void 0:L.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,K=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 ${K} 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(yo,{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(Bd,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>f(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[T&&g&&s.jsx(Bo,{mode:g,onChange:y,compact:!0}),T&&p&&s.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(jt,{size:14})}),k&&b&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>b(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(rs,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:s.jsx(vo,{size:14})}),!t&&!T&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",children:s.jsx(_t,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(Xo,{activeConv:e,clearToken:0,isCliTerminal:S,ideEntry:n,terminalRef:A,handleModalButton:j,handleRelaunch:v,handleSendChat:h,isSendingChat:l,sendFeedbackMessage:c,handleFocusAgent:M,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const wa={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 Rg(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Od(){const[e,t]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),l=e==="unix"?"unix":r;i.useEffect(()=>{t(Rg())},[]);const c=i.useCallback(()=>{navigator.clipboard.writeText(wa[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:wa[l].prompt}),s.jsx("span",{className:"flex-1 break-all",children:wa[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 Fd({section:e,onSectionChange:t}){const r=[{key:"machines",label:"Machines",icon:_t},{key:"chats",label:"Chats",icon:Jt}];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 As({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 ur({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 Pg({conversation:e,onCancel:t,onConfirm:r}){const n=ut(e),a=Ns(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 K;const c=t==="needs_attention"||t==="task_complete",d=t==="working",m=t==="earlier",u=t==="task_complete",{isReconnecting:f,isConnecting:x}=Ys(e.conversation),w=ut(e.conversation),b=Ns(e.conversation),p=Yc(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",h=m?"text-text-secondary":"text-text-primary",M=m?"text-text-muted":"text-text-secondary",j=m?"text-text-secondary opacity-80":"text-text-muted",v=m?"text-text-muted opacity-80":"text-text-muted",A=!d&&!u,T=!!e.conversation.daemonId&&typeof((K=e.conversation.settings)==null?void 0:K.meshCoordinatorFor)=="string"&&e.conversation.settings.meshCoordinatorFor.length>0,S="text-[color:var(--status-warning)]",k=L=>{if(!l)return;L.preventDefault(),L.stopPropagation();const N=l==null?void 0:l(e.conversation);Promise.resolve(N).catch(P=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",P)})};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(wo,{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(rs,{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:k,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 ${h}`,children:w}),A&&s.jsx("span",{className:`text-[11px] font-medium shrink-0 ${v}`,children:gc(e.timestamp)})]}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${M}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(Us,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),f?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${S} animate-pulse`,children:"Reconnecting…"})]}):x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):p==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:S,children:"Action needed"})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${j}`,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 fl({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 Dg({section:e,attentionItems:t,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:l,getAvatarText:c,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:f,onHideConversation:x,onOpenMeshGraph:w,onOpenNewSession:b,onOpenMachine:p,onOpenSettings:g,onSectionChange:y,wsStatus:h="connected",isStandalone:M=!1,onCollectChatDebugBundle:j}){const[v,A]=i.useState(null),T=h==="disconnected"||h==="reconnecting"||h==="offline"||h==="auth_failed",S=l.length>0,k=t.length>0||r.length>0||n.length>0||a.length>0,K=e==="machines"?"Machines":"Chats",L=M?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",N=M?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",P=i.useCallback(async C=>{const I=Hs(C);if(!I)return;const E=Array.isArray(C.messages)?C.messages:[],R=Dc({activeConv:C,visibleMessages:E,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:E.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),$=await m(I,"get_chat_debug_bundle",{...fs(C),delivery:"daemon_file",frontendSnapshot:R}),z=In($),F=Bc(z),me=await $c(F);me==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ot.showToast(Ec(z,{locatorCopyStatus:me}),me==="failed"?"warning":"success")},[d,m]),B=j||P,D=i.useCallback(()=>{v&&(x==null||x(v),A(null))},[v,x]);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:K}),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(Bn,{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($n,{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] ${N}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:T?s.jsx(ur,{icon:s.jsx(fl,{}),title:h==="offline"?"Network offline":h==="auth_failed"?"Session expired":"Reconnecting",subtitle:h==="offline"?"Waiting for network…":h==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):l.length===0?s.jsx(ur,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:M?"Waiting for your daemon":"Connect your machines",subtitle:M?"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:!M&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Od,{})})}):s.jsx(As,{children:l.map((C,I)=>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] ${I>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(C.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(C.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:C.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:C.unread>0?s.jsxs("span",{className:"text-accent-primary",children:[C.unread," new"]}):C.total>0?`${C.total} chats`:"Idle"})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:C.subtitle}),C.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[C.total," chat",C.total!==1?"s":"",C.unread>0?` · ${C.unread} unread`:""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},C.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(As,{children:t.map((C,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Zr,{item:C,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>A(C.conversation):void 0,onOpenMeshGraph:w,onCollectChatDebugBundle:B})},C.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(As,{children:r.map((C,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Zr,{item:C,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>A(C.conversation):void 0,onOpenMeshGraph:w,onCollectChatDebugBundle:B})},C.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(As,{children:n.map((C,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Zr,{item:C,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>A(C.conversation):void 0,onOpenMeshGraph:w,onCollectChatDebugBundle:B})},C.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(As,{children:a.map((C,I)=>s.jsx("div",{className:I>0?"border-t border-border-subtle/70":"",children:s.jsx(Zr,{item:C,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:x?()=>A(C.conversation):void 0,onOpenMeshGraph:w,onCollectChatDebugBundle:B})},C.conversation.tabKey))}):k?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):T?s.jsx(ur,{icon:s.jsx(fl,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):S?s.jsx(ur,{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(Jt,{size:20})}),title:"No conversations yet",subtitle:Qc,children:b&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:b,"aria-label":Ht,title:Ht,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:Ht})]})}):s.jsx(ur,{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(As,{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:f,children:"Restore all"})]})})})]}),e==="chats"&&b&&k&&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:b,"aria-label":Ht,title:Ht,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(Pg,{conversation:v,onCancel:()=>A(null),onConfirm:D}),s.jsx(Fd,{section:e,onSectionChange:y})]})}function Eg(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 Wd(e){const t=[e.workspace||"Workspace unknown"],r=Ss(e.summaryMetadata);r&&t.push(r),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const n=Eg(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Yn({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,f]=i.useState(r);i.useEffect(()=>{f(r)},[r]);const x=fg(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:()=>{!x||a||d(x)},disabled:!x||a,children:[s.jsx(yo,{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:b=>f(b.target.value),onKeyDown:b=>{b.key!=="Enter"||!w||a||(b.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(b=>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(b.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(ks,{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:b.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:b.path})]})]},b.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 Jo({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:f,showModelInput:x,modelValue:w,onModelChange:b,historyProviderNode:p,onConfirm:g,onCancel:y}){const h=n==null?void 0:n.find(M=>M.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:M=>o(M.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(M=>s.jsx("option",{value:M.key,children:M.label},M.key))}),(h==null?void 0:h.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:h.description})]}),p,r.map(M=>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:M.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:M.value})]},`${M.label}:${M.value}`)),x&&b&&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:M=>b(M.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&&f&&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:M=>f(M.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(ko,{size:14}),d?c:l]})]})]})})}function hl(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function ws(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?"⭐ ":""}${hl(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:hl(l),description:l,workspaceId:null,workspacePath:l}),n){const d=`saved:${n}`;if(o.some(m=>m.key===d))return{options:o,selectedKey:d}}return c?{options:o,selectedKey:`saved:${c.id}`}:l?{options:o,selectedKey:`custom:${l}`}:{options:o,selectedKey:"__home__"}}function $g(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Bg(e){return[$g(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Og(e){return e.lastLaunchedAt?On(e.lastLaunchedAt):""}function Kd(e){return{metaText:Bg(e),updatedLabel:Og(e)}}function ja(e,t,r){return e?"ide":t>0?"cli":r>0?"acp":null}function Fg({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]),f=e.defaultWorkspaceId||null,[x,w]=i.useState(f||((ct=u[0])==null?void 0:ct.id)||""),[b,p]=i.useState(""),[g,y]=i.useState(""),[h,M]=i.useState([]),[j,v]=i.useState(!1),[A,T]=i.useState(""),[S,k]=i.useState(!1),[K,L]=i.useState(ja(m,t.length,r.length)),N=i.useRef(null),[P,B]=i.useState(null),D=i.useRef("__home__"),[C,I]=i.useState("__home__"),[E,R]=i.useState(""),[$,z]=i.useState(""),[F,me]=i.useState(""),[ie,ee]=i.useState([]),[ce,je]=i.useState(()=>Nt().textQuery),[Ne,q]=i.useState(()=>Nt().workspaceQuery),[ge,he]=i.useState(()=>Nt().modelQuery),[we,xe]=i.useState(()=>Nt().resumableOnly),[Se,J]=i.useState(()=>Nt().sortMode),[fe,ae]=i.useState(!1),[ue,oe]=i.useState(!1),de=i.useRef(null),Q=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&l(e.id,{minFreshMs:3e4}).catch(()=>{})},[l,e]);const ve=x==="__custom__"?b.trim():((mt=u.find(O=>O.id===x))==null?void 0:mt.path)||"",le=x==="__custom__"&&!!ve&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),pe=x!=="__custom__"&&((pt=u.find(O=>O.id===x))==null?void 0:pt.path)||"",ne=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),p(be.path),M(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__"),k(!0);const O=Gn(e.platform,Vn(b.trim(),pe,ne,e.defaultWorkspacePath,(be=u.find(Te=>Te.id===f))==null?void 0:be.path,u.map(Te=>Te.path)));Ie(O)},[b,f,Ie,ne,pe,e.platform,u]),_e=i.useCallback(O=>{if(O!=null&&O.workspaceId){w(O.workspaceId),p("");return}if(O!=null&&O.workspacePath){w("__custom__"),p(O.workspacePath);return}w(""),p("")},[]),H=i.useCallback(O=>{if(w(O),O==="__custom__"){Ce();return}p("")},[Ce]),Me=i.useCallback(O=>{w("__custom__"),p(O)},[]),Ae=i.useCallback((O,be)=>{N.current=be,D.current=O.selectedWorkspaceKey||"__home__",I(O.selectedWorkspaceKey||"__home__"),R(O.initialArgs||""),z(O.initialModel||""),me(""),ee([]);const Te=O.providerType?`${e.id}:${O.providerType}`:null;if(dx(Q.current,Te)){const Be=Nt();je(Be.textQuery),q(Be.workspaceQuery),he(Be.modelQuery),xe(Be.resumableOnly),J(Be.sortMode)}Q.current=Te,B(O),O.providerType&&o&&(ae(!0),o(O.providerType).then(Be=>ee(Be||[])).catch(Be=>console.warn("Failed to load saved sessions",Be)).finally(()=>ae(!1)))},[o,e.id]),Ke=i.useMemo(()=>Zc(ie,{textQuery:ce,workspaceQuery:Ne,modelQuery:ge,resumableOnly:we,sortMode:Se}),[ge,we,ie,Se,ce,Ne]);i.useEffect(()=>{F&&(Ke.some(O=>O.providerSessionId===F)||me(""))},[Ke,F]);const Ve=i.useCallback(()=>{N.current&&(oe(!0),N.current().finally(()=>{N.current=null,oe(!1),B(null)}))},[]),Xe=i.useCallback(()=>{N.current=null,B(null)},[]),Ye=i.useCallback(O=>{D.current=O,I(O)},[]);return i.useEffect(()=>{var O;de.current!==e.id&&(de.current=e.id,w(f||((O=u[0])==null?void 0:O.id)||"__custom__"),p(""),y(""),M([]),T(""),k(!1),je(Nt().textQuery),q(Nt().workspaceQuery),he(Nt().modelQuery),xe(Nt().resumableOnly),J(Nt().sortMode),Q.current=null,L(ja(m,t.length,r.length)))},[r.length,t.length,f,m,e.id,u]),i.useEffect(()=>{var O;x!=="__custom__"&&(x&&u.some(be=>be.id===x)||w(f||((O=u[0])==null?void 0:O.id)||"__custom__"))},[f,x,u]),i.useEffect(()=>{K==="ide"&&m||K==="cli"&&t.length>0||K==="acp"&&r.length>0||L(ja(m,t.length,r.length))},[K,r.length,t.length,m]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:f,workspaceChoice:x,customWorkspacePath:b,browseCurrentPath:g,browseDirectories:h,browseBusy:j,browseError:A,browseDialogOpen:S,activeLauncherKind:K,launchConfirm:P,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:C,launchConfirmArgs:E,launchConfirmModel:$,launchConfirmResumeId:F,launchConfirmSavedSessions:ie,launchConfirmTextFilter:ce,launchConfirmWorkspaceFilter:Ne,launchConfirmModelFilter:ge,launchConfirmResumableOnly:we,launchConfirmSortMode:Se,filteredLaunchConfirmSavedSessions:Ke,launchConfirmSessionsLoading:fe,launchConfirmBusy:ue,resolvedWorkspacePath:ve,canCreateMissingWorkspace:le,openBrowseDialog:Ce,loadBrowsePath:Ie,handleWorkspaceChoiceChange:H,chooseCustomWorkspacePath:Me,setCustomWorkspacePath:p,setBrowseDialogOpen:k,setActiveLauncherKind:L,openLaunchConfirm:Ae,handleConfirmLaunch:Ve,closeLaunchConfirm:Xe,setWorkspaceSelectionFromOption:_e,setLaunchConfirmWorkspaceKeyAndSync:Ye,setLaunchConfirmArgs:R,setLaunchConfirmModel:z,setLaunchConfirmResumeId:me,setLaunchConfirmTextFilter:je,setLaunchConfirmWorkspaceFilter:q,setLaunchConfirmModelFilter:he,setLaunchConfirmResumableOnly:xe,setLaunchConfirmSortMode:J}}function Wg({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:l,machineAction:c,isStandalone:d,section:m,showBottomNav:u,onBack:f,onSectionChange:x,onOpenConversation:w,onOpenRecent:b,onOpenMachineDetails:p,onMachineUpgrade:g,onLaunchDetectedIde:y,onAddWorkspace:h,onBrowseDirectory:M,onLaunchWorkspaceProvider:j,onListSavedSessions:v}){const A=C=>C==="ide"?"IDE":C==="cli"?"CLI":"ACP",T=r.slice(0,4),S=t.slice(0,3),k=Fg({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:M,onListSavedSessions:v}),K=i.useMemo(()=>T.map(C=>{const{metaText:I,updatedLabel:E}=Kd(C);return{key:`recent-launch:${C.id}`,primary:C.label,secondary:I,updatedLabel:E,onClick:()=>{const{options:R,selectedKey:$}=ws({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspacePath:C.workspace});k.openLaunchConfirm({title:C.kind==="ide"?xs("restart-ide",C.label):C.providerSessionId?Wo(C.label):xs("start-fresh",C.label),description:C.kind==="ide"?bs("restart-ide"):C.providerSessionId?Ko():bs("start-fresh"),confirmLabel:C.kind==="ide"?zs("restart-ide"):C.providerSessionId?An(!0):zs("start-fresh"),busyLabel:C.kind==="ide"?Vs("restart-ide"):C.providerSessionId?Oo(!0):Vs("start-fresh"),workspaceOptions:R,selectedWorkspaceKey:$,details:[{label:"Mode",value:A(C.kind)},...C.providerType?[{label:"Provider",value:C.providerType}]:[]]},async()=>{const z=R.find(F=>F.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(z),await b({...C,workspace:(z==null?void 0:z.workspacePath)??null})})}}}),[k,b,T]),L=i.useMemo(()=>S.map(C=>({key:`recent-chat:${C.conversation.tabKey}`,primary:ut(C.conversation),secondary:Yh(C.conversation,{timestampLabel:C.timestamp?gc(C.timestamp):null}),unread:C.unread,onClick:()=>w(C.conversation)})),[w,S]),N=k.showAllRecent?K:K.slice(0,4),P=K.length>0,B=L.length>0,D=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 ${D} 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:f,type:"button","aria-label":"Back",children:s.jsx(yo,{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:Tt(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:[B&&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(C=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${C.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:C.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:C.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))})]}),P&&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:N.map(C=>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:C.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:C.primary}),C.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:C.secondary})]},C.key))}),K.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:()=>k.setShowAllRecent(C=>!C),children:k.showAllRecent?"Show fewer":`Show ${K.length-4} more`})})]}),(k.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:k.workspaceChoice,onChange:C=>k.handleWorkspaceChoiceChange(C.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:k.workspaceRows.length>0?s.jsxs(s.Fragment,{children:[k.workspaceRows.map(C=>s.jsxs("option",{value:C.id,children:[C.id===k.defaultWorkspaceId?"⭐ ":"",Wn(C.path,C.label)||C.path]},C.id)),s.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):s.jsx("option",{value:"__custom__",children:"Select workspace…"})}),k.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(ks,{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:k.resolvedWorkspacePath||k.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:k.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:()=>{k.resolvedWorkspacePath&&h(k.resolvedWorkspacePath)},disabled:!k.resolvedWorkspacePath||k.browseBusy,children:"Save as workspace"})]})]}),k.resolvedWorkspacePath&&s.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath})]})}),s.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[k.hasIdeOptions&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&s.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.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:()=>k.setActiveLauncherKind("acp"),children:"ACP"})]}),k.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:k.activeLauncherKind==="ide"?"Choose an IDE":k.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),s.jsx("div",{className:"grid grid-cols-1 gap-2",children:k.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(C=>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:I,selectedKey:E}=ws({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspaceId:k.workspaceChoice!=="__custom__"?k.workspaceChoice:null,currentWorkspacePath:k.resolvedWorkspacePath});k.openLaunchConfirm({title:`Launch ${C.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:I,selectedWorkspaceKey:E,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:C.name}]},async()=>{const R=I.find($=>$.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(R),y(C.type,{workspacePath:(R==null?void 0:R.workspacePath)??null})})},children:[s.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:C.name}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath||"Use selected workspace"})]},C.type)):(k.activeLauncherKind==="cli"?n:a).map(C=>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 I=k.activeLauncherKind==="cli"?"cli":"acp",{options:E,selectedKey:R}=ws({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspaceId:k.workspaceChoice!=="__custom__"?k.workspaceChoice:null,currentWorkspacePath:k.resolvedWorkspacePath});k.openLaunchConfirm({title:`Launch ${C.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${I.toUpperCase()}`,workspaceOptions:E,selectedWorkspaceKey:R,details:[{label:"Mode",value:I.toUpperCase()},{label:"Provider",value:C.displayName}],showArgsInput:!0,showModelInput:I==="acp",initialArgs:"",initialModel:"",providerType:C.type},async()=>{const $=E.find(z=>z.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption($),j(I,C.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:k.launchConfirmArgs,model:k.launchConfirmModel,resumeSessionId:k.launchConfirmResumeId||null})})},children:[s.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[C.icon?`${C.icon} `:"",C.displayName]}),s.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath||"Use selected workspace"})]},C.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,k.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:()=>h(k.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:p,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"})]})]})]})]}),k.browseDialogOpen&&s.jsx(Yn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:k.browseCurrentPath,directories:k.browseDirectories,busy:k.browseBusy,error:k.browseError,confirmLabel:"Use this folder",onClose:()=>k.setBrowseDialogOpen(!1),onNavigate:C=>{k.loadBrowsePath(C)},onConfirm:C=>{k.chooseCustomWorkspacePath(C),k.setBrowseDialogOpen(!1)}}),k.launchConfirm&&s.jsx(Jo,{title:k.launchConfirm.title,description:k.launchConfirm.description,details:k.launchConfirm.details,workspaceOptions:k.launchConfirm.workspaceOptions,selectedWorkspaceKey:k.launchConfirmWorkspaceKey,onWorkspaceChange:k.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:k.launchConfirm.providerType?An(!!k.launchConfirmResumeId):k.launchConfirm.confirmLabel,busyLabel:k.launchConfirm.providerType?void 0:k.launchConfirm.busyLabel,busy:k.launchConfirmBusy,showArgsInput:k.launchConfirm.showArgsInput,argsValue:k.launchConfirmArgs,onArgsChange:k.setLaunchConfirmArgs,showModelInput:k.launchConfirm.showModelInput,modelValue:k.launchConfirmModel,onModelChange:k.setLaunchConfirmModel,historyProviderNode:k.launchConfirm.providerType&&(k.launchConfirmSessionsLoading||k.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"}),k.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:Fo()}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:k.launchConfirmTextFilter,onChange:C=>k.setLaunchConfirmTextFilter(C.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:k.launchConfirmWorkspaceFilter,onChange:C=>k.setLaunchConfirmWorkspaceFilter(C.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:k.launchConfirmModelFilter,onChange:C=>k.setLaunchConfirmModelFilter(C.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),s.jsxs("select",{value:k.launchConfirmSortMode,onChange:C=>k.setLaunchConfirmSortMode(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.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:k.launchConfirmResumableOnly,onChange:C=>k.setLaunchConfirmResumableOnly(C.target.checked),disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:k.launchConfirmResumeId,onChange:C=>k.setLaunchConfirmResumeId(C.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:px()}),k.filteredLaunchConfirmSavedSessions.map(C=>s.jsxs("option",{value:C.providerSessionId,disabled:!C.canResume,children:[C.title||C.providerSessionId," ",C.canResume?"":"(workspace missing)"]},C.providerSessionId))]}),!k.launchConfirmSessionsLoading&&k.launchConfirmSavedSessions.length>0&&k.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),k.launchConfirmResumeId&&(()=>{const C=k.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===k.launchConfirmResumeId);if(!C)return null;const I=Wd(C);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:I.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:I.providerSessionId}),s.jsx("div",{className:"mt-1",children:I.metaLine}),I.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:I.updatedLabel}),I.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:I.preview})]})})()]}),onConfirm:k.handleConfirmLaunch,onCancel:k.closeLaunchConfirm}),u&&s.jsx(Fd,{section:m,onSectionChange:x})]})}function pn(e){return[...e].sort((t,r)=>{const n=r.timestamp-t.timestamp;return n!==0?n:t.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Kg(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:pn(e)}function Hg(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 Ug(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:Ss(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=Ir(n)?"cli":Es(n)?"acp":"ide",o=Ss(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((l=n.activeChat)==null?void 0:l.title)||(Ir(n)?n.cliName||n.type:Es(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Es(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 zg(e,t){const r=new Map;for(const n of t){const a=Ms(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((f,x)=>x.timestamp-f.timestamp)[0]||null,l=(o==null?void 0:o.conversation)||null,c=Ja(n),d=a.filter(f=>f.unread||f.requiresAction).length,m=Hg(n),u=[n.platform||"machine",m].filter(Boolean);return{id:n.id,label:Tt(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?Xh(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 Vg(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 Gg({conversations:e,machineEntries:t,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:l,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:w,setSelectedTabKey:b,setScreen:p,setSelectedMachineId:g,setSection:y,setMachineBackTarget:h,resetMachineAction:M}){const j=i.useRef(null),v=i.useCallback(A=>{if(!(A!=null&&A.sessionId))return;const T=kn(A,l),S=Math.max(Date.now(),vs(A),T.lastUpdated||0);en("mark_read:start",{tabKey:A.tabKey,sessionId:A.sessionId,displayPrimary:ut(A),inboxBucket:T.inboxBucket,unread:T.unread,lastSeenAt:T.lastSeenAt,lastUpdated:T.lastUpdated,activityAt:vs(A),readAt:S}),c(Ms(A)||A.routeId,"mark_session_seen",{sessionId:A.sessionId,providerSessionId:A.providerSessionId,seenAt:S,completionMarker:T.completionMarker}).then(k=>{en("mark_read:result",{tabKey:A.tabKey,sessionId:A.sessionId,result:k})}).catch(k=>{en("mark_read:error",{tabKey:A.tabKey,sessionId:A.sessionId,error:k instanceof Error?k.message:String(k)})})},[l,c]);return i.useEffect(()=>{var T;if(!n){Vg(o)&&p("inbox"),b(((T=e[0])==null?void 0:T.tabKey)||null),j.current=null;return}if(o!=="chat"){j.current=null;return}const A=`${n.tabKey}:${n.sessionId||""}`;j.current!==A&&(j.current=A,v(n))},[e,v,o,n,p,b]),i.useEffect(()=>{if(!d)return;const A=e.find(T=>T.tabKey===d);A&&(b(A.tabKey),p("chat"),m==null||m())},[e,m,d,p,b]),i.useEffect(()=>{if(!u)return;const A=t.find(T=>T.id===u);A&&(g(A.id),M(),y("machines"),h("inbox"),p("machine"),f==null||f())},[t,f,u,M,h,p,y,g]),i.useEffect(()=>{x&&(y(x),p("inbox"),w==null||w())},[w,x,p,y]),i.useEffect(()=>{const A=r.filter(T=>T.inboxBucket==="task_complete"||T.unread);A.length!==0&&en("inbox_state",{screen:o,selectedTabKey:a,items:A.map(T=>{const S=kn(T.conversation,l);return{liveState:S,tabKey:T.conversation.tabKey,sessionId:T.conversation.sessionId,displayPrimary:ut(T.conversation),serverBucket:S.inboxBucket,computedBucket:T.inboxBucket,serverUnread:S.unread,computedUnread:T.unread,lastSeenAt:S.lastSeenAt,lastUpdated:S.lastUpdated,activityAt:vs(T.conversation)}})})},[r,l,o,a]),{markConversationRead:v}}function qg(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function xl(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Yg(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Xg({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)},[]),f=i.useCallback(async(h,M,j)=>{var v;try{o("loading"),c(`Launching ${M}…`);const A={ideType:M,enableCdp:!0};(v=j==null?void 0:j.workspacePath)!=null&&v.trim()&&(A.workspace=j.workspacePath.trim()),await e(h,"launch_ide",A),o("done"),c(`${M} launch requested`)}catch(A){o("error"),c(A instanceof Error?A.message:"Launch IDE failed"),console.error("Launch IDE failed",A)}},[e]),x=i.useCallback(async(h,M,j)=>{if(M.trim())try{o("loading"),c(j!=null&&j.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(h,"workspace_add",{path:M.trim(),createIfMissing:(j==null?void 0:j.createIfMissing)===!0});if(v!=null&&v.success){o("done"),c(j!=null&&j.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 h=>{var M,j,v,A,T,S;try{o("loading"),c("Starting daemon upgrade…");const k=await e(h,"daemon_upgrade",{});if((M=k==null?void 0:k.result)!=null&&M.alreadyLatest){o("done"),c(`Already on v${((j=k==null?void 0:k.result)==null?void 0:j.version)||"latest"}.`);return}if((v=k==null?void 0:k.result)!=null&&v.upgraded||(A=k==null?void 0:k.result)!=null&&A.success){o("done"),c(`Upgrade to v${((T=k==null?void 0:k.result)==null?void 0:T.version)||"latest"} started. Daemon is restarting…`);return}o("error"),c(((S=k==null?void 0:k.result)==null?void 0:S.error)||"Upgrade failed")}catch(k){o("error"),c(k instanceof Error?k.message:"Upgrade failed")}},[e]),b=i.useCallback(async(h,M,j,v)=>{var S,k,K;const A=Date.now(),T={machineId:h,kind:M,providerType:j,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:A};try{o("loading"),c(`Launching ${j}…`),m(T);const L={cliType:j};(S=v==null?void 0:v.workspacePath)!=null&&S.trim()?L.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(L.workspaceId=v.workspaceId),v!=null&&v.resumeSessionId&&(L.resumeSessionId=v.resumeSessionId),(k=v==null?void 0:v.args)!=null&&k.trim()&&(L.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(K=v==null?void 0:v.model)!=null&&K.trim()&&(L.initialModel=v.model.trim());const N=await e(h,"launch_cli",L),P=(N==null?void 0:N.result)||N,B=(P==null?void 0:P.sessionId)||(P==null?void 0:P.id);if(N!=null&&N.success&&B){m(null),o("done"),c(`${j} launched`),t(is(B));return}if(N!=null&&N.success){o("loading"),c(`${j} launch requested — waiting for session…`);return}m(null),o("error"),c((N==null?void 0:N.error)||(P==null?void 0:P.error)||`Could not launch ${M.toUpperCase()} workspace`)}catch(L){if(Yg(L)){o("loading"),c(`${j} launch requested — waiting for session…`);return}m(null),o("error"),c(L instanceof Error?L.message:`Could not launch ${M.toUpperCase()} workspace`)}},[t,e]),p=i.useCallback(async(h,M)=>{try{const j=await e(h,"list_saved_sessions",{providerType:M,kind:"cli",limit:30}),v=(j==null?void 0:j.result)??j;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(j){return console.error("Failed to list saved sessions on mobile:",j),[]}},[e]),g=i.useCallback(async(h,M)=>qn(e,h,M),[e]);i.useEffect(()=>{if(!d)return;const h=xl(d.workspacePath),M=r.find(v=>{var L,N,P,B;if(!v||v.type==="adhdev-daemon"||qg(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 k=String(v.providerSessionId||"");if(d.resumeSessionId&&k)return k===d.resumeSessionId;if(h){const D=xl(v.workspace||v.runtimeWorkspaceLabel);return D?D===h:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((B=(P=(N=(L=v.activeChat)==null?void 0:L.messages)==null?void 0:N.at)==null?void 0:P.call(N,-1))==null?void 0:B.timestamp)||0)>=d.startedAt-5e3});if(!M)return;const j=Ed({entrySessionId:M.sessionId,entryInstanceId:M.instanceId,entryRouteId:M.id,conversations:n});j&&(m(null),o("done"),c(`${d.providerType} launched`),t(is(j)))},[n,r,t,d]),i.useEffect(()=>{if(!d)return;const h=window.setTimeout(()=>{m(M=>!M||M.startedAt!==d.startedAt?M:(o("error"),c("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(h)},[d]);const y=i.useCallback(async(h,M)=>{if(M.kind==="ide"&&M.providerType){await f(h,M.providerType,{workspacePath:M.workspace||null});return}(M.kind==="cli"||M.kind==="acp")&&M.providerType&&await b(h,M.kind,M.providerType,{workspacePath:M.workspace||null,resumeSessionId:M.providerSessionId||null})},[f,b]);return{machineAction:{state:a,message:l},resetMachineAction:u,handleLaunchDetectedIde:f,handleAddWorkspace:x,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:b,handleListSavedSessions:p,handleBrowseDirectory:g,handleOpenRecent:y}}function Jg({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]),f=i.useCallback(y=>{const h=e.find(M=>M.routeId===y.routeId&&M.streamSource==="native");h&&(o(h.tabKey),l("chat"),n(h))},[e,n,l,o]),x=i.useCallback(()=>{n(t),l("inbox")},[n,t,l]),w=i.useCallback((y,h="inbox")=>{c(y),a(),d("machines"),m(h),l("machine")},[a,m,l,d,c]),b=i.useCallback(y=>{const h=Ms(y);h&&w(h,"chat")},[w]),p=i.useCallback(()=>{a(),l(r)},[r,a,l]),g=i.useCallback(y=>{d(y),l("inbox")},[l,d]);return{openConversation:u,openNativeConversation:f,backFromConversation:x,openMachine:w,openConversationMachine:b,backFromMachine:p,changeMachineSection:g}}function Cs(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Qg(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function Zg({conversations:e,hiddenConversations:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:w,onOpenHistory:b,onOpenRemote:p,onStopCli:g,wsStatus:y,isConnected:h,onShowAllHiddenConversations:M,onHideConversation:j,onOpenMeshGraph:v,onOpenNewSession:A,liveSessionInboxState:T,setCliViewModeOverrides:S}){const[k,K]=i.useState(()=>{var ne;return((ne=e[0])==null?void 0:ne.tabKey)||null}),[L,N]=i.useState(()=>e[0]?"chat":"inbox"),[P,B]=i.useState("chats"),[D,C]=i.useState(null),[I,E]=i.useState("inbox"),R=i.useRef([]),$=qs(),z="0.9.81",F=i.useMemo(()=>e.find(ne=>ne.tabKey===k)||e[0]||null,[e,k]),me=i.useMemo(()=>F?r.find(ne=>ne.id===F.routeId):void 0,[r,F]),ie=i.useMemo(()=>!F||st(F)||!at(F)?null:Xs(F),[F]),ee=i.useMemo(()=>r.filter(ne=>ne.type==="adhdev-daemon").sort(Ao),[r]),ce=i.useMemo(()=>ee.find(ne=>ne.id===D)||null,[ee,D]),je=Hn({sendDaemonCommand:a,activeConv:F||void 0,setActionLogs:o,isStandalone:l}),Ne=Xg({sendDaemonCommand:a,navigate:$,ides:r,conversations:e}),q=i.useMemo(()=>e.map(ne=>{const Ie=L==="chat"&&(F==null?void 0:F.tabKey)===ne.tabKey,Ce=Fn(ne,T,{hideOpenTaskCompleteUnread:!0,isOpenConversation:Ie}),_e=vs(ne),H=qc(ne);return{conversation:ne,timestamp:_e,preview:H,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[e,T,L,F]),{markConversationRead:ge}=Gg({conversations:e,machineEntries:ee,items:q,selectedConversation:F,selectedTabKey:k,screen:L,liveSessionInboxState:T,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:f,requestedMobileSection:x,onRequestedMobileSectionConsumed:w,setSelectedTabKey:K,setScreen:N,setSelectedMachineId:C,setSection:B,setMachineBackTarget:E,resetMachineAction:Ne.resetMachineAction}),he=Jg({conversations:e,selectedConversation:F,machineBackTarget:I,markConversationRead:ge,resetMachineAction:Ne.resetMachineAction,setSelectedTabKey:K,setScreen:N,setSelectedMachineId:C,setSection:B,setMachineBackTarget:E}),we=i.useMemo(()=>pn(q.filter(ne=>ne.requiresAction)),[q]),xe=i.useMemo(()=>pn(q.filter(ne=>ne.unread&&!ne.requiresAction)),[q]),Se=i.useMemo(()=>Kg(q.filter(ne=>!ne.unread&&!ne.requiresAction&&ne.isWorking),R.current),[q]);i.useEffect(()=>{R.current=Se.map(ne=>ne.conversation.tabKey)},[Se]);const J=i.useMemo(()=>pn(q.filter(ne=>!ne.unread&&!ne.requiresAction&&!ne.isWorking)),[q]),fe=i.useMemo(()=>ce?q.filter(ne=>Ms(ne.conversation)===ce.id):[],[q,ce]),ae=i.useMemo(()=>Ug(ce,r),[r,ce]),ue=(ce==null?void 0:ce.version)||null,oe=!!ce&&!!ue&&!0&&ue!==z,de=i.useMemo(()=>(ce==null?void 0:ce.availableProviders)||[],[ce]),Q=i.useMemo(()=>de.filter(ne=>Cs(ne,"cli")).map(ne=>({type:ne.type,displayName:ne.displayName||ne.type,icon:ne.icon})),[de]),ve=i.useMemo(()=>de.filter(ne=>Cs(ne,"acp")).map(ne=>({type:ne.type,displayName:ne.displayName||ne.type,icon:ne.icon})),[de]),le=i.useMemo(()=>zg(ee,q),[q,ee]),pe=i.useCallback(async ne=>{ce&&await Ne.handleOpenRecent(ce.id,ne)},[Ne,ce]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:L==="chat"&&F?s.jsx(Lg,{selectedConversation:F,isAcp:st(F),isStandalone:l,selectedIdeEntry:me,actionLogs:n,userName:c,isSendingChat:je.isSendingChat,sendFeedbackMessage:je.sendFeedbackMessage,isFocusingAgent:je.isFocusingAgent,handleModalButton:je.handleModalButton,handleRelaunch:je.handleRelaunch,onBack:he.backFromConversation,onOpenNativeConversation:he.openNativeConversation,onOpenMachine:he.openConversationMachine,onOpenHistory:b,onOpenRemote:p,onOpenMeshGraph:v,onStopCli:g,cliViewMode:ie,onSetCliViewMode:async ne=>{await jd({conversation:F,mode:ne,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:S})},handleSendChat:je.handleSendChat,handleFocusAgent:je.handleFocusAgent}):L==="machine"&&ce?s.jsx(Wg,{selectedMachineEntry:ce,selectedMachineConversations:fe,selectedMachineRecentLaunches:ae,cliProviders:Q,acpProviders:ve,selectedMachineNeedsUpgrade:oe,appVersion:z,machineAction:Ne.machineAction,isStandalone:l,section:P,showBottomNav:I==="inbox",onBack:he.backFromMachine,onSectionChange:he.changeMachineSection,onOpenConversation:he.openConversation,onOpenRecent:pe,onOpenMachineDetails:()=>$(`/machines/${ce.id}`),onMachineUpgrade:()=>Ne.handleMachineUpgrade(ce.id),onLaunchDetectedIde:(ne,Ie)=>Ne.handleLaunchDetectedIde(ce.id,ne,Ie),onAddWorkspace:(ne,Ie)=>Ne.handleAddWorkspace(ce.id,ne,Ie),onBrowseDirectory:ne=>Ne.handleBrowseDirectory(ce.id,ne),onLaunchWorkspaceProvider:(ne,Ie,Ce)=>Ne.handleLaunchWorkspaceProvider(ce.id,ne,Ie,Ce),onListSavedSessions:ne=>Ne.handleListSavedSessions(ce.id,ne)}):s.jsx(Dg,{section:P,attentionItems:we,unreadItems:xe,workingItems:Se,completedItems:J,hiddenConversations:t,machineCards:le,getAvatarText:Qg,actionLogs:n,sendDaemonCommand:a,onOpenConversation:he.openConversation,onShowAllHidden:M,onHideConversation:j,onOpenMeshGraph:v,onOpenNewSession:A,onOpenMachine:he.openMachine,onOpenSettings:()=>$("/settings"),onSectionChange:B,wsStatus:y,isConnected:h,isStandalone:l})})}function ka(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function ey({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),f=i.useCallback(()=>{l.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",f),window.addEventListener("drop",f),()=>{window.removeEventListener("dragend",f),window.removeEventListener("drop",f)}),[f]);const x=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(),!ka(t,r)){u("merge");return}const y=g.currentTarget.getBoundingClientRect(),h=g.clientX-y.left,M=y.width/3;h<M?u("split-left"):h>M*2?u("split-right"):u("merge")},[t,r]),b=i.useCallback(()=>{l.current-=1,!(l.current>0)&&(l.current=0,d(!1),u(null))},[]),p=i.useCallback(g=>{l.current=0,d(!1);const y=g.dataTransfer.getData("text/tab-key"),h=y?e.some(j=>j.tabKey===y):!1,M=m;if(u(null),o(),!!y){if(g.preventDefault(),M==="split-left"&&ka(t,r)){r==null||r(y,"split-left");return}if(M==="split-right"&&ka(t,r)){r==null||r(y,"split-right");return}if(h){a(y);return}n==null||n(y)}},[e,m,t,r,n,a,o]);return{dragOver:c,dropAction:m,resetDragState:f,handleDragEnter:x,handleDragOver:w,handleDragLeave:b,handleDrop:p}}function ty(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 sy({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),f=i.useRef(null),x=i.useRef(null),w=i.useRef(n),b=i.useRef(a);i.useEffect(()=>{w.current=n},[n]),i.useEffect(()=>{b.current=a},[a]),i.useEffect(()=>{t&&t!==o&&l(t)},[t,o]),i.useEffect(()=>{d(T=>{const S=ty(T,e);return S.length===T.length&&S.every((k,K)=>k===T[K])?T:S})},[e]);const p=i.useMemo(()=>{const T=m??c;if(T.length===0)return e;const S=new Map(T.map((k,K)=>[k,K]));return[...e].sort((k,K)=>{const L=S.get(k.tabKey)??999,N=S.get(K.tabKey)??999;return L-N})},[e,m,c]);i.useEffect(()=>{var S,k;if(p.length===0){o!==null&&(l(null),(S=w.current)==null||S.call(w,null));return}if(o&&p.some(K=>K.tabKey===o))return;const T=p[0].tabKey;T!==o&&(l(T),(k=w.current)==null||k.call(w,T))},[p,o]);const g=i.useMemo(()=>p.find(T=>T.tabKey===o),[p,o]),y=i.useCallback(T=>{var S;l(T),(S=w.current)==null||S.call(w,T)},[]),h=i.useCallback((T,S,k)=>{d(K=>{var B;const L=K.filter(D=>D!==T),N=L.indexOf(S);if(N<0)return K;const P=k==="left"?N:N+1;return L.splice(P,0,T),(B=b.current)==null||B.call(b,L),L}),u(null)},[]),M=i.useCallback((T,S,k)=>{const L=(c.length>0?c:e.map(B=>B.tabKey)).filter(B=>B!==T),N=L.indexOf(S);if(N<0)return;const P=k==="left"?N:N+1;L.splice(P,0,T),f.current=L,u(L)},[c,e]),j=i.useCallback(()=>{var S;const T=f.current;T&&(d(T),(S=b.current)==null||S.call(b,T))},[]),v=i.useCallback(()=>{f.current=null,u(null)},[]),A=i.useCallback(T=>{d(S=>{var K;const k=S.filter(L=>L!==T);return k.push(T),(K=b.current)==null||K.call(b,k),k})},[]);return{activeTabId:o,activeConv:g,sortedConversations:p,previewOrderRef:f,draggingTabRef:x,selectTab:y,handleTabReorder:h,updatePreviewOrder:M,commitPreviewOrder:j,clearPreviewOrder:v,moveTabToEnd:A,setDraggingTabKey:T=>{x.current=T}}}function ry({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 Qo({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?Qc: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:Ht,"aria-label":Ht,children:[s.jsx(cc,{size:14}),s.jsx("span",{children:Ht})]})}),l&&s.jsx(Od,{}),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 Hd="adhdev-tab-shortcuts";function Ud(){try{return JSON.parse(localStorage.getItem(Hd)||"{}")}catch{return{}}}function zd({enabled:e=!0,sortedTabKeys:t,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,l]=i.useState(()=>Ud()),[c,d]=i.useState(null),m=i.useCallback(f=>{const x=[];return f.metaKey&&x.push(a?"⌘":"Meta"),f.ctrlKey&&x.push("Ctrl"),f.altKey&&x.push(a?"⌥":"Alt"),f.shiftKey&&x.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(f.key)?null:(x.push(f.key.length===1?f.key.toUpperCase():f.key),x.join("+"))},[a]),u=i.useCallback(f=>{l(f);try{localStorage.setItem(Hd,JSON.stringify(f))}catch{}},[]);return i.useEffect(()=>{if(!e||!c)return;const f=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){d(null);return}const w=m(x);if(!w)return;const b={...o};for(const[p,g]of Object.entries(b))g===w&&delete b[p];b[c]=w,u(b),d(null)};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)},[e,c,o,u,m]),i.useEffect(()=>{if(!e)return;const f=x=>{if(!(!x.ctrlKey&&!x.metaKey&&!x.altKey)){for(const[w,b]of Object.entries(o))if(t.includes(w)&&m(x)===b){x.preventDefault(),r(),n(w);return}}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,o,t,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const Sa=e=>{e.preventDefault()},ny=i.memo(function({conv:t,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:l,draggingTabRef:c,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:f,onReorderTab:x,onCommitPreviewOrder:w,onClearPreviewOrder:b,onDragStateReset:p,onDragTabKeyChange:g,onReceiveTab:y,onOpenContextMenu:h,longPressTimer:M,isGroupActive:j}){const v=Ys(t),A=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",T=v.isReconnecting,S=i.useCallback(I=>{c.current=t.tabKey,g(t.tabKey),I.dataTransfer.setData("text/tab-key",t.tabKey),I.dataTransfer.effectAllowed="move"},[t.tabKey,c,g]),k=i.useCallback(()=>{c.current=null,g(null),w(),b(),p()},[c,g,w,b,p]),K=i.useCallback(I=>{const E=c.current;if(!(!E||E===t.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const R=I.currentTarget.getBoundingClientRect(),$=I.clientX<R.left+R.width/2?"left":"right";f(E,t.tabKey,$)}},[t.tabKey,c,f]),L=i.useCallback(I=>{I.preventDefault(),I.stopPropagation();const E=I.dataTransfer.getData("text/tab-key");if(E&&E!==t.tabKey){const R=I.currentTarget.getBoundingClientRect(),$=I.clientX<R.left+R.width/2?"left":"right";l.includes(E)?x(E,t.tabKey,$):y&&y(E)}b()},[t.tabKey,l,x,y,b]),N=i.useCallback(I=>{I.stopPropagation(),d(),m(t.tabKey),u(t)},[t,u,d,m]),P=i.useCallback(I=>{I.preventDefault(),h(I.clientX,I.clientY,t.tabKey)},[t.tabKey,h]),B=i.useCallback(I=>{const E=I.touches[0];M.current=setTimeout(()=>{h(E.clientX,E.clientY,t.tabKey)},600)},[t.tabKey,M,h]),D=i.useCallback(()=>{M.current&&clearTimeout(M.current)},[M]),C=["adhdev-dockview-tab",A,r&&"is-active",j&&"is-group-active",T&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:C,draggable:!0,onDragStart:S,onDragEnd:k,onDragOver:K,onDrop:L,onClick:N,onContextMenu:P,onTouchStart:B,onTouchEnd:D,onTouchMove:D,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:hs(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[hs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:hs(t)}),s.jsx(Us,{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 ay({conversations:e,activeTabId:t,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:w,onReceiveTab:b,onHideTab:p,isGroupActive:g,allowTabShortcuts:y=!0}){const[h,M]=i.useState(null),j=i.useRef(null),v=i.useRef(null),A=i.useMemo(()=>e.map(P=>P.tabKey),[e]);_r("PaneGroupTabBar",{groupIndex:r,activeTabId:t,tabCount:e.length,ctxMenuTab:(h==null?void 0:h.tabKey)||null});const{isMac:T,tabShortcuts:S,shortcutListening:k,setShortcutListening:K,saveShortcuts:L}=zd({enabled:y,sortedTabKeys:e.map(P=>P.tabKey),onFocus:o,onSelectTab:l});i.useEffect(()=>{if(!h)return;const P=B=>{const D=document.querySelector("[data-pane-context-menu]");D&&D.contains(B.target)||M(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[h]),i.useEffect(()=>{const P=v.current;if(!P)return;const B=D=>{Math.abs(D.deltaY)<=Math.abs(D.deltaX)||(D.preventDefault(),P.scrollLeft+=D.deltaY)};return P.addEventListener("wheel",B,{passive:!1}),()=>P.removeEventListener("wheel",B)},[]);const N=i.useCallback((P,B,D)=>{M({x:P,y:B,tabKey:D})},[]);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(P=>s.jsx(ny,{conv:P,isActive:t===P.tabKey,isDraggedTab:a.current===P.tabKey,isTaskCompleteUnread:n.has(P.tabKey),shortcut:y?S[P.tabKey]:void 0,conversationKeys:A,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:f,onDragStateReset:x,onDragTabKeyChange:w,onReceiveTab:b,onOpenContextMenu:N,longPressTimer:j,isGroupActive:g},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),h&&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:h.x,top:h.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:Sa,onClick:P=>{P.stopPropagation(),K(h.tabKey),M(null)},children:["⌨ ",S[h.tabKey]?`Change shortcut (${S[h.tabKey]})`:"Set shortcut"]}),S[h.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:Sa,onClick:()=>{const P={...S};delete P[h.tabKey],L(P),M(null)},children:"✕ Remove shortcut"})]}),p&&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:Sa,onClick:()=>{p(h.tabKey),M(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&k&&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:()=>K(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.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 oy({conversations:e,ides:t,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,userName:d,groupIndex:m,onFocus:u,isSplitMode:f,numGroups:x,onMoveTab:w,onReceiveTab:b,style:p,onActiveTabChange:g,initialActiveTabId:y,initialTabOrder:h,onTabOrderChange:M,onHideTab:j,isFocused:v,allowTabShortcuts:A=!0,onOpenNewSession:T,liveSessionInboxState:S}){const{sendCommand:k}=kt(),K=i.useRef(null),{activeTabId:L,activeConv:N,sortedConversations:P,draggingTabRef:B,selectTab:D,handleTabReorder:C,updatePreviewOrder:I,commitPreviewOrder:E,clearPreviewOrder:R,moveTabToEnd:$,setDraggingTabKey:z}=sy({conversations:e,initialActiveTabId:y,initialTabOrder:h,onActiveTabChange:g,onTabOrderChange:M}),F=Hn({sendDaemonCommand:a,activeConv:N,setActionLogs:o,isStandalone:l}),{dragOver:me,dropAction:ie,resetDragState:ee,handleDragEnter:ce,handleDragOver:je,handleDragLeave:Ne,handleDrop:q}=ey({conversations:e,numGroups:x,onMoveTab:w,onReceiveTab:b,onOwnTabDrop:$,onClearPreviewOrder:R}),ge=N&&!st(N)&&Xs(N)==="terminal",he=i.useMemo(()=>N?t.find(J=>J.id===N.routeId):void 0,[t,N]),we=i.useMemo(()=>N?n.filter(J=>J.routeId===N.tabKey):[],[n,N]),xe=i.useMemo(()=>new Set(P.filter(J=>$p(J,S,{isOpenConversation:J.tabKey===L})).map(J=>J.tabKey)),[L,S,P]);_r("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:L,dragOver:me});const Se=i.useCallback(J=>{J.streamSource==="agent-stream"&&J.agentType&&k(J.routeId,Pc(),{agentType:J.agentType,...J.sessionId&&{targetSessionId:J.sessionId}}).catch(()=>{})},[k]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:me?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(ay,{conversations:P,activeTabId:L,groupIndex:m,numGroups:x,unreadTabKeys:xe,draggingTabRef:B,onFocus:u,onSelectTab:D,onConversationActivated:Se,onPreviewReorder:I,onReorderTab:C,onCommitPreviewOrder:E,onClearPreviewOrder:R,onDragStateReset:ee,onDragTabKeyChange:z,onMoveTab:w,onReceiveTab:b,onHideTab:j,isGroupActive:v??!1,allowTabShortcuts:A}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:ce,onDragOver:je,onDragLeave:Ne,onDrop:q,children:[me&&s.jsx(ry,{dropAction:ie,canSplit:!!(x<4&&w)}),N?s.jsx(Xo,{activeConv:N,clearToken:r[N.tabKey]||0,isCliTerminal:!!ge,ideEntry:he,terminalRef:K,handleModalButton:F.handleModalButton,handleRelaunch:F.handleRelaunch,handleSendChat:F.handleSendChat,isSendingChat:F.isSendingChat,sendFeedbackMessage:F.sendFeedbackMessage,handleFocusAgent:F.handleFocusAgent,isFocusingAgent:F.isFocusingAgent,actionLogs:we,userName:d,isInputActive:!f||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(Qo,{conversationsCount:e.length,isSplitMode:f,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:T})})]})]})}function iy({containerRef:e,isSplitMode:t,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:x,focusedGroup:w,focusGroup:b,moveTabToGroup:p,splitTabRelative:g,closeGroup:y,handleResizeStart:h,groupActiveTabIds:M,setGroupActiveTab:j,groupTabOrders:v,setGroupTabOrder:A,toggleHiddenTab:T,onOpenNewSession:S,allowTabShortcuts:k=!0,liveSessionInboxState:K}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((L,N)=>{const P=t&&n.length===r?`${n[N]}%`:void 0;return s.jsxs(St.Fragment,{children:[t&&N>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:B=>h(N-1,B),onDoubleClick:()=>y(N),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(oy,{style:t?{flexBasis:P??`${100/r}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:L,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:f,userName:x,groupIndex:N,isFocused:t&&w===N,onFocus:()=>b(N),isSplitMode:t,numGroups:r,onMoveTab:(B,D)=>{D==="left"&&N>0?p(B,N-1):D==="right"&&N<r-1?p(B,N+1):D==="split-left"&&r<4?g(B,N,"left"):D==="split-right"&&r<4&&g(B,N,"right")},onReceiveTab:B=>p(B,N),onActiveTabChange:B=>j(N,B),initialActiveTabId:M[N],initialTabOrder:v[N],onTabOrderChange:B=>A(N,B),onHideTab:T,onOpenNewSession:S,allowTabShortcuts:k,liveSessionInboxState:K})]},N)})})}function Vd({doId:e,targetSessionId:t,connState:r,viewMode:n}){const[a,o]=i.useState(null),[l,c]=i.useState(null);i.useEffect(()=>e?ft.onScreenshot("ide-page",(u,f)=>{if(u!==e)return;const x=new FileReader;x.onload=()=>o(x.result),x.readAsDataURL(f)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=ft.onStatus)==null?void 0:u.call(ft,(f,x)=>{f===e&&x!=null&&x.screenshotUsage&&c(x.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,t]),i.useEffect(()=>{const m=e?ft.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 f=e?ft.get(e):null;return!f||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):f.sendInput(m,u,t)},[e,r,t]);return{connScreenshot:a,screenshotUsage:l,handleRemoteAction:d}}const Gd="adhdev-dashboard-action-shortcuts",ly=1200,cy=[["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 dy(){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 uo(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function Pn(e){const t=Object.fromEntries(qd(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(Gd)||"{}"),n={...t,...r};for(const[a,o]of cy)n[a]===o&&(n[a]=t[a]);return n}catch{return t}}function Yd(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function uy({enabled:e=!0,onTrigger:t}){const r=dy(),[n,a]=i.useState(()=>Pn(r)),[o,l]=i.useState(null),[c,d]=i.useState([]),m=i.useRef({parts:[],timer:null}),u=i.useCallback(p=>{const g=[];return p.metaKey&&g.push(r?"⌘":"Meta"),p.ctrlKey&&g.push("Ctrl"),p.altKey&&g.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&g.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(g.push(Yd(p.key)),g.join("+"))},[r]),f=i.useCallback(p=>{a(p);try{localStorage.setItem(Gd,JSON.stringify(p))}catch{}},[]);i.useEffect(()=>{const p=Pn(r),g=Object.entries(n),y=Object.entries(p);g.length===y.length&&g.every(([h,M])=>p[h]===M)||f(p)},[n,r,f]);const x=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}},ly))},[]);i.useEffect(()=>{if(!o)return;const p=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){l(null),d([]);return}const y=u(g);if(!y)return;const M=!(g.metaKey||g.ctrlKey||g.altKey)&&/^[A-Z0-9]$/.test(y);if(c.length===0&&M){d([y]);return}const v=[...c,y].slice(0,2).join(" "),A={...n};for(const[T,S]of Object.entries(A))S===v&&delete A[T];A[o]=v,f(A),l(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,f,o,c]),i.useEffect(()=>{if(!e||o)return;const p=g=>{if(g.defaultPrevented)return;const y=u(g);if(!y)return;const h=g.metaKey||g.ctrlKey||g.altKey;if(uo(g.target))return;const M=m.current.parts,j=h?[y]:[...M.slice(-1),y].slice(-2),v=j.join(" "),A=j[j.length-1],T=Object.entries(n).filter(([,N])=>!!N),S=T.find(([,N])=>N===v);if(S){g.preventDefault(),x(),t(S[0]);return}if(T.some(([,N])=>N.startsWith(`${v} `))){g.preventDefault(),m.current.parts=j,w();return}const K=T.find(([,N])=>N===A);if(K){g.preventDefault(),x(),t(K[0]);return}if(T.some(([,N])=>N.startsWith(`${A} `))){g.preventDefault(),m.current.parts=[A],w();return}x()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,w,e,u,t,x,o]),i.useEffect(()=>()=>x(),[x]);const b=i.useMemo(()=>qd(r),[r]);return{isMac:r,actionDefinitions:b,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:l,setShortcutListeningDraft:d,saveShortcuts:f}}function my({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 Xd(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function bl({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:r,ides:n}){return!e||r>0?!1:t?!Xd(n):!0}function py({previousVisibleConversationCount:e,visibleConversationCount:t,ides:r}){return t>0||e<=0?!1:Xd(r)}const Jd=1e3,fy=4;function gl(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function yl(e,t,r){return Math.abs(t.clientX-e.clientX)>r||Math.abs(t.clientY-e.clientY)>r}function hy({detachDelayMs:e=Jd,stillnessThresholdPx:t=fy,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 f=()=>{m!=null&&(a(m),m=null)},x=()=>{f(),c=null},w=()=>{f(),o=null,l=null,c=null,d=null,u=!1},b=()=>{!o||!c||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!c||!d||u)&&gl(d,l)&&(yl(c,d,t)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},p=y=>{if(!(!o||u)){if(!gl(y,l)){d={clientX:y.clientX,clientY:y.clientY},x();return}(!c||yl(c,y,t))&&(f(),c={clientX:y.clientX,clientY:y.clientY}),d={clientX:y.clientX,clientY:y.clientY},b()}},g=y=>{!o||u||(y&&(d={clientX:y.clientX,clientY:y.clientY}),x())};return{startDrag:y=>{f(),o=y.panelId,l=y.selfPanelBounds??null,c=null,d={clientX:y.clientX,clientY:y.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:g,markNoDropTarget:g,markDockTarget:g,endDrag:w,isDragging:()=>o!=null,hasDetached:()=>u,dispose:w}}function xy(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function tn(e){return e.isActive}function vl(e){return e.isVisible}const Qd=i.createContext(null);function Xn(){const e=i.useContext(Qd);if(!e)throw new Error("DashboardDockviewContext missing");return e}function fn(e){return ut(e)||e.tabKey}function by(e){return`remote:${e}`}function $t(e){return e.startsWith("remote:")}function wl(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function gy(e){e.preventDefault()}function Na(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 Ca(e,t){e.classList.remove(Ua.className,za.className),e.classList.add(t==="light"?Ua.className:za.className)}function jl(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 yy(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 vy(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:fn(m),params:{kind:"conversation",tabKey:m.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return r??((l=t[0])==null?void 0:l.tabKey)??null}function kl(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])$t(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!==fn(a)&&o.api.setTitle(fn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:fn(a),params:{kind:"conversation",tabKey:a.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Sl(e,t,r){var d,m;const n=r?by(r):null;for(const u of[...e.panels])$t(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Ft(t,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),l=Jc(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=>!$t(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 wy({params:e,api:t}){var w;const r=Xn(),n=i.useRef(null),[a,o]=i.useState(()=>tn(t)),[l,c]=i.useState(()=>vl(t)),d=r.conversationsByTabKey.get(e.tabKey),m=Hn({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(tn(t)),c(vl(t));const b=[t.onDidActiveChange(p=>o(p.isActive)),t.onDidActiveGroupChange(p=>{if(!tn(t)&&!p.isActive){o(!1);return}o(tn(t))}),t.onDidVisibilityChange(p=>c(p.isVisible))];return()=>{for(const p of b)p.dispose()}},[t]);const u=i.useMemo(()=>d?r.ides.find(b=>b.id===d.routeId):void 0,[r.ides,d]),f=i.useMemo(()=>d?r.actionLogs.filter(b=>b.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(Qo,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const x=!st(d)&&Xs(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(Xo,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:x,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:f,userName:r.userName,scrollToBottomRequestNonce:((w=r.scrollToBottomRequest)==null?void 0:w.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:l})})}function jy({params:e}){var d;const t=Xn(),r=i.useMemo(()=>Ft([...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}=Vd({doId:a,targetSessionId:r?Rc(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(bc,{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 ky(){const e=Xn();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(Qo,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function Sy(e){var w,b;yy(e);const t=Xn(),r=i.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Ft([...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":(p==null?void 0:p.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:p!=null&&p.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:p.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=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,o=e.api.isGroupActive,l=Fn(n,t.liveSessionInboxState,{isOpenConversation:a}),c=l.isReconnecting,d=l.isConnecting,m=l.isGenerating,u=l.isWaiting,f=l.unread,x=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:p=>{var g;p.preventDefault(),r(p),t.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((g=p.target)==null?void 0:g.ownerDocument)??document})},children:[f&&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:hs(n)}):d?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:hs(n)}):s.jsx("span",{children:hs(n)})})]}),x&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:x,children:x})]})}function Ny({visibleConversations:e,clearedTabs:t,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:f,registerActionHandlers:x,onActiveTabChange:w,onOpenNewSession:b,onRequestScrollToBottom:p,requestedActiveTabKey:g,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:h,scrollToBottomRequest:M,liveSessionInboxState:j,layoutProfile:v}){var Te,Be,qe;const{theme:A}=Js(),{sendCommand:T}=kt(),S=i.useRef(null),k=i.useRef(null),K=i.useRef(null),L=i.useRef(!1),N=i.useRef(!1),P=i.useRef(!1),B=i.useRef(null),D=i.useRef([]),[C,I]=i.useState(null),[E,R]=i.useState(0),$=i.useRef(typeof window>"u"?{}:Ub(v)),z=i.useMemo(()=>new Map(e.map(V=>[V.tabKey,V])),[e]),F=i.useMemo(()=>{const V=S.current;return V?V.groups.some(U=>{try{const X=U.model.location.type;return X!=="floating"&&X!=="popout"?!1:U.panels.some(se=>z.has(se.id))}catch{return!1}}):!1},[z,E,e]),me=i.useCallback(()=>{var V;(V=S.current)==null||V.focus()},[]),ie=i.useCallback((V,U)=>{p==null||p(V,U)},[p]),ee=i.useCallback(V=>{const U=document,X=V.document;for(const re of U.querySelectorAll('link[rel="stylesheet"]')){const ke=X.createElement("link");ke.rel="stylesheet",ke.href=re.href,re.crossOrigin&&(ke.crossOrigin=re.crossOrigin),X.head.appendChild(ke)}for(const re of U.querySelectorAll("style")){const ke=X.createElement("style");ke.textContent=re.textContent,X.head.appendChild(ke)}const se=[];for(const re of U.styleSheets)try{for(const ke of re.cssRules)ke instanceof CSSStyleRule&&(ke.selectorText===":root"||ke.selectorText==="html")&&se.push(ke.cssText)}catch{}if(se.length>0){const re=X.createElement("style");re.textContent=se.join(`
|
|
54
|
+
`),X.head.appendChild(re)}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 te=X.getElementById("dv-popout-window");te instanceof HTMLElement&&(te.classList.add("adhdev-dockview"),Ca(te,A))},[A]),ce=i.useCallback(()=>{var U;const V=S.current;if(V)for(const X of V.groups)try{const se=(U=X.element)==null?void 0:U.ownerDocument;if(!se||se===document)continue;const W=se.getElementById("dv-popout-window");W instanceof HTMLElement&&(W.classList.add("adhdev-dockview"),Ca(W,A));const G=document.documentElement.getAttribute("data-theme");G&&se.documentElement.setAttribute("data-theme",G),se.documentElement.style.colorScheme=G==="light"?"light":"dark",se.body.className=document.body.className;const te=document.documentElement.getAttribute("style");te?se.documentElement.setAttribute("style",te):se.documentElement.removeAttribute("style")}catch{}},[A]),je=i.useCallback(V=>{const U=S.current;if(!U)return;const X=U.getPanel(V);X&&U.addPopoutGroup(X,{popoutUrl:"/popout.html",onDidOpen:({window:se})=>{ee(se),fe();const W=z.get(V);se.document.title=W?`${ut(W)} — ADHDev`:"ADHDev — Popout"}})},[z,ee]),Ne=i.useCallback(V=>{const U=S.current,X=U==null?void 0:U.getPanel(V);if(!U||!X)return;const se=U.groups.filter(W=>{var G;try{return((G=W.element)==null?void 0:G.ownerDocument)===document}catch{return!0}});se.length>0?X.api.moveTo({group:se[0],position:"center"}):X.api.moveTo({position:"center"}),X.api.setActive()},[]),q=i.useCallback(V=>{var se;const U=S.current;if(!U)return!1;const X=U.getPanel(V);if(!X)return!1;try{return((se=X.group.element)==null?void 0:se.ownerDocument)!==document}catch{return!1}},[]),ge=i.useCallback(V=>{q(V)&&Ne(V),u(V)},[q,Ne,u]),he=i.useCallback(V=>{const U=S.current,X=U==null?void 0:U.getPanel(V);!U||!X||U.addFloatingGroup(X,{width:600,height:500})},[]),we=i.useCallback(V=>{var X;const U=(X=S.current)==null?void 0:X.getPanel(V);if(!U)return!1;try{return U.group.model.location.type==="floating"}catch{return!1}},[]),xe=i.useCallback(()=>{var U,X;const V=(X=(U=S.current)==null?void 0:U.activePanel)==null?void 0:X.id;return!V||$t(V)?null:z.has(V)?V:null},[z]),Se=i.useCallback(V=>{const U=S.current,X=U==null?void 0:U.getPanel(V);if(!U||!X)return;const se=U.groups.filter(W=>{try{return W.model.location.type==="grid"}catch{return!0}});se.length>0?X.api.moveTo({group:se[0],position:"center"}):X.api.moveTo({position:"center"}),X.api.setActive()},[]),J=i.useCallback(()=>{var G;const V=S.current;if(!V)return;const X=V.groups.filter(te=>{var re;try{return((re=te.element)==null?void 0:re.ownerDocument)===document&&te.model.location.type==="grid"}catch{return!1}})[0]||null,se=[...V.panels];for(const te of se){const re=(G=te.group.element)==null?void 0:G.ownerDocument,ke=te.group.model.location.type;re===document&&ke==="grid"||(X&&X.id!==te.group.id?te.api.moveTo({group:X,position:"center"}):te.api.moveTo({position:"center"}))}const W=V.activePanel;W&&(W.group.model.openPanel(W),W.api.setActive()),Na(document)},[]),fe=i.useCallback(()=>{var U,X;const V=S.current;if(V)for(const se of V.groups){const W=(U=se.element)==null?void 0:U.ownerDocument;if(!W||W===document)continue;const G=W.getElementById("dv-popout-window");if(!(G instanceof HTMLElement))continue;let te=null,re=W.title||"ADHDev",ke="Popout workspace";const Ee=se.activePanel;if(Ee)if(te=Ee.id,$t(Ee.id)){const Le=((X=Ee.params)==null?void 0:X.routeId)||Ee.id.slice(7),Qe=Ft([...z.values()],Le);re=Jc(Qe),ke=Qe!=null&&Qe.machineName?`Remote view · ${Qe.machineName}`:"Remote view"}else{const Le=z.get(Ee.id);re=Le?ut(Le):Ee.title||Ee.id,ke=Le?hs(Le):"Dockview panel"}W.title=`${re} — 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;">${wl(re)}</div>
|
|
58
|
+
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${wl(ke)}</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=!te,Ue.style.opacity=te?"1":"0.5",Ue.style.cursor=te?"pointer":"default",Ue.onclick=()=>{var Le;te&&Ne(te),(Le=W.defaultView)==null||Le.focus()})}},[z,Ne]),ae=i.useCallback(V=>{var se;const U=S.current,X=U==null?void 0:U.getPanel(V);if(!(!U||!X)){X.group.model.openPanel(X),X.api.setActive(),ie(V,"dockview-shortcut");try{const W=X.group.model.location;W.type==="popout"?W.getWindow().focus():Na((se=X.group.element)==null?void 0:se.ownerDocument)}catch{}}},[ie]),ue=i.useCallback(V=>{const U=S.current,X=U==null?void 0:U.activePanel,se=(U==null?void 0:U.activeGroup)||(X==null?void 0:X.group);if(!U||!X||!se)return;const W=se.panels||[];if(W.length<=1)return;const G=W.findIndex(ke=>ke.id===X.id);if(G<0)return;const te=(G+V+W.length)%W.length,re=W[te];re&&(re.group.model.openPanel(re),re.api.setActive(),$t(re.id)||ie(re.id,"dockview-shortcut"))},[ie]),oe=i.useCallback(V=>{var Fe;const U=S.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 se=U.groups||[],W=se.find(Ue=>Ue.id===X.id);if(!W)return;const G=W.element.getBoundingClientRect(),te=G.left+G.width/2,re=G.top+G.height/2,ke=(Ue,Le,Qe,et)=>Math.max(0,Math.min(Le,et)-Math.max(Ue,Qe)),Ee=Ue=>{const Le=Ue.element.getBoundingClientRect(),Qe=Le.left+Le.width/2,et=Le.top+Le.height/2;let gt=0,yt=0,dt=0,ht=!1;if(V==="left"?(ht=Qe<te,gt=Math.max(0,G.left-Le.right),yt=Math.abs(et-re),dt=ke(G.top,G.bottom,Le.top,Le.bottom)):V==="right"?(ht=Qe>te,gt=Math.max(0,Le.left-G.right),yt=Math.abs(et-re),dt=ke(G.top,G.bottom,Le.top,Le.bottom)):V==="above"?(ht=et<re,gt=Math.max(0,G.top-Le.bottom),yt=Math.abs(Qe-te),dt=ke(G.left,G.right,Le.left,Le.right)):(ht=et>re,gt=Math.max(0,Le.top-G.bottom),yt=Math.abs(Qe-te),dt=ke(G.left,G.right,Le.left,Le.right)),!ht)return Number.POSITIVE_INFINITY;const Ge=dt>0?0:120;return gt*3+yt+Ge};let Oe=null,Re=Number.POSITIVE_INFINITY;for(const Ue of se){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(V=>{var se;const U=oe(V);if(!U)return;const X=U.activePanel||U.panels[0];X&&(U.model.openPanel(X),X.api.setActive(),$t(X.id)||ie(X.id,"dockview-focus"),Na((se=U.element)==null?void 0:se.ownerDocument))},[oe,ie]),Q=i.useCallback((V,U)=>{const X=S.current,se=X==null?void 0:X.activePanel,W=(X==null?void 0:X.activeGroup)||(se==null?void 0:se.group);if(!X||!se||!W)return;let G=oe(V);!G&&(U!=null&&U.createGroupIfMissing)&&(G=X.addGroup({referenceGroup:W,direction:V})),G&&(se.api.moveTo({group:G,position:"center"}),se.group.model.openPanel(se),se.api.setActive(),$t(se.id)||ie(se.id,U!=null&&U.createGroupIfMissing?"dockview-split":"dockview-move"))},[oe,ie]),{isMac:ve,tabShortcuts:le,shortcutListening:pe,setShortcutListening:ne,saveShortcuts:Ie}=zd({sortedTabKeys:e.map(V=>V.tabKey),onFocus:me,onSelectTab:ae}),Ce=i.useCallback(()=>{var X;const V=S.current;if(!V)return;const U=V.activePanel;if(U){if($t(U.id)){const se=((X=U.params)==null?void 0:X.routeId)||U.id.slice(7),W=Ft(e,se);W!=null&&W.tabKey&&ne(W.tabKey);return}z.has(U.id)&&ne(U.id)}},[z,ae,ne,e]),_e=i.useCallback(V=>{const U=[];return V.metaKey&&U.push(ve?"⌘":"Meta"),V.ctrlKey&&U.push("Ctrl"),V.altKey&&U.push(ve?"⌥":"Alt"),V.shiftKey&&V.key.length!==1&&U.push(ve?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(V.key)?null:(U.push(Yd(V.key)),U.join("+"))},[ve]),H=i.useCallback(V=>{var U,X;switch(V){case"splitActiveTabRight":Q("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Q("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const se=xe();se&&he(se);return}case"popoutActiveTab":{const se=xe();se&&je(se);return}case"dockActiveTab":{const se=xe();if(!se)return;q(se)?Ne(se):we(se)&&Se(se);return}case"focusLeftPane":de("left");return;case"focusRightPane":de("right");return;case"focusUpPane":de("above");return;case"focusDownPane":de("below");return;case"moveActiveTabToLeftPane":Q("left");return;case"moveActiveTabToRightPane":Q("right");return;case"moveActiveTabToUpPane":Q("above");return;case"moveActiveTabToDownPane":Q("below");return;case"selectPreviousGroupTab":ue(-1);return;case"selectNextGroupTab":ue(1);return;case"setActiveTabShortcut":Ce();return;case"hideCurrentTab":{const se=(X=(U=S.current)==null?void 0:U.activePanel)==null?void 0:X.id;se&&!$t(se)&&ge(se);return}default:return}},[ue,Se,de,he,xe,ge,we,q,Ne,Q,je,Ce]);i.useEffect(()=>{if(!C)return;const V=C.sourceDocument,U=V.defaultView??window,X=se=>{const W=V.querySelector("[data-dockview-tab-context-menu]");W&&W.contains(se.target)||I(null)};return U.addEventListener("mousedown",X,!0),U!==window&&window.addEventListener("mousedown",()=>I(null),!0),()=>{U.removeEventListener("mousedown",X,!0),U!==window&&window.removeEventListener("mousedown",()=>I(null),!0)}},[C]);const Me=i.useMemo(()=>({actionLogs:n,clearedTabs:t,conversationsByTabKey:z,hasDetachedConversationPanels:F,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:b,liveSessionInboxState:j,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:ge,userName:m,scrollToBottomRequest:M,tabShortcuts:le,openTabContextMenu:({x:V,y:U,tabKey:X,sourceDocument:se})=>I({x:V,y:U,tabKey:X,sourceDocument:se??document}),popoutTab:je,moveTabBackToMain:Ne,isTabInPopout:q,floatTab:he,isTabFloating:we}),[n,t,z,F,r,l,c,b,j,a,o,ge,m,M,le,je,Ne,q,he,we]),Ae=C?my({isTabInPopout:q(C.tabKey),isTabFloating:we(C.tabKey),tabShortcut:le[C.tabKey],actionShortcuts:f}):[],Ke=i.useCallback(V=>{var se;const U=S.current;if((((se=U==null?void 0:U.activePanel)==null?void 0:se.id)??null)===V.id){V.group.model.openPanel(V);return}V.group.model.openPanel(V),V.api.setActive()},[]),Ve=i.useCallback((V,U="requested-tab")=>{if(!V)return!1;const X=S.current;if(!X)return!1;const se=X.getPanel(V);return se?(Ke(se),ie(V,U),h==null||h(),!0):!1},[Ke,h,ie]),Xe=i.useCallback(()=>{if(P.current)return!1;const V=Ve(B.current,"stored-layout-restore");return V&&(P.current=!0),V},[Ve]),Ye=i.useCallback(()=>{var U;const V=S.current;V&&Hb(v,{activeTabId:((U=V.activePanel)==null?void 0:U.id)??null,layout:V.toJSON()})},[v]),tt=i.useCallback(()=>{zb(v,$.current)},[v]),ct=i.useCallback(V=>{var se,W,G,te;const U=S.current;if(!U)return{kind:"grid"};const X=U.toJSON();for(const re of X.floatingGroups||[])if((W=(se=re.data)==null?void 0:se.views)!=null&&W.includes(V)&&re.position)return{kind:"floating",position:re.position};for(const re of X.popoutGroups||[])if((te=(G=re.data)==null?void 0:G.views)!=null&&te.includes(V))return{kind:"popout",position:re.position,popoutUrl:re.url};return{kind:"grid"}},[]),mt=i.useCallback(V=>{const U=S.current;if(!U)return;const X=U.getPanel(V),se=$.current[V];if(!X||!se||se.kind==="grid")return;if(X.group.model.location.type===se.kind){delete $.current[V],tt();return}if(se.kind==="floating"){U.addFloatingGroup(X,{x:se.position.left??24,y:se.position.top??24,width:se.position.width,height:se.position.height}),delete $.current[V],tt();return}delete $.current[V],tt()},[tt]);i.useEffect(()=>(x==null||x({setShortcutForActiveTab:Ce,restoreHiddenTabToSavedLocation:mt,activateConversationTab:ae,resetAllPanelsToMain:J,activatePreviousTabInGroup:()=>ue(-1),activateNextTabInGroup:()=>ue(1),floatActiveTab:()=>{const V=xe();V&&he(V)},popoutActiveTab:()=>{const V=xe();V&&je(V)},dockActiveTab:()=>{const V=xe();V&&(q(V)?Ne(V):we(V)&&Se(V))},splitActiveTabRight:()=>Q("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Q("below",{createGroupIfMissing:!0}),focusLeftPane:()=>de("left"),focusRightPane:()=>de("right"),focusUpPane:()=>de("above"),focusDownPane:()=>de("below"),moveActiveTabToLeftPane:()=>Q("left"),moveActiveTabToRightPane:()=>Q("right"),moveActiveTabToUpPane:()=>Q("above"),moveActiveTabToDownPane:()=>Q("below")}),()=>x==null?void 0:x(null)),[ue,Se,he,de,xe,we,q,Q,Ne,je,x,J,mt,ae,Ce]),i.useEffect(()=>()=>{var V;(V=K.current)==null||V.call(K),K.current=null},[]);const pt=i.useCallback(V=>{var X,se;S.current=V.api,(X=K.current)==null||X.call(K),K.current=null;const U=Kb(v);if(B.current=(U==null?void 0:U.activeTabId)??null,U!=null&&U.layout&&V.api.fromJSON(U.layout,{reuseExistingPanels:!1}),N.current=bl({hasStoredLayout:!!(U!=null&&U.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),N.current||(kl(V.api,e),Sl(V.api,e,y)),V.api.totalPanels===0&&e.length>0){const W=vy(V.api,e,g);if(W){const G=V.api.getPanel(W);G&&Ke(G)}}else!N.current&&!Ve(g)&&Xe();if(L.current=!0,V.api.onDidActivePanelChange(W=>{var te;if(B.current=(W==null?void 0:W.id)??null,P.current=!0,fe(),W&&$t(W.id)){const re=((te=W.params)==null?void 0:te.routeId)||W.id.slice(7),ke=Ft(e,re);w((ke==null?void 0:ke.tabKey)??null),Ye();return}if(w((W==null?void 0:W.id)??null),Ye(),!W)return;const G=z.get(W.id);(G==null?void 0:G.streamSource)==="agent-stream"&&G.agentType&&T(G.routeId,Pc(),{agentType:G.agentType,...G.sessionId&&{targetSessionId:G.sessionId}}).catch(()=>{})}),V.api.onDidLayoutChange(()=>{Ye(),fe(),R(W=>W+1)}),xy()){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},te=Re=>{var Ue;const Fe=(Ue=k.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},re=hy({detachDelayMs:Jd,onDetach:({panelId:Re,clientX:Fe,clientY:Ue})=>{var dt,ht;const Le=V.api.getPanel(Re);if(!Le)return;try{if(Le.group.model.location.type!=="grid")return}catch{return}const Qe=(dt=k.current)==null?void 0:dt.getBoundingClientRect(),et=(ht=Le.group.element)==null?void 0:ht.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));V.api.addFloatingGroup(Le,{x:Qe?Math.max(0,Fe-Qe.left-32):void 0,y:Qe?Math.max(0,Ue-Qe.top-18):void 0,width:gt,height:yt}),Le.api.setActive(),Ye(),fe(),R(Ge=>Ge+1)}}),ke=[V.api.onWillDragPanel(Re=>{if(!(Re.nativeEvent.defaultPrevented||Re.nativeEvent.shiftKey)){try{if(Re.panel.group.model.location.type!=="grid")return}catch{return}re.startDrag({panelId:Re.panel.id,selfPanelBounds:G(Re.panel.group.element),...W(Re.nativeEvent)})}}),V.api.onWillShowOverlay(Re=>{if(re.hasDetached()){Re.preventDefault();return}re.markDockTarget(W(Re.nativeEvent))}),V.api.onWillDrop(Re=>{if(re.hasDetached()){Re.preventDefault(),re.endDrag();return}re.markDockTarget(W(Re.nativeEvent))}),V.api.onDidDrop(()=>re.endDrag()),V.api.onUnhandledDragOverEvent(Re=>{re.isDragging()&&re.markSelfPanel(W(Re.nativeEvent))})],Ee=Re=>{if(!re.isDragging())return;const Fe=W(Re);te(Fe)&&re.markNonSelfPanel(Fe)},Oe=()=>re.endDrag();window.addEventListener("dragover",Ee,!0),window.addEventListener("drop",Oe,!0),window.addEventListener("dragend",Oe,!0),K.current=()=>{re.dispose();for(const Re of ke)Re.dispose();window.removeEventListener("dragover",Ee,!0),window.removeEventListener("drop",Oe,!0),window.removeEventListener("dragend",Oe,!0)}}V.api.onDidAddGroup(W=>{requestAnimationFrame(()=>{var G,te;try{const re=(G=W.element)==null?void 0:G.ownerDocument;if(!re||re===document)return;(te=re.getElementById("dv-popout-window"))==null||te.classList.add("adhdev-dockview");const ke=document.documentElement.getAttribute("data-theme");ke&&re.documentElement.setAttribute("data-theme",ke),re.body.className=document.body.className;const Ee=document.documentElement.getAttribute("style");Ee&&re.documentElement.setAttribute("style",Ee)}catch{}fe(),R(re=>re+1)})}),w(((se=V.api.activePanel)==null?void 0:se.id)??null)},[Ke,Ve,z,r,d,v,w,Ye,g,y,T,fe,e]);i.useLayoutEffect(()=>{const V=S.current;if(!V||!L.current||N.current&&bl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;N.current&&(N.current=!1);const U=D.current,X=new Set(U),se=e.map(Oe=>Oe.tabKey),W=new Set(se),G=py({previousVisibleConversationCount:U.length,visibleConversationCount:e.length,ides:r});let te=!1;for(const Oe of U)W.has(Oe)||G||($.current[Oe]=ct(Oe),te=!0);te&&tt(),G||(kl(V,e),Sl(V,e,y));const re=se.filter(Oe=>!X.has(Oe));let ke=!1;for(const Oe of re){const Re=V.getPanel(Oe),Fe=$.current[Oe];if(!Re||!Fe||Fe.kind==="grid")continue;if(Re.group.model.location.type===Fe.kind){delete $.current[Oe],ke=!0;continue}if(Fe.kind==="floating"){V.addFloatingGroup(Re,{x:Fe.position.left??24,y:Fe.position.top??24,width:Fe.position.width,height:Fe.position.height}),delete $.current[Oe],ke=!0;continue}}if(ke&&tt(),D.current=se,g&&Ve(g))return;!V.activePanel&&V.panels[0]&&Ke(V.panels[0]),!!(V.activePanel&&V.getPanel(V.activePanel.id))||Xe()},[Ke,Ve,Xe,r,d,tt,ct,g,y,e]),i.useEffect(()=>{L.current&&Ve(g)},[Ve,g]),i.useEffect(()=>{const V=X=>{const se=X.target;if(!se)return;const W=se.querySelector("[data-tab-key]")||se.closest("[data-tab-key]");if(W){const G=W.getAttribute("data-tab-key");if(G&&X.dataTransfer){const te=se.closest(".dv-tab")||W.closest(".dv-tab")||W;X.dataTransfer.effectAllowed="move",X.dataTransfer.setData("text/tab-key",G),te instanceof HTMLElement&&X.dataTransfer.setDragImage(te,Math.max(12,Math.round(te.clientWidth/2)),Math.max(10,Math.round(te.clientHeight/2)))}}};window.addEventListener("dragstart",V);const U=jl(S.current);for(const X of U)X.addEventListener("dragstart",V);return()=>{window.removeEventListener("dragstart",V);for(const X of U)X.removeEventListener("dragstart",V)}},[E]),i.useEffect(()=>{var U;const V=(U=k.current)==null?void 0:U.querySelector(".adhdev-dockview");V instanceof HTMLElement&&Ca(V,A),ce(),fe()},[fe,ce,A]),i.useEffect(()=>{fe()},[fe]),i.useEffect(()=>{const V=U=>{if(U.defaultPrevented||pe)return;const X=_e(U);if(!X)return;const se=U.metaKey||U.ctrlKey||U.altKey;uo(U.target)&&!se||Pn(ve).setActiveTabShortcut!==X||(U.preventDefault(),U.stopPropagation(),Ce())};return window.addEventListener("keydown",V,!0),()=>window.removeEventListener("keydown",V,!0)},[_e,ve,pe,Ce]),i.useEffect(()=>{const V=k.current;if(!V)return;const U=X=>{var re,ke;if(!X.isTrusted)return;const se=(ke=(re=X.target)==null?void 0:re.closest)==null?void 0:ke.call(re,".dv-scrollable");if(!se)return;X.preventDefault(),X.stopPropagation();const W=Math.abs(X.deltaX),G=Math.abs(X.deltaY),te=W>G?X.deltaX:X.deltaY;se.dispatchEvent(new WheelEvent("wheel",{deltaY:te,deltaMode:X.deltaMode,bubbles:!1,cancelable:!0}))};return V.addEventListener("wheel",U,{passive:!1,capture:!0}),()=>V.removeEventListener("wheel",U,{capture:!0})},[]),i.useEffect(()=>{const V=jl(S.current);if(V.length===0)return;const U=V.map(X=>{let se=[],W=null;const G=()=>{W!=null&&X.clearTimeout(W),W=null,se=[]},te=()=>{W!=null&&X.clearTimeout(W),W=X.setTimeout(()=>{W=null,se=[]},1200)},re=Ee=>{if(!Ee.ctrlKey&&!Ee.metaKey&&!Ee.altKey)return;const Oe=_e(Ee);if(!Oe)return;const Re=Ud();for(const[Fe,Ue]of Object.entries(Re))if(e.some(Le=>Le.tabKey===Fe)&&Ue===Oe){Ee.preventDefault(),ae(Fe);return}},ke=Ee=>{if(Ee.defaultPrevented||pe)return;const Oe=_e(Ee);if(!Oe)return;const Re=Ee.metaKey||Ee.ctrlKey||Ee.altKey;if(uo(Ee.target))return;const Fe=Pn(ve),Ue=Object.entries(Fe).filter(([Ge,Wt])=>!!Wt&&(Ge==="splitActiveTabRight"||Ge==="splitActiveTabDown"||Ge==="floatActiveTab"||Ge==="popoutActiveTab"||Ge==="dockActiveTab"||Ge==="focusLeftPane"||Ge==="focusRightPane"||Ge==="focusUpPane"||Ge==="focusDownPane"||Ge==="moveActiveTabToLeftPane"||Ge==="moveActiveTabToRightPane"||Ge==="moveActiveTabToUpPane"||Ge==="moveActiveTabToDownPane"||Ge==="selectPreviousGroupTab"||Ge==="selectNextGroupTab"||Ge==="setActiveTabShortcut"||Ge==="hideCurrentTab")),Le=Re?[Oe]:[...se.slice(-1),Oe].slice(-2),Qe=Le.join(" "),et=Le[Le.length-1],gt=Ue.find(([,Ge])=>Ge===Qe);if(gt){Ee.preventDefault(),G(),H(gt[0]);return}if(Ue.some(([,Ge])=>Ge.startsWith(`${Qe} `))){Ee.preventDefault(),se=Le,te();return}const dt=Ue.find(([,Ge])=>Ge===et);if(dt){Ee.preventDefault(),G(),H(dt[0]);return}if(Ue.some(([,Ge])=>Ge.startsWith(`${et} `))){Ee.preventDefault(),se=[et],te();return}G()};return X.addEventListener("keydown",re),X.addEventListener("keydown",ke),()=>{G(),X.removeEventListener("keydown",re),X.removeEventListener("keydown",ke)}});return()=>{for(const X of U)X()}},[_e,ve,E,ae,pe,H,e]);const O=A==="light"?Ua:za,be=((qe=(Be=(Te=S.current)==null?void 0:Te.activePanel)==null?void 0:Be.group.element)==null?void 0:qe.ownerDocument)??document;return s.jsxs(Qd.Provider,{value:Me,children:[s.jsx("div",{ref:k,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Ju,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:wy,remote:jy},defaultTabComponent:Sy,watermarkComponent:ky,onReady:pt,singleTabMode:"default",tabAnimation:"smooth",theme:O,popoutUrl:"/popout.html"})}),C&&Sr.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:C.x,top:C.y},children:Ae.map(V=>{if(V.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},V.id);let U=s.jsx(ep,{size:13,className:"shrink-0 opacity-70"}),X=()=>{};switch(V.id){case"dockInWindow":case"dockBackToGrid":U=s.jsx(sp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{Se(C.tabKey),I(null)};break;case"moveBackToMain":U=s.jsx(Zm,{size:13,className:"shrink-0 opacity-70"}),X=()=>{Ne(C.tabKey),I(null)};break;case"floatAsPanel":U=s.jsx(tp,{size:13,className:"shrink-0 opacity-70"}),X=()=>{he(C.tabKey),I(null)};break;case"openInNewWindow":U=s.jsx(Qm,{size:13,className:"shrink-0 opacity-70"}),X=()=>{je(C.tabKey),I(null)};break;case"setShortcut":X=se=>{se.stopPropagation(),ne(C.tabKey),I(null)};break;case"removeShortcut":U=s.jsx(jt,{size:13,className:"shrink-0 opacity-70"}),X=()=>{const se={...le};delete se[C.tabKey],Ie(se),I(null)};break;case"hideTab":U=s.jsx(wo,{size:13,className:"shrink-0 opacity-70"}),X=()=>{ge(C.tabKey),I(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 ${V.tone==="muted"?"text-text-muted":""}`,onMouseDown:gy,onClick:X,children:[U,s.jsx("span",{className:"flex-1 min-w-0",children:V.label}),V.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:V.shortcut}):null]},V.id)})}),C.sourceDocument.body),pe&&Sr.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:()=>ne(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:V=>V.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 Zd="adhdev-recent-launch-args-v1",Cy=8;function eu(e){return String(e||"").trim().replace(/\s+/g," ")}function Zo(e,t){return`${e.trim()}::${t.trim()}`}function ei(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(Zd)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function tu(e){if(!(typeof window>"u"))try{window.localStorage.setItem(Zd,JSON.stringify(e))}catch{}}function mo(e,t){var o;const r=String(e||"").trim(),n=String(t||"").trim();return!r||!n?[]:((o=ei().byKey[Zo(r,n)])==null?void 0:o.items)||[]}function su(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=eu(r);if(!n||!a||!o)return;const l=ei(),c=Zo(n,a),d=((u=l.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(f=>f!==o)].slice(0,Cy);l.byKey[c]={items:m},tu(l)}function Iy(e,t,r){var u;const n=String(e||"").trim(),a=String(t||"").trim(),o=eu(r);if(!n||!a||!o)return;const l=ei(),c=Zo(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(f=>f!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],tu(l)}function ru(e){return!e.hasLoadedInitialResults&&!e.isLoading}function hn({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 My({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 nu({busy:e,savedSessionsLoading:t,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?Wd(o):null,u=My({savedSessionsLoading:t,savedSessionsLoaded:n,savedSessionsCount:a});return s.jsxs(hn,{title:"Saved history",description:Fo(),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:hx()})]}),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 au({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 Ay({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 Ia(e){var n;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Cs(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":t.some(a=>Cs(a,"acp"))?"acp":null}function sn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ty({machines:e,ides:t,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var Ge,Wt;const u=Rr(),f=i.useMemo(()=>[...e].sort(Ao),[e]),[x,w]=i.useState(((Ge=f[0])==null?void 0:Ge.id)||""),b=i.useMemo(()=>f.find(Z=>Z.id===x)||f[0],[x,f]),p=i.useMemo(()=>((b==null?void 0:b.workspaces)||[]).map(Z=>({id:Z.id,path:Z.path,label:Z.label})),[b]),g=(b==null?void 0:b.defaultWorkspaceId)||null,[y,h]=i.useState("workspace"),[M,j]=i.useState(""),[v,A]=i.useState(""),[T,S]=i.useState([]),[k,K]=i.useState(""),[L,N]=i.useState(!1),[P,B]=i.useState(null),[D,C]=i.useState(""),[I,E]=i.useState(Ia(f[0])),[R,$]=i.useState(""),[z,F]=i.useState(""),[me,ie]=i.useState([]),[ee,ce]=i.useState(""),[je,Ne]=i.useState([]),[q,ge]=i.useState(!1),[he,we]=i.useState(!1),[xe,Se]=i.useState(""),[J,fe]=i.useState(!1),[ae,ue]=i.useState(()=>Nt()),[oe,de]=i.useState(null),[Q,ve]=i.useState(!1),[le,pe]=i.useState(""),[ne,Ie]=i.useState(null),[Ce,_e]=i.useState(!1),[H,Me]=i.useState(""),[Ae,Ke]=i.useState([]),[Ve,Xe]=i.useState(!1),[Ye,tt]=i.useState(""),[ct,mt]=i.useState(!1),pt=i.useRef(null),O=i.useRef(0);i.useEffect(()=>{var Z;!x&&((Z=f[0])!=null&&Z.id)&&w(f[0].id)},[x,f]),i.useEffect(()=>{!b||!(!b.workspaces||!b.availableProviders||!b.detectedIdes||!b.recentLaunches)||u(b.id,{minFreshMs:3e4}).catch(()=>{})},[u,b]);const be=i.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(Z=>Cs(Z,"cli")),[b]),Te=i.useMemo(()=>((b==null?void 0:b.availableProviders)||[]).filter(Z=>Cs(Z,"acp")),[b]),Be=i.useMemo(()=>((b==null?void 0:b.detectedIdes)||[]).map(Z=>({id:Z.type,label:Z.name||Z.type,meta:Z.running?"Detected locally":"Available to open"})),[b]),qe=i.useMemo(()=>I==="cli"?be.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"CLI provider"})):I==="acp"?Te.map(Z=>({id:Z.type,label:Z.displayName||Z.type,meta:"ACP provider"})):Be,[Te,I,be,Be]),V=i.useMemo(()=>T.find(Z=>Z.id===k)||null,[T,k]),U=i.useMemo(()=>be.find(Z=>Z.type===R)||null,[be,R]),X=i.useMemo(()=>Pd(U==null?void 0:U.meshCoordinator,{meshId:(V==null?void 0:V.id)||"",workspace:(V==null?void 0:V.workspace)||""}),[U,V]),se=ne||X,W=i.useCallback(async Z=>{N(!0),C("");try{const $e=await c(Z);S($e),K(_=>{var Y;return $e.some(ye=>ye.id===_)?_:((Y=$e[0])==null?void 0:Y.id)||""}),B(Z)}catch($e){S([]),K(""),B(Z),C($e instanceof Error?$e.message:"Could not load meshes")}finally{N(!1)}},[c]);i.useEffect(()=>{var $e;if(!b)return;if(pt.current!==b.id){pt.current=b.id,h("workspace"),j(g||(($e=p[0])==null?void 0:$e.id)||"__home__"),A(""),S([]),K(""),B(null),C(""),E(Ia(b)),$(""),F(""),ce(""),Ne([]),we(!1),Se(""),ue(Nt()),pe(""),Ie(null);return}j(_=>{var Y;return _==="__custom__"||_==="__home__"||p.some(ye=>ye.id===_)?_:g||((Y=p[0])==null?void 0:Y.id)||"__home__"}),E(_=>_==="ide"&&Be.length>0||_==="cli"&&be.length>0||_==="acp"&&Te.length>0?_:Ia(b))},[Te.length,be.length,g,Be.length,b,p]),i.useEffect(()=>{!b||y!=="mesh"||P===b.id||L||W(b.id)},[W,P,L,b,y]),i.useEffect(()=>{y==="mesh"&&I!=="cli"&&be.length>0&&E("cli")},[I,be.length,y]),i.useEffect(()=>{var Z;I&&(qe.some($e=>$e.id===R)||$(((Z=qe[0])==null?void 0:Z.id)||""))},[I,qe,R]),i.useEffect(()=>{Ie(null)},[b==null?void 0:b.id,k,R,y]);const G=i.useCallback(async(Z,$e)=>{const _=O.current+1;return O.current=_,ge(!0),Se(""),m(Z,$e).then(Y=>{O.current===_&&Ne(Y)}).catch(Y=>{O.current===_&&(Ne([]),Se(Y instanceof Error?Y.message:"Could not load saved sessions"))}).finally(()=>{O.current===_&&(ge(!1),we(!0))})},[m]),te=i.useCallback((Z,$e)=>{ie(mo(Z,$e))},[]);i.useEffect(()=>{O.current+=1,ce(""),ue(Nt()),!b||!R||I==="ide"?ie([]):te(b.id,R),we(!1),Ne([]),Se(""),ge(!1)},[I,te,G,b,R]),i.useEffect(()=>{if(!ee)return;const Z=je.find($e=>$e.providerSessionId===ee);Z!=null&&Z.canResume||ce("")},[je,ee]);const re=M==="__custom__"?v.trim():M==="__home__"?"":((Wt=p.find(Z=>Z.id===M))==null?void 0:Wt.path)||"",ke=i.useMemo(()=>b?t.filter(Z=>Z.id!==b.id&&Z.daemonId===b.id).map(Z=>Z.workspace):[],[t,b]),Ee=i.useMemo(()=>((b==null?void 0:b.recentLaunches)||[]).map(Z=>Z.workspace),[b]),Oe=i.useCallback(Z=>{const $e=String(Z.workspace||"").trim();if(!$e)return;const _=p.find(Y=>sn(Y.path)===sn($e));if(_){j(_.id),A("");return}j("__custom__"),A($e)},[p]),Re=i.useCallback(Z=>{const $e=String(Z.workspace||"").trim();if(!$e)return{workspaceId:null,workspacePath:null};const _=p.find(Y=>sn(Y.path)===sn($e));return _?{workspaceId:_.id,workspacePath:null}:{workspaceId:null,workspacePath:$e}},[p]),Fe=i.useMemo(()=>je.find(Z=>Z.providerSessionId===ee)||null,[je,ee]),Ue=i.useMemo(()=>{var $e;if(I!=="cli"||!b||!R)return null;const Z=(($e=be.find(_=>_.type===R))==null?void 0:$e.displayName)||R;return{routeId:b.id,daemonId:b.id,providerSessionId:ee||void 0,transport:"pty",mode:"chat",agentName:Z,agentType:R,status:"idle",title:Z,messages:[],ideType:R,workspaceName:re,workspacePath:re,displayPrimary:Z,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${b.id}:${R}`,machineName:Tt(b,{fallbackId:b.id})}},[I,be,re,b,ee,R]),Le=i.useCallback(()=>{var $e;if(!b)return;j("__custom__"),_e(!0),tt("");const Z=Gn(b.platform,Vn(v.trim(),re,ke,Ee,b.defaultWorkspacePath,($e=p.find(_=>_.id===g))==null?void 0:$e.path,p.map(_=>_.path)));Xe(!0),n(b.id,Z).then(_=>{Me(_.path),A(_.path),Ke(_.directories)}).catch(_=>{tt(_ instanceof Error?_.message:"Could not load folder")}).finally(()=>Xe(!1))},[v,g,Ee,ke,n,re,b,p]),Qe=i.useCallback(Z=>{b&&(Xe(!0),tt(""),n(b.id,Z).then($e=>{Me($e.path),A($e.path),Ke($e.directories)}).catch($e=>{tt($e instanceof Error?$e.message:"Could not load folder")}).finally(()=>Xe(!1)))},[n,b]),et=i.useCallback(async()=>{if(!b||!re)return;mt(!0),pe("");const Z=await a(b.id,re);if(mt(!1),!Z.ok){pe(Z.error||"Could not save workspace");return}pe("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,re,b]),gt=i.useCallback(async()=>{if(!b)return;if(y==="mesh"){if(!k||!R)return;ve(!0),pe(""),Ie(null);const _=await d(b.id,k,R);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(!I||!R)return;ve(!0),pe("");const Z=z.trim()?z.trim().split(/\s+/).filter(Boolean):[],$e=I==="ide"?await o(b.id,R,{workspacePath:re||null}):await l(b.id,I,R,{workspaceId:M!=="__home__"&&M!=="__custom__"?M:null,workspacePath:M==="__custom__"&&re||null,resumeSessionId:I==="cli"&&ee?ee:null,cliArgs:Z});if(ve(!1),!$e.ok){pe($e.error||"Could not start session");return}I!=="ide"&&z.trim()&&(su(b.id,R,z),te(b.id,R)),r()},[I,z,te,r,o,d,l,re,b,k,ee,R,M,y]),yt=y==="mesh"?"Start mesh coordinator":I?ed(I,I==="cli"&&!!ee):"Start",dt=y==="mesh"?"Starting coordinator…":I?td(I,I==="cli"&&!!ee):"Starting…",ht=f.length>5;return b?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(hn,{title:"Machine",children:ht?s.jsx("select",{"aria-label":"Machine",value:b.id,onChange:Z=>w(Z.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q,children:f.map(Z=>s.jsx("option",{value:Z.id,children:Tt(Z,{fallbackId:Z.id})},Z.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:f.map(Z=>{const $e=Tt(Z,{fallbackId:Z.id}),_=b.id===Z.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(Z.id),disabled:Q,title:$e,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${Z.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:$e})]},Z.id)})})}),s.jsxs(hn,{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:Q,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(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":y===Z.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${y===Z.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:()=>{h(Z.id),pe(""),Z.id==="mesh"&&b&&P!==b.id&&!L&&W(b.id)},disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold",children:Z.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:Z.desc})]},Z.id))}),y==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:M,onChange:Z=>{const $e=Z.target.value;j($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:Q,children:[s.jsx("option",{value:"__home__",children:"Home directory"}),p.map(Z=>s.jsxs("option",{value:Z.id,children:[Z.id===g?"⭐ ":"",Wn(Z.path,Z.label)||Z.path]},Z.id)),s.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:M==="__home__"?"Launch without a workspace.":re||"Select a workspace folder."}),M==="__custom__"&&re&&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:Q,children:[s.jsx(ks,{size:14}),"Select folder"]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:et,disabled:Q||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&&D&&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:D}),!L&&!D&&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(Z=>s.jsxs("button",{type:"button",role:"radio","aria-checked":k===Z.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${k===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>K(Z.id),disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[Z.repoIdentity||"Repo mesh",typeof Z.nodesCount=="number"?` · ${Z.nodesCount} node${Z.nodesCount===1?"":"s"}`:""]}),Z.workspace&&s.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",Z.workspace]})]},Z.id))}),V&&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(Ay,{workspaceMode:y,activeKind:I,cliEnabled:be.length>0,ideEnabled:Be.length>0,acpEnabled:Te.length>0,busy:Q,onSelect:E}),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:I==="ide"?"Choose IDE":I==="cli"?"Choose CLI provider":"Choose ACP provider"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[qe.map(Z=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${R===Z.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(Z.id),disabled:Q,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Z.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Z.meta})]},Z.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"&&se&&s.jsx(au,{setup:se,providerName:(U==null?void 0:U.displayName)||(U==null?void 0:U.name)||R}),y!=="mesh"&&I!=="ide"&&s.jsxs(hn,{title:"Startup arguments",children:[s.jsx("input",{type:"text",value:z,onChange:Z=>F(Z.target.value),placeholder:"Optional flags...",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:Q}),me.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:me.map(Z=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>F(Z),disabled:Q,title:Z,children:Z},Z))})]}),y!=="mesh"&&I==="cli"&&s.jsx(nu,{busy:Q,savedSessionsLoading:q,savedSessionsError:xe,selectedSession:Fe,onRefresh:()=>{!b||!R||G(b.id,R)},onOpenHistory:()=>{!b||!R||(fe(!0),ru({hasLoadedInitialResults:he,isLoading:q})&&G(b.id,R))},onClearSelection:()=>ce("")}),le&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${le.includes("saved")||le.includes("requested")||le.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:le})]}),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:Q,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:Q||(y==="mesh"?!k||!R||I!=="cli"||L:!I||!R||M==="__custom__"&&!re),children:[s.jsx(ko,{size:14}),Q?dt:yt]})]})]})}),Ce&&s.jsx(Yn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:H,directories:Ae,busy:Ve,error:Ye,onClose:()=>_e(!1),onNavigate:Qe,onConfirm:Z=>{A(Z),Me(Z),j("__custom__"),_e(!1)}}),J&&Ue&&s.jsx(Ho,{activeConv:Ue,ides:[],isCreatingChat:!1,isRefreshingHistory:q,savedSessions:je,isSavedSessionsLoading:q,isResumingSavedSessionId:oe,savedHistoryFilters:ae,missingWorkspaceResumePath:re||null,onSavedHistoryFiltersChange:ue,onClose:()=>fe(!1),onNewChat:()=>{ce(""),fe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!b||!R||G(b.id,R)},onResumeSavedSession:Z=>{if(!b||!R||oe||!Z.canResume)return;const $e=Re(Z);ce(Z.providerSessionId),Oe(Z),de(Z.providerSessionId),fe(!1),ve(!0),pe(""),l(b.id,"cli",R,{workspaceId:$e.workspaceId,workspacePath:$e.workspacePath,resumeSessionId:Z.providerSessionId}).then(_=>{if(!_.ok){pe(_.error||"Could not resume session");return}r()}).finally(()=>{ve(!1),de(_=>_===Z.providerSessionId?null:_)})}})]}):null}function ou(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 iu(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=ou(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 lu(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function _y(e){var t;return!lu(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 cu(e){return e.nodes.filter(t=>t.type!=="submoduleNode")}function Ly(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=cu(e);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 Ry(e){const t=cu(e),r=new Set(t.map(o=>o.branch).filter(o=>!!o)).size,n=e.nodes.filter(o=>o.type==="submoduleNode").length,a=t.filter(o=>o.isOrphan).length;return t.length>=6||r>=3||n>=3||a>0}function du(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 Py(e,t,r){const n=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(r));return`${du(e)}::${n}x${a}`}const Dy={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"},Ey={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"},$y={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"},By={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 Qs(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",graphMiniMapClass:"!bottom-4 !right-4 !bg-white/95 !border !border-slate-200 !rounded-xl !shadow-md",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=>Ey[t],actionButton:t=>By[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",graphMiniMapClass:"!bottom-4 !right-4 !bg-slate-950/85 !border !border-white/10 !rounded-xl",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=>Dy[t],actionButton:t=>$y[t]}}const Nl=420,Cl=212,Il=132,Oy=44,Ml=166,Fy=24,uu=i.createContext(Qs("dark"));function Wy(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=iu(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 Vt(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 Ky(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 mu(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 Hy(e){return e.replace(/_/g," ")}function Uy(e){return!e.upstream||e.upstreamStatus==="fresh"}function zy(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),!Uy(e))t.push("upstream unverified");else{const n=ou(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 Vy({data:e,selected:t}){const r=i.useContext(uu),n=e.graphNode,a=n.type==="defaultBranchNode",o=n.type==="submoduleNode",l=_y(n),c=a?"default branch anchor":o?n.submodulePath||"submodule checkout":n.machineLabel||n.workspace,d=n.submoduleCommit?n.submoduleCommit.slice(0,7):null,m=iu(n),u=zy(n),f=lu(n);return s.jsxs("div",{className:`${o?"w-[204px]":"w-[220px]"} rounded-2xl border px-3.5 py-3 backdrop-blur-sm transition-all ${Wy(n,t,r.isDark)}`,children:[s.jsx(bi,{type:"target",position:gi.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:mu(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] ${Ky(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 ${Vt("health",r.isDark)}`,children:Hy(n.health)}),o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("submodule",r.isDark)}`,children:"submodule"}),n.branch&&!o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("meta",r.isDark)}`,children:n.branch}),d&&o&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("meta",r.isDark)}`,children:d}),n.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("dirty",r.isDark)}`,children:o?"local changes":`${n.dirtyFiles} dirty`}),n.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("conflict",r.isDark)}`,children:"out of sync"}),n.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("conflict",r.isDark)}`,children:"conflicts"}),!o&&n.upstream&&n.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("orphan",r.isDark)}`,children:"upstream unverified"}),n.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Vt("orphan",r.isDark)}`,children:"needs follow-up"})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,children:u}),l&&f&&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:f}),s.jsx(bi,{type:"source",position:gi.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Gy={meshNode:Vy};function Ma(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 qy(e,t=Qs("dark")){const r=[...e.nodes].sort(Ma),n=r.find(p=>p.type==="defaultBranchNode")??null,a=new Map;for(const p of r){if(p.type!=="submoduleNode"||!p.parentNodeId)continue;const g=a.get(p.parentNodeId)??[];g.push(p),a.set(p.parentNodeId,g)}const o=r.filter(p=>p.id!==(n==null?void 0:n.id)&&p.type!=="submoduleNode"),l=new Map,c=[];for(const p of o){if(p.isOrphan||!p.branch){c.push(p);continue}const g=p.branch,y=l.get(g)??[];y.push(p),l.set(g,y)}const d=[...l.entries()].sort(([p],[g])=>n!=null&&n.branch&&p===n.branch&&g!==n.branch?-1:n!=null&&n.branch&&g===n.branch&&p!==n.branch?1:p.localeCompare(g));c.length>0&&d.push(["__orphans__",[...c].sort(Ma)]),d.length===0&&d.push(["__nodes__",[]]);const m=[],u=d.length,f=Math.max(1,u-1)*Nl,x=n?0:80,w=n?Cl:0;n&&m.push({id:n.id,type:"meshNode",position:{x:f/2,y:x},data:{graphNode:n},selected:!1,draggable:!1,selectable:!0}),d.forEach(([p,g],y)=>{const h=y*Nl,M=g.length>0?g:o.length>0?o:[];let j=w;M.forEach(v=>{m.push({id:v.id,type:"meshNode",position:{x:h,y:j},data:{graphNode:v},selected:!1,draggable:!1,selectable:!0});const A=[...a.get(v.id)??[]].sort(Ma);if(A.length>0){A.forEach((T,S)=>{m.push({id:T.id,type:"meshNode",position:{x:h+Oy,y:j+Ml+S*Il},data:{graphNode:T},selected:!1,draggable:!1,selectable:!0})}),j+=Ml+A.length*Il+Fy;return}j+=Cl}),p==="__nodes__"&&o.length===0&&n&&m.push({id:`${n.id}__placeholder`,type:"meshNode",position:{x:h,y:w},data:{graphNode:{id:`${n.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:e.repoIdentity,branch:n.branch,upstream:null,upstreamStatus:null,machineLabel:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${n.id}__placeholder`,machineLabel:"",workspace:e.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}},selected:!1,draggable:!1,selectable:!1})});const b=e.edges.map(p=>({id:p.id,source:p.source,target:p.target,label:p.label,type:p.type==="worktreeLink"||p.type==="submoduleLink"?"smoothstep":"bezier",animated:p.type==="orphanLink",markerEnd:{type:rm.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:Al(p)},style:{stroke:Al(p),strokeWidth:p.type==="orphanLink"?2.25:p.type==="submoduleLink"?1.7:p.type==="worktreeLink"?1.8:2,strokeDasharray:p.type==="orphanLink"?"5 4":p.type==="submoduleLink"?"4 3":void 0},labelStyle:{fill:t.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:t.edgeLabelBackgroundColor,fillOpacity:1,stroke:t.edgeLabelBorderColor},labelBgPadding:[5,3],labelBgBorderRadius:6}));return{nodes:m,edges:b}}function Al(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 Yy({data:e,viewportKey:t}){const r=nm(),n=am(),a=i.useRef(null),o=i.useMemo(()=>du(e),[e]),l=i.useMemo(()=>Ly(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?.2:.16,maxZoom:m?1.04:.96,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,l,o,r,n,t]),null}function Xy({data:e,selectedNodeId:t=null,onNodeClick:r}){const{theme:n}=Js(),a=i.useMemo(()=>Qs(n),[n]),o=i.useMemo(()=>qy(e,a),[e,a]),l=i.useMemo(()=>Ry(e),[e]),c=i.useRef(null),[d,m]=i.useState({width:0,height:0}),u=i.useMemo(()=>Py(e,d.width,d.height),[e,d.height,d.width]),f=i.useMemo(()=>o.nodes.map(x=>({...x,selected:x.id===t})),[o.nodes,t]);return i.useEffect(()=>{const x=c.current;if(!x)return;const w=()=>{const p=Math.max(0,Math.round(x.clientWidth)),g=Math.max(0,Math.round(x.clientHeight));m(y=>y.width===p&&y.height===g?y:{width:p,height:g})};w();const b=typeof ResizeObserver=="function"?new ResizeObserver(()=>w()):null;return b==null||b.observe(x),window.addEventListener("resize",w),()=>{b==null||b.disconnect(),window.removeEventListener("resize",w)}},[]),s.jsx(uu.Provider,{value:a,children:s.jsxs("div",{ref:c,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-[420px] w-full min-w-0 min-h-[420px] sm:h-[520px] xl:h-[640px]",children:s.jsxs(Qu,{nodes:f,edges:o.edges,nodeTypes:Gy,minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!1,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(x,w)=>r==null?void 0:r(w.data.graphNode),className:"h-full w-full",colorMode:a.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(Yy,{data:e,viewportKey:u}),l&&s.jsx(Zu,{className:a.graphMiniMapClass,nodeColor:x=>mu(x.data.graphNode.health)}),s.jsx(em,{className:a.graphControlsClass,showInteractive:!1}),s.jsx(tm,{variant:sm.Dots,gap:18,size:1.2,color:a.graphBackgroundDotColor})]})})]})})}function bt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function De(...e){for(const t of e){if(typeof t!="string")continue;const r=t.trim();if(r)return r}}function Lt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function Dt(...e){for(const t of e)if(typeof t=="boolean")return t}function Aa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Jy(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 Qy(e,t){if(!Array.isArray(e))return;const r=e.map(n=>{const a=bt(n),o=De(a.path),l=De(a.commit),c=De(a.repoPath,a.repo_root)??Jy(t,o);return!o||!l||!c?null:{path:o,commit:l,repoPath:c,dirty:Dt(a.dirty)??!1,outOfSync:Dt(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:Lt(a.lastCheckedAt,a.last_checked_at)??Date.now(),...De(a.error)?{error:De(a.error)}:{}}}).filter(n=>n!==null);return r.length>0?r:void 0}function Zy(e){return Dt(e.isGitRepo)!==void 0||!!De(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||Lt(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 xn(e,t,r){const n=Dt(e.isGitRepo);if(!Object.keys(e).length||!Zy(e))return;const a=n??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(x=>typeof x=="string"):[],l=Lt(e.conflicts)??o.length,c=Dt(e.hasConflicts)??l>0,d=De(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,m=Qy(e.submodules,d),u=De(e.upstreamStatus,e.upstream_status),f=De(e.error);return{workspace:De(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:De(e.branch)??null,headCommit:De(e.headCommit)??null,headMessage:De(e.headMessage)??null,upstream:De(e.upstream)??null,upstreamStatus:u??"unchecked",ahead:Lt(e.ahead)??0,behind:Lt(e.behind)??0,staged:Lt(e.staged)??0,modified:Lt(e.modified)??0,untracked:Lt(e.untracked)??0,deleted:Lt(e.deleted)??0,renamed:Lt(e.renamed)??0,hasConflicts:c,conflictFiles:o,stashCount:Lt(e.stashCount,e.stash_count)??0,lastCheckedAt:(r==null?void 0:r.lastCheckedAt)??Lt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...m?{submodules:m}:{},...f?{error:f}:{}}}function e0(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),e.upstreamStatus&&e.upstreamStatus!=="unchecked"&&(t+=5),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 t0(e){const t=bt(e.lastGit??e.last_git),r=bt(t.result),n=bt(t.status),a=bt(r.status),o=bt(e.lastProbe??e.last_probe),l=bt(o.git),c=bt(l.result),d=bt(l.status),m=bt(c.status);let u=null;for(const f of[n,a,d,m]){const x=xn(f,e,{lastCheckedAt:Date.now()});if(!x)continue;const w=e0(x);(!u||w>u.score)&&(u={git:x,score:w})}return u==null?void 0:u.git}function s0(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 r0(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 Dn(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=s0(e);return t.outOfSync?"degraded":t.dirty||r0(e)?"dirty":"online"}function n0(e,t){const r=t?Dn(t):void 0;return!e||e==="unknown"?r:e}function a0(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=bt(o),c=De(l.sessionId,l.session_id,l.id);return c?{sessionId:c,...De(l.providerType,l.provider)?{providerType:De(l.providerType,l.provider)}:{},...De(l.state,l.status)?{state:De(l.state,l.status)}:{},...De(l.lifecycle)?{lifecycle:De(l.lifecycle)}:{},...De(l.surfaceKind,l.surface_kind)?{surfaceKind:De(l.surfaceKind,l.surface_kind)}:{},...De(l.recoveryState,l.recovery_state)?{recoveryState:De(l.recoveryState,l.recovery_state)}:{},...De(l.workspace)?{workspace:De(l.workspace)}:{},...De(l.title)?{title:De(l.title)}:{},...De(l.lastActivityAt,l.last_activity_at)?{lastActivityAt:De(l.lastActivityAt,l.last_activity_at)}:{},...Dt(l.isCached,l.is_cached)!==void 0?{isCached:Dt(l.isCached,l.is_cached)}:{}}:null}).filter(o=>o!==null);if(a.length>0)return a}const r=bt(e.activeSession??e.active_session),n=De(r.id,r.sessionId,r.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id);if(n)return[{sessionId:n,...De(r.providerType,r.provider)?{providerType:De(r.providerType,r.provider)}:{},...De(r.state,r.status)?{state:De(r.state,r.status)}:{}}]}function o0(e){const t=bt(e.connection);return Object.keys(t).length>0?t:void 0}function i0(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 ti(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 Tl(e){var n,a,o,l,c,d;let t=0;const r=e.git;return ti(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),r!=null&&r.upstreamStatus&&r.upstreamStatus!=="unchecked"&&(t+=6),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 l0(e,t){var w,b,p,g;const r=Tl(e),a=Tl(t)>r?t:e,o=a===t?e:t,l=a.git??o.git,c=(((w=a.providers)==null?void 0:w.length)??0)>0?a.providers:o.providers,d=(((b=a.activeSessions)==null?void 0:b.length)??0)>0?a.activeSessions:o.activeSessions,m=(((p=a.activeSessionDetails)==null?void 0:p.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,u=(((g=a.providerPriority)==null?void 0:g.length)??0)>0?a.providerPriority:o.providerPriority,f=a.connection??o.connection,x={...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")?Dn(l):a.health,providers:c??[],activeSessions:d??[],...m&&m.length>0?{activeSessionDetails:m}:{},...u&&u.length>0?{providerPriority:u}:{},...f?{connection:f}:{},...l?{git:l}:{}};return l&&(delete x.gitProbePending,delete x.error),x}function c0(e){const t=bt(e),r=De(t.nodeId,t.id);if(!r)return null;const n=bt(t.cachedStatus),a=t0(t),o=a?void 0:xn(bt(t.git),t)??xn(t,t),l=a??o,c=l?void 0:xn(bt(n.git),t),d=l??c,m=De(t.machineStatus,t.machine_status,n.machineStatus,n.machine_status),u=De(t.health),f=a?Dn(d):n0(u,l)||(d?Dn(d):void 0)||De(n.health)||m||De(t.status)||"unknown",w=(a?void 0:De(t.error))??(l?void 0:De(n.error)),b=a0(t),p=Aa(t.activeSessions),g=(b==null?void 0:b.map(S=>S.sessionId))??[],y=Aa(t.providerPriority),h=Dt(t.gitProbePending,t.git_probe_pending),M=l?void 0:h,j=o0(t),v=bt(t.branchConvergence??t.branch_convergence),A=j==null?void 0:j.state,T=a&&(!(j!=null&&j.reported)||A==="unknown")?i0(j):j;return{nodeId:r,machineLabel:De(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,r)||r,workspace:De(t.workspace,d==null?void 0:d.workspace)||"",...De(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:De(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...De(t.daemonId,t.daemon_id)?{daemonId:De(t.daemonId,t.daemon_id)}:{},...De(t.machineId,t.machine_id)?{machineId:De(t.machineId,t.machine_id)}:{},...m?{machineStatus:m}:{},...Dt(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:Dt(t.isLocalWorktree,t.is_local_worktree)}:{},...De(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:De(t.worktreeBranch,t.worktree_branch)}:{},health:f,...d?{git:d}:{},...M!==void 0?{gitProbePending:M}:{},providers:Aa(t.providers),activeSessions:p.length>0?p:g,...b&&b.length>0?{activeSessionDetails:b}:{},...y.length>0?{providerPriority:y}:{},...Dt(t.launchReady)!==void 0?{launchReady:Dt(t.launchReady)}:a?{launchReady:!0}:{},...De(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)?{lastSeenAt:De(t.lastSeenAt,t.last_seen_at,n.lastSeenAt,n.last_seen_at)}:{},...De(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)?{updatedAt:De(t.updatedAt,t.updated_at,n.updatedAt,n.updated_at)}:{},...T?{connection:T}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...w?{error:w}:{}}}function pu(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=l0(a,n);t.set(n.nodeId,o);const l=r.findIndex(c=>c.nodeId===n.nodeId);l>=0&&(r[l]=o)}return r}function fu(e){return{...e,nodes:pu(e.nodes??[])}}function d0(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:ti(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 u0(e){const t=De(e.meshId,e.mesh_id,e.id),r=e.nodes,n=Array.isArray(r)?r.map(d=>c0(d)).filter(d=>d!==null):null;if(!t||!n)return null;const a=pu(n),o=De(e.meshName,e.mesh_name,e.name),l=De(e.repoIdentity,e.repo_identity),c=De(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 m0(e){var o;let t=0;const r=bt(e.sourceOfTruth),n=bt(r.directPeerTruth);De(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),c.upstreamStatus&&c.upstreamStatus!=="unchecked"&&(t+=2),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 hu(e){const t=(e==null?void 0:e.result)??e,r=[e==null?void 0:e.status,t==null?void 0:t.status,t,e];let n=null;for(const a of r){const o=u0(bt(a));if(!o)continue;const l=m0(o);(!n||l>n.score)&&(n={status:o,score:l})}return(n==null?void 0:n.status)??null}const p0=5*60*1e3;function f0(e){return ti(e)}function si(e){var t;return f0(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function h0(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function ri(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function ni(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function Mr(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function x0(e){return Mr(e)?"degraded":ni(e)?"dirty":"online"}function b0(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function _l(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 Ta(e){return e.length===0?"unknown":e.reduce((t,r)=>_l(r)>_l(t)?r:t)}function g0(e){var o,l,c,d,m;const t=new Map,r=new Map;for(const u of e){const f=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();f&&(r.set(f,(r.get(f)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(f,(t.get(f)??0)+1))}const n=[...t.entries()].sort((u,f)=>{if(f[1]!==u[1])return f[1]-u[1];const x=["main","master","develop","dev"],w=x.indexOf(u[0]),b=x.indexOf(f[0]);return w!==-1||b!==-1?w===-1?1:b===-1?-1:w-b:u[0].localeCompare(f[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,f)=>f[1]-u[1])[0])==null?void 0:m[0])??null}function y0(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 Ll(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 v0(e){return e.reduce((t,r)=>Ll(r.status)>Ll(t.status)?r:t)}function w0(e){if(si(e))return null;const t=e.branchConvergence;if(!t||typeof t!="object")return null;const r=t.status;if(!r||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(r))return null;const n=e.git;return{status:r,needsConvergence:t.needsConvergence??r!=="merged_to_main",reason:t.reason??"provided_by_coordinator",nextStep:t.nextStep??null,branch:t.branch??(n==null?void 0:n.branch)??null,defaultBranch:t.defaultBranch??null,upstream:t.upstream??(n==null?void 0:n.upstream)??null,upstreamStatus:t.upstreamStatus??(n==null?void 0:n.upstreamStatus)??null,ahead:t.ahead??(n==null?void 0:n.ahead)??0,behind:t.behind??(n==null?void 0:n.behind)??0,dirty:t.dirty??(ri(n)||ni(n)),hasConflicts:t.hasConflicts??(!!(n!=null&&n.hasConflicts)||Mr(n))}}function j0(e,t){const r=w0(e);if(r)return{...r,defaultBranch:r.defaultBranch??t};if(!t||si(e))return null;const n=e.git,a=(n==null?void 0:n.branch)??null,o=(n==null?void 0:n.upstream)??null,l=(n==null?void 0:n.upstreamStatus)??null,c=(n==null?void 0:n.ahead)??0,d=(n==null?void 0:n.behind)??0,m=ri(n)||ni(n),u=!!(n!=null&&n.hasConflicts)||Mr(n),f={branch:a,defaultBranch:t,upstream:o,upstreamStatus:l,ahead:c,behind:d,dirty:m,hasConflicts:u};return(n==null?void 0:n.isGitRepo)!==!0?{...f,status:"blocked_review",needsConvergence:!0,reason:"git_status_unavailable",nextStep:`Resolve git status for '${e.machineLabel||e.nodeId}' before declaring the mesh converged.`}:a?u||m?{...f,status:"not_mergeable",needsConvergence:!0,reason:n!=null&&n.hasConflicts?"conflicts_present":Mr(n)?"submodule_out_of_sync":"dirty_workspace",nextStep:`Commit, checkpoint, or resolve '${a}' before any convergence step into ${t}.`}:o&&l&&l!=="fresh"?{...f,status:"blocked_review",needsConvergence:!0,reason:"upstream_unverified",nextStep:`Refresh '${a}' against ${o} before claiming the mesh is converged.`}:a===t?c>0||d>0?{...f,status:"blocked_review",needsConvergence:!0,reason:"default_branch_not_even_with_upstream",nextStep:`Bring ${t} even with ${o??"its upstream"} before declaring convergence complete.`}:{...f,status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch",nextStep:null}:e.isLocalWorktree?{...f,status:"cleanup_candidate",needsConvergence:!0,reason:"clean_non_default_worktree_branch",nextStep:`Run refine / cleanup for '${a}' or explicitly classify the worktree before ending the task.`}:!o||c>0||d>0?{...f,status:"blocked_review",needsConvergence:!0,reason:o?"feature_branch_not_even_with_upstream":"feature_branch_missing_upstream",nextStep:`Push or reconcile '${a}', then merge it into ${t} or mark it blocked with a reason.`}:{...f,status:"pushed_feature_branch_needs_merge",needsConvergence:!0,reason:"clean_non_default_branch",nextStep:`Review and merge '${a}' into ${t}; do not treat it as fully complete while it remains off ${t}.`}:{...f,status:"blocked_review",needsConvergence:!0,reason:"branch_unknown",nextStep:`Inspect '${e.machineLabel||e.nodeId}' and confirm which branch should converge into ${t}.`}}function k0(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function S0(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(si(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const f=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(f?`${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(f=>f.path));if(r.size>0){const f=[...r].filter(x=>!c.has(x));f.length>0&&a.push(`${o} is missing submodule visibility for ${f.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>p0&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(f=>f.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(f=>f.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function N0(e){var L;const t=fu(e),n=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??g0(t.nodes),a=h0(t.refreshedAt),o=new Set(t.nodes.flatMap(N=>{var P;return(((P=N.git)==null?void 0:P.submodules)??[]).map(B=>B.path)})),l=[],c=[],d=[],m=new Map;for(const N of t.nodes){const P=N.git,B=(P==null?void 0:P.branch)??null,D=x0(P),C=ri(P)||D==="dirty",I=y0(N,n),E=j0(N,n),R=S0({nodeStatus:N,expectedSubmodulePaths:o,refreshedAtMs:a}),$={id:N.nodeId,type:I.length>0?"orphanNode":"worktreeNode",label:N.machineLabel||N.nodeId.slice(0,8),workspace:N.workspace,branch:B,upstream:(P==null?void 0:P.upstream)??null,upstreamStatus:(P==null?void 0:P.upstreamStatus)??null,machineLabel:N.machineLabel||null,health:Ta([N.health,D]),ahead:(P==null?void 0:P.ahead)??0,behind:(P==null?void 0:P.behind)??0,dirty:C,dirtyFiles:b0(P),hasConflicts:(P==null?void 0:P.hasConflicts)??!1,activeSessionCount:((L=N.activeSessions)==null?void 0:L.length)??0,activeSessions:N.activeSessions??[],providers:N.providers??[],isOrphan:I.length>0,orphanReasons:I,error:N.error,nextStepHint:R.snapshotWarnings[0]??I[0]??(E==null?void 0:E.nextStep)??void 0,parentNodeId:null,submodulePath:null,submoduleCommit:(P==null?void 0:P.headCommit)??null,outOfSync:Mr(P),snapshotCompleteness:R.snapshotCompleteness,snapshotWarnings:R.snapshotWarnings,branchConvergence:E,source:N};if(l.push($),B){const z=m.get(B)??[];z.push($.id),m.set(B,z)}for(const z of(P==null?void 0:P.submodules)??[]){const F=`${$.id}::submodule::${z.path}`,me=z.path.split("/").filter(Boolean).pop()||z.path;l.push({id:F,type:"submoduleNode",label:me,workspace:z.repoPath,branch:null,upstream:null,upstreamStatus:null,machineLabel:$.machineLabel,health:k0(z),ahead:0,behind:0,dirty:z.dirty,dirtyFiles:z.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:z.error,nextStepHint:z.error||(z.outOfSync?`${z.path} is out of sync with the parent checkout`:z.dirty?`${z.path} has local changes`:`${z.path} is in sync with the parent checkout`),parentNodeId:$.id,submodulePath:z.path,submoduleCommit:z.commit,outOfSync:z.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:$.id,parentWorkspace:N.workspace,submodule:z}}),c.push({id:`${$.id}--${F}`,source:$.id,target:F,type:"submoduleLink",label:z.outOfSync?"submodule out of sync":"submodule"})}}const u=n?`__branch_${n}`:null;if(u&&n){const P=(m.get(n)??[]).map(E=>l.find(R=>R.id===E)).filter(Boolean),B=P.map(E=>E.branchConvergence).filter(Boolean),D=B.length>0?v0(B):null,C=B.filter(E=>E.needsConvergence).length,I={id:u,type:"defaultBranchNode",label:n,workspace:t.repoIdentity,branch:n,upstream:null,upstreamStatus:null,machineLabel:"default branch",health:Ta(P.map(E=>E.health)),ahead:0,behind:0,dirty:P.some(E=>E.dirty),dirtyFiles:P.reduce((E,R)=>E+R.dirtyFiles,0),hasConflicts:P.some(E=>E.hasConflicts),activeSessionCount:P.reduce((E,R)=>E+R.activeSessionCount,0),activeSessions:P.flatMap(E=>E.activeSessions),providers:[...new Set(P.flatMap(E=>E.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:C>0?`${C} workspace(s) on ${n} still need follow-up`:P.length>0?`${P.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:D,source:{nodeId:u,machineLabel:n,workspace:t.repoIdentity,health:Ta(P.map(E=>E.health)),providers:[],activeSessions:[]}};l.push(I);for(const E of l)if(!(E.id===u||E.type==="submoduleNode")){if(E.branch===n){c.push({id:`${u}--${E.id}`,source:u,target:E.id,type:"parentBranch",label:"checked out"});continue}if(E.branch){c.push({id:`${u}--${E.id}`,source:u,target:E.id,type:E.isOrphan?"orphanLink":"parentBranch",label:E.branch});continue}E.isOrphan&&c.push({id:`${u}--${E.id}`,source:u,target:E.id,type:"orphanLink",label:"detached"})}}for(const[N,P]of m){if(P.length<2)continue;const B=P.map(D=>l.find(C=>C.id===D)).filter(Boolean);B.sort((D,C)=>D.label.localeCompare(C.label));for(let D=1;D<B.length;D+=1)c.push({id:`wt_${B[D-1].id}--${B[D].id}`,source:B[D-1].id,target:B[D].id,type:"worktreeLink",label:D===1?`${N} peers`:void 0})}const f=l.filter(N=>N.type!=="defaultBranchNode"),x=f.filter(N=>N.isOrphan).length,w=f.filter(N=>N.hasConflicts).length,b=f.filter(N=>N.health==="offline").length,p=f.filter(N=>N.type==="submoduleNode"&&N.outOfSync).length,g=f.filter(N=>{var P;return N.type!=="submoduleNode"&&((P=N.branchConvergence)==null?void 0:P.needsConvergence)}).length,y=f.filter(N=>{var P;return((P=N.branchConvergence)==null?void 0:P.status)==="blocked_review"}).length,h=f.filter(N=>{var P;return((P=N.branchConvergence)==null?void 0:P.status)==="pushed_feature_branch_needs_merge"}).length,M=f.filter(N=>{var P;return((P=N.branchConvergence)==null?void 0:P.status)==="cleanup_candidate"}).length,j=f.filter(N=>{var P;return((P=N.branchConvergence)==null?void 0:P.status)==="not_mergeable"}).length,v=f.filter(N=>N.snapshotWarnings.length>0).length,A=f.filter(N=>N.snapshotCompleteness==="pending_git").length,T=f.filter(N=>N.snapshotCompleteness==="missing_git").length,S=f.filter(N=>N.snapshotCompleteness==="missing_submodule_report").length,k=f.filter(N=>N.snapshotCompleteness==="stale").length,K=[A>0?`${A} node(s) are still waiting for a live peer git snapshot`:null,T>0?`${T} node(s) have no visible peer git snapshot`:null,S>0?`${S} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,k>0?`${k} 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`),x>0&&d.push(`${x} workspace(s) need attention before safe coordination`),y>0&&d.push(`${y} workspace(s) are blocked on branch convergence or upstream sync`),h>0&&d.push(`${h} clean feature branch workspace(s) still need merge follow-up`),M>0&&d.push(`${M} worktree workspace(s) are ready for refine / cleanup`),j>0&&d.push(`${j} workspace(s) have local changes or conflicts blocking convergence`),w>0&&d.push(`${w} workspace(s) report merge conflicts`),b>0&&d.push(`${b} node(s) are currently offline`),p>0&&d.push(`${p} submodule(s) are out of sync with their parent checkout`),d.push(...K),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:f.length,onlineNodes:f.filter(N=>N.health==="online").length,dirtyNodes:f.filter(N=>N.dirty).length,orphanNodes:x,errorNodes:f.filter(N=>!!N.error||N.outOfSync).length,offlineNodes:b,followUpNodes:g,blockedReviewNodes:y,mergeReadyNodes:h,cleanupCandidateNodes:M,notMergeableNodes:j,incompleteSnapshotNodes:v,missingGitSnapshotNodes:T,missingSubmoduleSnapshotNodes:S,staleGitSnapshotNodes:k,totalActiveSessions:f.reduce((N,P)=>N+P.activeSessionCount,0)},warnings:d,snapshotWarnings:K}}const C0={recentFailures:0},ai=i.createContext(Qs("dark"));function nt({label:e,tone:t="default"}){const r=i.useContext(ai);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 ts({label:e,value:t}){const r=i.useContext(ai);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 I0(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 M0(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 A0(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 T0(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 _0(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 Rl(e){return e?e.slice(0,7):null}function L0(e,t){var o,l,c;const r=Rl((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?[Rl(a.commit),a.message].filter(Boolean).join(" · "):null}function R0(e,t){const r=L0(e,t);return r||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function P0(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 D0(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 E0(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":T0(e.connection)}function $0(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 B0(e,t){return t?e.nodes.find(r=>r.id===t)??null:null}function xu({status:e,emptyMessage:t="No live mesh graph is available for this coordinator yet.",daemonId:r=null,sendDaemonCommand:n=null}){var I,E,R,$,z;const{theme:a}=Js(),o=i.useMemo(()=>Qs(a),[a]),l=i.useMemo(()=>fu(e),[e]),c=i.useMemo(()=>N0(l),[l]),[d,m]=i.useState(null),[u,f]=i.useState(null),[x,w]=i.useState({}),b=i.useMemo(()=>new Map(l.nodes.map(F=>[F.nodeId,F])),[l.nodes]),p=i.useMemo(()=>new Map(c.nodes.map(F=>[F.id,F])),[c.nodes]),g=((I=l.queue)==null?void 0:I.summary)??null,y=((E=l.ledger)==null?void 0:E.summary)??C0,h=i.useMemo(()=>_0(l),[l]),M=i.useMemo(()=>{const F=new Map;for(const me of h){const ie=me.session.state||me.session.lifecycle||"unknown";F.set(ie,(F.get(ie)??0)+1)}return[...F.entries()].sort((me,ie)=>ie[1]-me[1])},[h]);i.useEffect(()=>{d&&(p.has(d)||(m(null),f(F=>!F||"nodeId"in F&&F.nodeId===d?null:F)))},[p,d]);const j=d?b.get(d)??null:null,v=B0(c,d);i.useEffect(()=>{var F,me,ie;if(d)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:l.meshId,selectedNodeId:d,canonicalNode:d0(j),graphNode:v?{id:v.id,branch:v.branch,upstream:v.upstream,headCommit:v.submoduleCommit,submoduleCount:((me=(F=j==null?void 0:j.git)==null?void 0:F.submodules)==null?void 0:me.length)??0,snapshotCompleteness:v.snapshotCompleteness,snapshotWarnings:v.snapshotWarnings,branchConvergence:((ie=v.branchConvergence)==null?void 0:ie.status)??null}:null})}catch{}},[l.meshId,v,d,j]);const A=(u==null?void 0:u.kind)==="session"?h.find(F=>F.nodeId===u.nodeId&&F.session.sessionId===u.sessionId)??null:null,T=i.useMemo(()=>h.filter(F=>F.nodeId===d),[d,h]),S=D0({coordinatorDaemonId:r,selectedNodeStatus:j,selectedSessionEntry:A}),k=(S==null?void 0:S.workspace)??null,K=k?x[k]??null:null,L=R0(j,(K==null?void 0:K.entries)??[]),N=i.useCallback(()=>{m(null),f(null)},[]);i.useEffect(()=>{if(!v)return;const F=me=>{me.key==="Escape"&&N()};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[N,v]),i.useEffect(()=>{if(!S||!n)return;const{daemonId:F,workspace:me}=S,ie=x[me];if(ie!=null&&ie.loading||ie&&(ie.entries.length>0||ie.error))return;let ee=!1;return w(ce=>{var je;return{...ce,[me]:{loading:!0,error:null,entries:((je=ce[me])==null?void 0:je.entries)??[]}}}),n(F,"git_log",{workspace:me,limit:5}).then(ce=>{ee||w(je=>({...je,[me]:{loading:!1,error:null,entries:P0(ce)}}))}).catch(ce=>{ee||w(je=>({...je,[me]:{loading:!1,error:ce instanceof Error?ce.message:"git_log failed",entries:[]}}))}),()=>{ee=!0}},[x,S,n]);const P=[...c.warnings??[],...l.nodes.filter(F=>F.machineStatus&&F.machineStatus!=="online").map(F=>`${F.machineLabel}: ${F.machineStatus}`)],B=c.stats.incompleteSnapshotNodes>0,D=c.stats.followUpNodes>0?`${c.stats.followUpNodes} need follow-up`:B?"mesh visibility incomplete":"mesh converged",C=c.stats.followUpNodes>0?"danger":B?"warn":"good";return s.jsx(ai.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:`mb-3 flex flex-wrap items-start justify-between gap-3 rounded-2xl px-3.5 py-3 ${o.isDark?"border border-white/10 bg-slate-950/45":"border border-slate-200 bg-white/95 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:D,tone:C}),c.stats.blockedReviewNodes>0&&s.jsx(nt,{label:`${c.stats.blockedReviewNodes} blocked review`,tone:"danger"}),c.stats.notMergeableNodes>0&&s.jsx(nt,{label:`${c.stats.notMergeableNodes} not mergeable`,tone:"danger"}),c.stats.mergeReadyNodes>0&&s.jsx(nt,{label:`${c.stats.mergeReadyNodes} need merge`,tone:"warn"}),c.stats.cleanupCandidateNodes>0&&s.jsx(nt,{label:`${c.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info"}),c.stats.offlineNodes>0&&s.jsx(nt,{label:`${c.stats.offlineNodes} offline`,tone:"danger"}),c.stats.incompleteSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn"}),c.stats.missingGitSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn"}),c.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn"}),c.stats.staleGitSnapshotNodes>0&&s.jsx(nt,{label:`${c.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn"}),((g==null?void 0:g.active)??0)>0&&s.jsx(nt,{label:`${(g==null?void 0:g.active)??0} active queue`,tone:"info"}),s.jsx(nt,{label:`${c.stats.totalNodes} nodes`,tone:"default"}),c.stats.totalActiveSessions>0&&s.jsx(nt,{label:`${c.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:`${c.stats.dirtyNodes} dirty`,tone:c.stats.dirtyNodes>0?"warn":"good"}),s.jsx(nt,{label:`${c.stats.orphanNodes} orphan`,tone:c.stats.orphanNodes>0?"warn":"good"}),s.jsx(nt,{label:`${y.recentFailures} recent failures`,tone:y.recentFailures>0?"danger":"good"}),M.length===0?s.jsx(nt,{label:"no session metadata"}):M.slice(0,2).map(([F,me])=>s.jsx(nt,{label:`${me} ${F}`,tone:M0(F)},F))]}),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"})]}),P.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:P.map(F=>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:F},F))}),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."})]})]})]}),c.nodes.length>0?s.jsx(Xy,{data:c,selectedNodeId:d,onNodeClick:F=>{if((u==null?void 0:u.kind)==="node"&&d===F.id){m(null),f(null);return}m(F.id),f({kind:"node",nodeId:F.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}),v&&(u==null?void 0:u.kind)==="node"&&s.jsx("div",{className:"absolute inset-3 z-20 flex items-center justify-center rounded-[24px] bg-slate-950/35 p-3 backdrop-blur-sm",onClick:N,role:"presentation",children:s.jsxs("section",{role:"dialog","aria-modal":"false","aria-label":"Selected node",className:o.isDark?"max-h-[min(78vh,520px)] w-full max-w-xl overflow-y-auto rounded-2xl border border-white/12 bg-slate-950/95 p-4 shadow-2xl shadow-black/40":"max-h-[min(78vh,520px)] w-full max-w-xl overflow-y-auto rounded-2xl border border-slate-200 bg-white/95 p-4 shadow-2xl shadow-slate-900/15",onClick:F=>F.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:v.label}),s.jsx("div",{className:`mt-1 font-mono text-[11px] ${o.textMuted}`,children:v.id.slice(0,16)})]}),s.jsx("button",{type:"button",onClick:N,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:(j==null?void 0:j.health)??v.health,tone:I0((j==null?void 0:j.health)??v.health)}),v.branch&&s.jsx(nt,{label:v.branch,tone:"default"}),v.ahead>0&&s.jsx(nt,{label:`ahead ${v.ahead}`,tone:"warn"}),v.behind>0&&s.jsx(nt,{label:`behind ${v.behind}`,tone:"warn"}),v.dirtyFiles>0&&s.jsx(nt,{label:`${v.dirtyFiles} dirty`,tone:"warn"}),(j==null?void 0:j.connection)&&s.jsx(nt,{label:E0(j),tone:A0(j.connection)}),T.length>0&&s.jsx(nt,{label:`${T.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-2 text-xs sm:grid-cols-2",children:[s.jsx(ts,{label:"Workspace",value:(j==null?void 0:j.workspace)??v.workspace}),s.jsx(ts,{label:"Branch",value:v.branch??"unknown"}),s.jsx(ts,{label:"HEAD",value:L??(j!=null&&j.gitProbePending?"Pending live git probe":"not reported")}),s.jsx(ts,{label:"Upstream",value:v.upstream??"none"}),s.jsx(ts,{label:"Dirty/ahead/behind",value:`${v.dirtyFiles} dirty · ↑${v.ahead}/↓${v.behind}`}),s.jsx(ts,{label:"Source",value:String(((R=j==null?void 0:j.connection)==null?void 0:R.source)??$0(v))}),s.jsx(ts,{label:"Transport",value:(($=j==null?void 0:j.connection)==null?void 0:$.transport)??"unknown"}),s.jsx(ts,{label:"Sessions",value:T.length>0?T.map(F=>F.session.state||F.session.lifecycle||"unknown").join(", "):"none active"})]}),v.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:v.snapshotWarnings[0]})]}),((z=v.branchConvergence)==null?void 0:z.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:v.branchConvergence.nextStep})]})]})})]})})})})}function O0({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=Rd(),{theme:l}=Js(),c=i.useMemo(()=>Qs(l),[l]),[d,m]=i.useState(null),[u,f]=i.useState(!1),[x,w]=i.useState(null),[b,p]=i.useState(null),g=i.useRef(!1);i.useEffect(()=>{g.current=d!==null},[d]);const y=i.useCallback(async(A=!1)=>{if(!a||!n){w("This coordinator does not expose a live mesh id."),m(null);return}f(!g.current),w(null);try{const T=o!=null&&o.loadMeshStatus?await o.loadMeshStatus(a,n,{refresh:A}):await t(a,"mesh_status",{meshId:n,refresh:A}),S=hu(T);if(!S){w("mesh_status returned an unexpected payload.");return}m(S),p(S.refreshedAt||new Date().toISOString())}catch(T){w(T instanceof Error?T.message:"Failed to load live mesh status")}finally{f(!1)}},[a,n,o,t]);i.useEffect(()=>{y(!1)},[y]),i.useEffect(()=>{const A=T=>{T.key==="Escape"&&r()};return window.addEventListener("keydown",A),()=>window.removeEventListener("keydown",A)},[r]);const h=(d==null?void 0:d.meshName)||n||"Repo Mesh",M=b?new Date(b).toLocaleTimeString():null,j=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:A=>A.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(rs,{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:h}),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:[M&&s.jsxs("span",{className:c.dialogRefreshedChipClass,children:["Refreshed ",M]}),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})})]})]}),x&&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:x}),s.jsx("div",{className:c.dialogBodyClass,children:d?s.jsx(xu,{status:d,emptyMessage:j,daemonId:a,sendDaemonCommand:t}):s.jsx("div",{className:c.dialogEmptyClass,children:j})})]})})}function F0(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=W0(n);return{remoteUrl:n,githubUrl:c,loading:o}}function W0(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 bu=5e3;function K0(e){return`git:${e}`}function H0({workspace:e,includeDiffSummary:t=!1,intervalMs:r=bu}){return{type:"subscribe",topic:"workspace.git",key:K0(e),params:{workspace:e,includeDiffSummary:t,intervalMs:r}}}function oi(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Is(e,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 U0(e){const t=oi(e);return(t==null?void 0:t.success)===!1?{status:null,error:Is(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Is(t,"Git status response did not include status")}}function z0(e){const t=oi(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Is(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Is(t,"Git diff summary response did not include diffSummary")}}function _a(e){return e===void 0||typeof e=="boolean"}function V0(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&_a(t.binary)&&_a(t.truncated)&&_a(t.staged)}function G0(e){const t=oi(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Is(t,"Git file diff request failed")}:V0(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Is(t,"Git file diff response did not include a valid diff object")}}function q0({daemonId:e,workspace:t,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=bu}){const{sendCommand:o,sendData:l}=kt(),c=typeof t=="string"?t.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[f,x]=i.useState(null),[w,b]=i.useState(!1),[p,g]=i.useState(null),y=i.useCallback(async()=>{if(!(!d||!e||!c)){b(!0),g(null);try{const M=U0(await o(e,"git_status",{workspace:c}));if(M.error){u(null),x(null),g(M.error);return}if(u(M.status),!n){x(null);return}const j=z0(await o(e,"git_diff_summary",{workspace:c}));if(j.error){x(null),g(j.error);return}x(j.diffSummary)}catch(M){g(Is(M,"Git status request failed"))}finally{b(!1)}}},[d,e,n,o,c]),h=i.useMemo(()=>c?H0({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!h){u(null),x(null),b(!1),g(null);return}const M=l?Xt.subscribe({sendData:l},e,h,j=>{var v,A;j.workspace===c&&(u(j.status),x(j.diffSummary??null),g(((v=j.status)==null?void 0:v.error)||((A=j.diffSummary)==null?void 0:A.error)||null),b(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{M==null||M()}},[d,e,y,h,l,c]),{status:m,diffSummary:f,loading:w,error:p,refresh:y}}const Y0={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},X0={added:"text-emerald-400",modified:"text-orange-400",deleted:"text-red-400",renamed:"text-sky-400",copied:"text-sky-400",untracked:"text-zinc-400",conflict:"text-red-400 font-bold"};function Pl(e){return e.split("/").pop()??e}function J0(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function Q0({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=Y0[o.status]??"?",d=X0[o.status]??"text-zinc-400",m=J0(o.path),u=Pl(o.path),f=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:["← ",Pl(o.oldPath)]}),f]}),!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 Z0(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 ev({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(`
|
|
65
|
+
`);return s.jsxs("div",{ref:l,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,m)=>Z0(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 tv(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(`
|
|
66
|
+
`)}function gu({daemonId:e,workspace:t,onClose:r}){const{sendCommand:n}=kt(),{status:a,diffSummary:o,loading:l,error:c,refresh:d}=q0({daemonId:e,workspace:t,includeDiffSummary:!0}),[m,u]=i.useState(null),[f,x]=i.useState(null),[w,b]=i.useState(""),[p,g]=i.useState(!1),[y,h]=i.useState(!1),[M,j]=i.useState(null),[v,A]=i.useState(null),{githubUrl:T}=F0(e,t),S=i.useCallback(async B=>{if(!((m==null?void 0:m.path)===B.path&&!m.loading)){u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const D=await n(e,"git_diff_file",{workspace:t,path:B.path,staged:B.staged}),C=G0(D);if(C.error||!C.diff){u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C.error??"Failed to load diff"});return}u({path:B.path,diff:C.diff.diff,binary:C.diff.binary??!1,truncated:C.diff.truncated??!1,loading:!1,error:null})}catch(D){const C=D instanceof Error?D.message:"Failed to load diff";u({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:C})}}},[e,n,m,t]),k=i.useCallback(B=>{b(""),g(!1),j(null),A(null),x(B)},[]),K=i.useCallback(()=>{x(null),j(null),h(!1)},[]),L=i.useCallback(async()=>{var B,D,C;if(f){h(!0),j(null);try{let I;f==="checkpoint"?I=await n(e,"git_checkpoint",{workspace:t,message:w,includeUntracked:p}):f==="stash"?I=await n(e,"git_stash_push",{workspace:t,message:w,includeUntracked:p}):f==="stash_pop"?I=await n(e,"git_stash_pop",{workspace:t}):f==="checkout_files"&&m&&(I=await n(e,"git_checkout_files",{workspace:t,paths:[m.path]}));const E=(I==null?void 0:I.result)??I;if((E==null?void 0:E.success)===!1||E!=null&&E.error){j((E==null?void 0:E.error)??"Action failed"),h(!1);return}f==="checkpoint"?A(`Checkpoint created: ${((D=(B=E==null?void 0:E.checkpoint)==null?void 0:B.commit)==null?void 0:D.slice(0,7))??"done"}`):f==="stash"?A(`Stashed as ${((C=E==null?void 0:E.stash)==null?void 0:C.stashRef)??"stash@{0}"}`):f==="stash_pop"?A("Stash restored"):(A("File reverted"),u(null)),x(null),await d()}catch(I){j(I instanceof Error?I.message:"Action failed")}finally{h(!1)}}},[f,n,e,t,w,p,m,d]),N=!!(a!=null&&a.hasConflicts),P=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:B=>{B.target===B.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"}),P===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(Q0,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:S}),!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(ev,{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:()=>A(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:()=>k("checkpoint"),disabled:N,title:N?"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:()=>k("stash"),disabled:N,title:N?"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:()=>k("stash_pop"),disabled:N||!(a!=null&&a.stashCount),title:N?"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:()=>k("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 B=tv((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(B),A("Copied to clipboard"),setTimeout(()=>A(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),f&&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:[f==="checkpoint"&&"Create checkpoint commit",f==="stash"&&"Stash changes",f==="stash_pop"&&"Restore latest stash?",f==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(f==="checkpoint"||f==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:w,onChange:B=>b(B.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:p,onChange:B=>g(B.target.checked)}),"Include untracked files"]})]}),M&&s.jsx("p",{className:"text-xs text-red-400",children:M}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:K,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||(f==="checkpoint"||f==="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 sv({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),[f,x]=i.useState(!1),[w,b]=i.useState("quickstart"),[p,g]=i.useState("workspace"),y=i.useMemo(()=>!t&&!e,[t,e]),h=i.useCallback(S=>{a(S),S&&l(!1)},[]),M=i.useCallback(S=>{l(S),S&&a(!1)},[]),j=i.useCallback(()=>{b(r===0?"quickstart":"shortcuts"),g("workspace"),d(!0),a(!1),l(!1)},[r]),v=i.useCallback(()=>{d(!1)},[]),A=i.useCallback(()=>{u(!0)},[]),T=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!y){x(!1);return}x(!0);const S=window.setTimeout(()=>{x(!1)},1e4);return()=>window.clearTimeout(S)},[y]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:f,guideTab:w,shortcutSection:p,isDesktopDashboard:y,setGuideTab:b,setShortcutSection:g,handleInboxOpenChange:h,handleHiddenOpenChange:M,handleOpenShortcutHelp:j,closeShortcutHelp:v,openNewSession:A,closeNewSession:T}}function rv(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 nv(e){return e instanceof Error?e.message:String(e||"")}function av(e){const t=nv(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ov({showMobileChatMode:e,isMobile:t,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:l,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:f,ides:x,actionLogs:w,sendDaemonCommand:b,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:y,initialDataLoaded:h,userName:M,requestedMobileTabKey:j,onRequestedMobileTabConsumed:v,requestedMachineId:A,onRequestedMachineConsumed:T,requestedMobileSection:S,onRequestedMobileSectionConsumed:k,containerRef:K,isSplitMode:L,numGroups:N,groupSizes:P,groupedConvs:B,clearedTabs:D,focusedGroup:C,focusGroup:I,moveTabToGroup:E,splitTabRelative:R,closeGroup:$,handleResizeStart:z,groupActiveTabIds:F,setGroupActiveTab:me,groupTabOrders:ie,setGroupTabOrder:ee,toggleHiddenTab:ce,visibleConversations:je,requestedDesktopTabKey:Ne,onRequestedDesktopTabConsumed:q,onDesktopActiveTabChange:ge,onRequestScrollToBottom:he,onHideConversation:we,onShowHiddenConversation:xe,onShowAllHiddenConversations:Se,scrollToBottomRequest:J,machineEntries:fe,layoutProfile:ae,onBrowseMachineDirectory:ue,onSaveMachineWorkspace:oe,onLaunchMachineIde:de,onLaunchMachineProvider:Q,onListMachineMeshes:ve,onLaunchMeshCoordinator:le,onListMachineSavedSessions:pe,notifications:ne,notificationUnreadCount:Ie,liveSessionInboxState:Ce,onMarkNotificationRead:_e,onMarkNotificationUnread:H,onDeleteNotification:Me}){const Ae=St.useRef(null),{inboxOpen:Ke,hiddenOpen:Ve,shortcutHelpOpen:Xe,newSessionOpen:Ye,guideNudgeVisible:tt,guideTab:ct,shortcutSection:mt,isDesktopDashboard:pt,setGuideTab:O,setShortcutSection:be,handleInboxOpenChange:Te,handleHiddenOpenChange:Be,handleOpenShortcutHelp:qe,closeShortcutHelp:V,openNewSession:U,closeNewSession:X}=sv({isMobile:t,showMobileChatMode:e,visibleConversationCount:je.length}),[se,W]=St.useState(null),[G,te]=St.useState(null),re=St.useCallback((_,Y)=>{W({daemonId:_,workspace:Y})},[]),ke=St.useCallback(_=>{te(_)},[]),Ee=St.useCallback(_=>{var Y;Sr.flushSync(()=>{xe(_)}),(Y=Ae.current)==null||Y.restoreHiddenTabToSavedLocation(_.tabKey)},[xe]),Oe=St.useCallback(_=>{var ye;const Y=u.find(We=>eo(We,_))||f.find(We=>eo(We,_));Y&&(f.some(We=>We.tabKey===Y.tabKey)&&Ee(Y),ge(Y.tabKey),(ye=Ae.current)==null||ye.activateConversationTab(Y.tabKey),he(Y.tabKey,"notification-open")),_e(_.id),Te(!1)},[Ee,f,u,ge,_e,he]),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 He;if(!r)return;const Y=(He=r.modalButtons)==null?void 0:He[_];if(!Y)return;const ye=Hs(r);if(!ye)return;const We=Y.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Pe=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(We);try{await b(ye,"resolve_action",{button:Y,action:Pe?"approve":"reject",buttonIndex:_,...fs(r)})}catch(rt){av(rt)||console.error("[Shortcut approval] Failed:",rt)}},[r,b]),{isMac:Ue,actionDefinitions:Le,actionShortcuts:Qe,shortcutListening:et,shortcutListeningDraft:gt,setShortcutListening:yt,setShortcutListeningDraft:dt,saveShortcuts:ht}=uy({enabled:pt&&!Xe,onTrigger:_=>{var Y,ye,We,Pe,He,rt,Mt,xt,Zt,Er,$r,Br,Or,Fr,Wr,Kr;if(_==="openShortcutHelp"){qe();return}if(_==="openNewSession"){U();return}if(_==="hideCurrentTab"){r&&we(r);return}if(_==="toggleHiddenTabs"){Be(!Ve);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"){(Pe=Ae.current)==null||Pe.popoutActiveTab();return}if(_==="dockActiveTab"){(He=Ae.current)==null||He.dockActiveTab();return}if(_==="focusLeftPane"){(rt=Ae.current)==null||rt.focusLeftPane();return}if(_==="focusRightPane"){(Mt=Ae.current)==null||Mt.focusRightPane();return}if(_==="focusUpPane"){(xt=Ae.current)==null||xt.focusUpPane();return}if(_==="focusDownPane"){(Zt=Ae.current)==null||Zt.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"){(Kr=Ae.current)==null||Kr.activateNextTabInGroup();return}!r||!at(r)||st(r)||_==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),Ge=St.useCallback(()=>{V(),yt(null),dt([])},[V,yt,dt]),Wt=St.useMemo(()=>mt==="all"?Le:Le.filter(_=>rv(_)===mt),[Le,mt]),Z=St.useCallback(()=>{const _=Object.fromEntries(Le.map(Y=>[Y.id,""]));ht(_)},[Le,ht]),$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]));ht(_)},[Le,ht]);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(),Ge())};return window.addEventListener("keydown",_,!0),()=>window.removeEventListener("keydown",_,!0)},[Ge,Xe,et]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(cx,{activeConv:r,wsStatus:n,isConnected:a,conversations:je,hiddenConversations:f,onOpenHistory:o,onHideConversation:we,onShowConversation:Ee,onShowAllHidden:Se,onResetPanelsToMain:Re,notifications:ne,notificationUnreadCount:Ie,onOpenNotification:Oe,onMarkNotificationRead:_e,onMarkNotificationUnread:H,onDeleteNotification:Me,inboxOpen:Ke,onInboxOpenChange:Te,hiddenOpen:Ve,onHiddenOpenChange:Be,onOpenNewSession:t?void 0:U,onOpenDashboardGuide:qe,guideNudgeVisible:tt,actionShortcuts:Qe,onOpenRemote:()=>{!r||at(r)||st(r)||l(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:re,onOpenMeshGraph:ke}),e?s.jsx(Zg,{conversations:u,hiddenConversations:f,ides:x,actionLogs:w,sendDaemonCommand:b,setActionLogs:p,setCliViewModeOverrides:g,isStandalone:y,userName:M,requestedActiveTabKey:j,onRequestedActiveTabConsumed:v,requestedMachineId:A,onRequestedMachineConsumed:T,requestedMobileSection:S,onRequestedMobileSectionConsumed:k,onOpenHistory:o,onOpenRemote:l,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Se,onHideConversation:we,onOpenMeshGraph:ke,onOpenNewSession:U,liveSessionInboxState:Ce}):t?s.jsx(iy,{containerRef:K,isSplitMode:L,numGroups:N,groupSizes:P,groupedConvs:B,clearedTabs:D,ides:x,actionLogs:w,sendDaemonCommand:b,setActionLogs:p,isStandalone:y,hasRegisteredMachines:fe.length>0,userName:M,focusedGroup:C,focusGroup:I,moveTabToGroup:E,splitTabRelative:R,closeGroup:$,handleResizeStart:z,groupActiveTabIds:F,setGroupActiveTab:me,groupTabOrders:ie,setGroupTabOrder:ee,toggleHiddenTab:ce,onOpenNewSession:U,allowTabShortcuts:!1,liveSessionInboxState:Ce}):s.jsx(Ny,{visibleConversations:je,clearedTabs:D,ides:x,actionLogs:w,sendDaemonCommand:b,setActionLogs:p,isStandalone:y,hasRegisteredMachines:fe.length>0,initialDataLoaded:h,userName:M,toggleHiddenTab:ce,actionShortcuts:Qe,registerActionHandlers:_=>{Ae.current=_},onActiveTabChange:ge,requestedActiveTabKey:Ne,onRequestedActiveTabConsumed:q,onRequestScrollToBottom:he,scrollToBottomRequest:J,onOpenNewSession:U,liveSessionInboxState:Ce,layoutProfile:ae}),Ye&&s.jsx(Ty,{machines:fe,ides:x,onClose:X,onBrowseDirectory:ue,onSaveWorkspace:oe,onLaunchIde:de,onLaunchProvider:Q,onListMeshes:ve,onLaunchMeshCoordinator:le,onListSavedSessions:pe}),G&&s.jsx(O0,{activeConv:G,sendDaemonCommand:b,onClose:()=>te(null)}),se&&s.jsx(gu,{daemonId:se.daemonId,workspace:se.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:Ge,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:Ge,"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:Z,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:Wt.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...":Qe[_.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={...Qe};Y[_.id]="",ht(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 La=[{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=La[t],a=t===La.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:La.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:`
|
|
67
|
+
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
68
|
+
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
69
|
+
`})]})}function lv({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 cv({ideData:e,allIdes:t,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,l]=i.useState(()=>a||"native"),c=i.useMemo(()=>rd(t),[t]),d=i.useMemo(()=>e?Uo(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=i.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),f=i.useMemo(()=>e?Ft(d,e.id):null,[d,e]);i.useEffect(()=>{a&&l(a)},[a]),i.useEffect(()=>{if(a||!f)return;const p=f.streamSource==="native"?"native":f.tabKey;!p||o===p||o==="native"&&l(p)},[o,f,a]),i.useEffect(()=>{var p;o!=="native"&&(u.some(g=>g.tabKey===o)||l(((p=u[0])==null?void 0:p.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(m||u[0]&&l(u[0].tabKey))},[o,m,u]);const x=i.useMemo(()=>o==="native"&&m?m:u.find(p=>p.tabKey===o)||f||m||u[0],[o,m,f,u]),w=i.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:Xc(p)||n,status:p.status})),[u,n]),b=i.useCallback(p=>{if(p)return d.find(g=>eo(g,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:o,setActiveChatTab:l,activeConv:x,conversations:d,extensionTabs:w,hasExtensions:w.length>0,resolveConversationByTarget:b}}function dv({activeConv:e,ideEntry:t,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:l,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:f}){const[x,w]=i.useState("split"),[b,p]=i.useState(()=>os(e)?"native":e.tabKey),g=i.useRef(null),y=i.useMemo(()=>t||r.find(I=>I.id===e.routeId),[e.routeId,t,r]),h=i.useMemo(()=>lt((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:M,extensionTabs:j,hasExtensions:v}=cv({ideData:y,allIdes:r,connectionStates:n,ideName:h||"IDE",preferredTabKey:os(e)?void 0:e.tabKey}),A=i.useMemo(()=>y?Ft(M,y.id):null,[y,M]);i.useEffect(()=>{const I=g.current,E={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(g.current=E,!(I&&I.routeId===E.routeId&&I.tabKey===E.tabKey&&I.streamSource===E.streamSource)){if(os(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(b==="native"){if(M.some(I=>I.streamSource==="native"))return;(A==null?void 0:A.streamSource)==="agent-stream"&&p(A.tabKey);return}if(!M.some(I=>I.tabKey===b)){if((A==null?void 0:A.streamSource)==="agent-stream"){p(A.tabKey);return}p("native")}},[M,b,A]);const T=i.useMemo(()=>b==="native"?M.find(I=>I.streamSource==="native")||e:M.find(I=>I.tabKey===b)||e,[e,M,b]),S=xd(T),k=i.useMemo(()=>S.status||S.modalMessage||S.modalButtons?{...T,...S.status?{status:S.status}:{},...S.modalMessage!==void 0?{modalMessage:S.modalMessage}:{},...S.modalButtons!==void 0?{modalButtons:S.modalButtons}:{}}:T,[T,S]),K=Lr(k),L=Hn({sendDaemonCommand:o,activeConv:k,setActionLogs:l,isStandalone:c}),{connScreenshot:N,screenshotUsage:P,handleRemoteAction:B}=Vd({doId:K,targetSessionId:Rc(k),connState:k.connectionState||"new",viewMode:x}),D=i.useMemo(()=>a.filter(I=>I.routeId===k.tabKey),[a,k.tabKey]);i.useEffect(()=>{u==null||u(k)},[k,u]),i.useEffect(()=>{const I=E=>{E.key==="Escape"&&f()};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[f]);const C=i.useCallback(I=>{I.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:f,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:C,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(_t,{size:16})}),s.jsx("span",{className:"truncate",children:Lo(T)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:f,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(I=>{const E=x===I;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${E?"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(I),title:I==="split"?"Split view":"Remote only",children:I==="split"?s.jsx(Fm,{size:15}):s.jsx(_t,{size:15})},I)})}),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(vo,{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:f,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${x==="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:[x!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${x==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(lv,{hasExtensions:v,ideName:h||"IDE",activeChatTab:b,extensionTabs:j,onSelectTab:p}),s.jsx(yc,{activeConv:k,onModalButton:L.handleModalButton}),s.jsx(so,{activeConv:k,ideEntry:y,showMetaChips:!1,handleSendChat:L.handleSendChat,isSendingChat:L.isSendingChat,sendFeedbackMessage:L.sendFeedbackMessage,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:D,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${x==="split"?"order-1 md:order-2":""}`,children:s.jsx(bc,{addLog:()=>{},connState:k.connectionState||"new",connScreenshot:N,screenshotUsage:P,transportType:k.transport,onAction:B})})]})]})})}function uv({activeConv:e,canSaveAndStop:t=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=Qh(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 mv({historyModal:e,remoteDialog:t,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var l;return s.jsxs(s.Fragment,{children:[s.jsx(rx,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&s.jsx(Ho,{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(dv,{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(uv,{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(sd,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&s.jsx(iv,{onClose:o.onClose})]})}function pv({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=Tt(l,{fallbackId:l.id}),d=n[l.id],m=l.version||l.daemonVersion||"unknown",u=l.versionUpdateRequired===!0,x=Td(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:x})]},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 fv(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function hv(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 xv(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>hv(t)).map(t=>t.id)}}function bv(){var pi,fi,hi,xi;const{sendCommand:e}=kt(),t=Rr(),r=hd(),n=bo(),a=qs(),[o,l]=om(),c=o.get("activeTab"),d=((pi=n.state)==null?void 0:pi.openRemoteForTabKey)||null,m=((fi=n.state)==null?void 0:fi.openMachineId)||null,u=((hi=n.state)==null?void 0:hi.mobileSection)||null,f=Vc(),x=f.ides||[],w=f.initialLoaded??!0,{updateRouteChats:b,setToasts:p}=f,[g,y]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),h=f.toasts||[],M=f.wsStatus||"connected",j=f.isConnected??!0,v=f.connectionStates||{},A=f.showReconnected||!1,{layoutProfile:T,groupAssignments:S,updateGroupAssignments:k,focusedGroup:K,updateFocusedGroup:L,focusGroup:N,groupActiveTabIds:P,updateGroupActiveTabIds:B,setGroupActiveTab:D,groupTabOrders:C,updateGroupTabOrders:I,setGroupTabOrder:E,groupSizes:R,updateGroupSizes:$,isMobile:z,hasHydratedStoredLayout:F,hydrateStoredLayout:me,focusConversationTab:ie}=qb(),[ee,ce]=i.useState(()=>Go());i.useEffect(()=>ob(ce),[]);const je=i.useMemo(()=>fv({isMobile:z,mobileViewMode:ee}),[z,ee]),[Ne,q]=i.useState([]),[ge,he]=i.useState({}),[we,xe]=i.useState({});_r("Dashboard",{ideCount:x.length,toastCount:h.length,focusedGroup:K,groupCount:Object.keys(S).length,actionLogCount:Ne.length});const Se=i.useMemo(()=>x.filter(Je=>Je.type==="adhdev-daemon").sort(Ao),[x]),J=Se[0],fe=!!J;i.useEffect(()=>{const{metadataDaemonIds:Je,runtimeDaemonIds:Et}=xv(Se);for(const Zs of Je)t(Zs,{minFreshMs:3e4}).catch(()=>{});for(const Zs of Et)r(Zs,{minFreshMs:3e4}).catch(()=>{})},[t,r,Se]);const ae=(J==null?void 0:J.terminalBackend)||null,ue=J?Tt(J,{fallbackId:J.id}):null,oe=(J==null?void 0:J.id)||null,de=i.useMemo(()=>vb(x,ge),[x,ge]),{hiddenTabs:Q,autoHiddenTabs:ve,autoHideTarget:le,hideTarget:pe,toggleTarget:ne,showTarget:Ie,showAllTabs:Ce}=yb(),{conversations:_e,visibleConversations:H,visibleTabKeys:Me,resolveConversationBySessionId:Ae,resolveConversationByTarget:Ke}=Rb({ides:de,connectionStates:v,clearedTabs:we,hiddenTabs:Q}),Ve=i.useMemo(()=>new Map(_e.map(Je=>[Je.tabKey,Je])),[_e]),Xe=i.useMemo(()=>gb(_e,Q,ve),[_e,Q,ve]);i.useEffect(()=>{for(const Je of Xe)le(Je)},[Xe,le]),Ah(H,je),i.useEffect(()=>{Object.keys(ge).length!==0&&he(Je=>wb(Je,x))},[x,ge]);const Ye=i.useMemo(()=>Ep(x),[x]),{notifications:tt,unreadCount:ct}=dg({conversations:_e,liveSessionInboxState:Ye}),{handleMarkDashboardNotificationRead:mt,handleMarkDashboardNotificationUnread:pt,handleDeleteDashboardNotification:O}=ug({notifications:tt,sendDaemonCommand:e}),{containerRef:be,normalizedGroupAssignments:Te,numGroups:Be,isSplitMode:qe,groupedConvs:V,moveTabToGroup:U,closeGroup:X,handleResizeStart:se,splitTabRelative:W}=tg({groupAssignments:S,updateGroupAssignments:k,updateFocusedGroup:L,updateGroupActiveTabIds:B,updateGroupTabOrders:I,groupSizes:R,updateGroupSizes:$,isMobile:z,visibleConversations:H,visibleTabKeys:Me}),{activeConv:G,openDesktopConversation:te,requestScrollToBottom:re,scrollToBottomRequest:ke,setDesktopActiveTab:Ee}=Ng({isMobile:z,conversations:_e,visibleConversations:H,groupActiveTabIds:P,focusedGroup:K,groupedConvs:V,setSearchParams:l});Mg({activeConv:G,isMobile:z,liveSessionInboxState:Ye,sendDaemonCommand:e});const{requestedDesktopTabKey:Oe,requestedMobileTabKey:Re,consumeRequestedActiveTab:Fe}=Pb({isMobile:z,urlActiveTab:c,resolveConversationBySessionId:Ae,setSearchParams:l}),{remoteDialogConv:Ue,remoteDialogIdeEntry:Le,remoteDialogActiveConv:Qe,setRemoteDialogActiveConv:et,openRemoteDialog:gt,closeRemoteDialog:yt,cliStopDialogOpen:dt,cliStopTargetConv:ht,requestCliStop:Ge,cancelCliStop:Wt,confirmCliStop:Z}=_g({isMobile:z,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Oe,conversations:_e,ides:x,resolveConversationByTarget:Ke,activeConv:G,sendDaemonCommand:e}),{historyModalOpen:$e,openHistoryModal:_,closeHistoryModal:Y,historyTargetConv:ye,isSavedSessionHistoryTarget:We,isHistoryCreatingChat:Pe,isHistoryRefreshingHistory:He,handleHistorySwitchSession:rt,handleHistoryNewChat:Mt,handleHistoryRefresh:xt,savedHistorySessions:Zt,savedHistoryFilters:Er,setSavedHistoryFilters:$r,missingWorkspaceResumePath:Br,isSavedHistoryLoading:Or,resumingSavedHistorySessionId:Fr,handleRefreshSavedHistory:Wr,handleResumeSavedHistorySession:Kr}=Ag({activeConv:G,remoteDialogConv:Ue,remoteDialogActiveConv:Qe,ides:x,sendDaemonCommand:e,updateRouteChats:b,setToasts:p,setClearedTabs:xe,setSearchParams:l}),ku=i.useMemo(()=>H,[H]),Hr=z&&ee==="chat",Su=i.useMemo(()=>_e.filter(Je=>zn(Q,Je)),[_e,Q]),di=i.useCallback(Je=>{const Et=new URLSearchParams(o);Et.set("activeTab",Je),l(Et,{replace:!0})},[o,l]),{trackPendingLaunch:Nu}=wg({ides:x,conversations:_e,onOpenSession:di}),{handleBrowseMachineDirectory:Cu,handleSaveMachineWorkspace:Iu,handleLaunchMachineIde:Mu,handleLaunchMachineProvider:Au,handleListMachineMeshes:Tu,handleLaunchMeshCoordinator:_u,handleListMachineSavedSessions:Lu,setActiveCliViewMode:Ru}=jg({sendDaemonCommand:e,trackPendingLaunch:Nu,onOpenSession:di,activeConv:G,ides:x,setCliViewModeOverrides:he});jb({visibleConversations:H,clearedTabs:we,setClearedTabs:xe,setActionLogs:q}),Db({ides:x,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Ke});const{isRefreshingHistory:Pu,handleRefreshHistory:Du}=Ad({sendDaemonCommand:e,activeConv:G,chats:(xi=x.find(Je=>Je.id===(G==null?void 0:G.routeId)))==null?void 0:xi.chats,updateRouteChats:b,setToasts:p,setClearedTabs:xe});Xb({urlActiveTab:z&&!Hr?c:null,conversations:_e,resolveConversationBySessionId:Ae,normalizedGroupAssignments:Te,hasHydratedStoredLayout:z&&!Hr?F:!0,hydrateStoredLayout:z&&!Hr?me:()=>{},focusConversationTab:ie,setSearchParams:l,historyModalOpen:$e,activeConv:G,isRefreshingHistory:Pu,ides:x,handleRefreshHistory:Du});const Eu=i.useMemo(()=>!G||!at(G)||st(G)?null:Xs(G),[G]),{versionMismatchDaemons:$u,hasRequiredVersionDaemons:ui,targetVersion:Bu,versionBannerDismissed:Ou,setVersionBannerDismissed:Fu,upgradingDaemons:Wu,handleBannerUpgrade:Ku}=rg({ides:x,sendDaemonCommand:e}),mi=i.useCallback(Je=>{Ie(Je),te(Je)},[te,Ie]),Hu=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(nx,{terminalBackend:ae,isStandalone:fe,machineLabel:ue,machineKey:oe}),(!Ou||ui)&&s.jsx(pv,{daemons:$u,targetVersion:Bu,required:ui,upgradingDaemons:Wu,onUpgrade:Ku,onDismiss:()=>Fu(!0)}),s.jsx(ov,{showMobileChatMode:Hr,isMobile:z,activeConv:G,wsStatus:M,isConnected:j,onOpenHistory:Je=>{Je&&et(Je),_()},onOpenRemote:gt,onStopCli:Ge,activeCliViewMode:Eu,onSetActiveCliViewMode:Ru,mobileChatConversations:ku,ides:x,actionLogs:Ne,sendDaemonCommand:e,setActionLogs:q,setCliViewModeOverrides:he,isStandalone:fe,initialDataLoaded:w,userName:f.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:R,groupedConvs:V,clearedTabs:we,focusedGroup:K,focusGroup:N,moveTabToGroup:U,splitTabRelative:W,closeGroup:X,handleResizeStart:se,groupActiveTabIds:P,setGroupActiveTab:D,groupTabOrders:C,setGroupTabOrder:E,toggleHiddenTab:Je=>ne(Ve.get(Je)||{tabKey:Je}),visibleConversations:H,hiddenConversations:Su,requestedDesktopTabKey:Oe,onRequestedDesktopTabConsumed:Fe,onDesktopActiveTabChange:Ee,onRequestScrollToBottom:re,onHideConversation:Hu,onShowHiddenConversation:mi,onShowAllHiddenConversations:Ce,scrollToBottomRequest:ke,machineEntries:Se,layoutProfile:T,onBrowseMachineDirectory:Cu,onSaveMachineWorkspace:Iu,onLaunchMachineIde:Mu,onLaunchMachineProvider:Au,onListMachineMeshes:Tu,onLaunchMeshCoordinator:_u,onListMachineSavedSessions:Lu,notifications:tt,notificationUnreadCount:ct,liveSessionInboxState:Ye,onMarkNotificationRead:mt,onMarkNotificationUnread:pt,onDeleteNotification:O}),s.jsx("style",{children:`
|
|
70
|
+
body { overflow: hidden; overscroll-behavior: none; }
|
|
71
|
+
`}),s.jsx(mv,{historyModal:{open:$e,targetConv:ye,ides:x,isCreatingChat:Pe,isRefreshingHistory:We?!1:He,savedSessions:Zt,savedHistoryFilters:Er,missingWorkspaceResumePath:Br||null,onSavedHistoryFiltersChange:$r,isSavedSessionsLoading:Or,isResumingSavedSessionId:Fr,onClose:Y,onNewChat:Mt,onSwitchSession:rt,onRefreshHistory:We?Wr:xt,onResumeSavedSession:Kr},remoteDialog:{conversation:Ue,ideEntry:Le,ides:x,connectionStates:v,actionLogs:Ne,sendDaemonCommand:e,setActionLogs:q,isStandalone:fe,userName:f.userName,onOpenHistory:Je=>{Je&&et(Je),_()},onConversationChange:et,onClose:yt},cliStopDialog:{open:dt,targetConv:ht,onCancel:Wt,onStopNow:async()=>{await Z("hard")},onSaveAndStop:async()=>{await Z("save")}},connectionBanner:{wsStatus:M,showReconnected:A,loginUrl:f.connectionLoginUrl,onReconnect:f.retryServerConnection},toastOverlay:{toasts:h,onDismiss:Je=>p(Et=>Et.filter(Zs=>Zs.id!==Je)),onClick:Je=>{if(Je.targetKey){const Et=Ke(Je.targetKey);Et&&(ie(Et.tabKey,Te),mi(Et),re(Et.tabKey,"toast-open"))}}},onboarding:{open:g,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}}})]})}function gv({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),[f,x]=i.useState(!1),[w,b]=i.useState(null),[p,g]=i.useState(!1),[y,h]=i.useState(""),M=i.useRef(null),j=i.useCallback(R=>{M.current=R},[]),v=i.useCallback((R,$,z=!1)=>{l(F=>[...F.slice(-100),{timestamp:Date.now(),level:R,message:$}]),setTimeout(()=>{var F;return(F=a.current)==null?void 0:F.scrollIntoView({behavior:"smooth"})},100),z&&ot.showToast($,R==="error"||R==="warn"?"warning":"success")},[a]),A=i.useCallback(R=>{const $=R instanceof Error?R.message:String(R||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),T=i.useCallback(async(R,$)=>{var z;if(!e||c)return!1;d(R),v("info",`Launching ${lt(R)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const F={ideType:R,enableCdp:!0};(z=$==null?void 0:$.workspace)!=null&&z.trim()?F.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(F.useDefaultWorkspace=!0);const me=await r(e,"launch_ide",F);return v(me!=null&&me.success?"info":"error",me!=null&&me.success?`${lt(R)} launched`:`Failed: ${me==null?void 0:me.error}`,!0),!!(me!=null&&me.success)}catch(F){return v("error",`Launch error: ${F.message}`,!0),!1}finally{d(null)}},[e,c,v,r]),S=i.useCallback(async R=>{if(!e)return{success:!1};const{cliType:$,dir:z,workspaceId:F,useDefaultWorkspace:me,useHome:ie,argsStr:ee,model:ce,resumeSessionId:je}=R;if(!$)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const Ne=ee?ee.split(/\s+/).filter(Boolean):void 0,q=(z==null?void 0:z.trim())||(F?"(saved id)":me?"(default workspace)":ie?"(home)":"");v("info",`Launching ${$}${q?` in ${q}`:""}${ce?` (model: ${ce})`:""}...`),u($);try{const ge={cliType:$,cliArgs:Ne,initialModel:ce||void 0};z!=null&&z.trim()?ge.dir=z.trim():F?ge.workspaceId=F:me?ge.useDefaultWorkspace=!0:ie&&(ge.useHome=!0),je&&(ge.resumeSessionId=je);const he=await r(e,"launch_cli",ge),we=(he==null?void 0:he.result)||he;return he!=null&&he.success?(v("info",`${$} 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: ${(he==null?void 0:he.error)||(we==null?void 0:we.error)}`,!0),(he==null?void 0:he.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&b({cliType:$,argsStr:ee,model:ce}),{success:!1,sessionId:we==null?void 0:we.sessionId})}catch(ge){return A(ge)?(v("warn",`${$} 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,A,r]),k=i.useCallback(async(R,$,z,F)=>e?R?$.trim()?S({cliType:R,dir:$,argsStr:z,model:F}):(b({cliType:R,argsStr:z,model:F}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,S]),K=i.useCallback(async(R,$,z)=>{if(e&&window.confirm(`Stop ${R}?
|
|
72
|
+
This will terminate the process.`))try{const F=await r(e,"stop_cli",{cliType:R,dir:$,targetSessionId:z});F!=null&&F.success?v("info",`${R} stopped`,!0):v("error",`Stop failed: ${(F==null?void 0:F.error)||"Unknown error"}`,!0)}catch(F){v("error",`Stop failed: ${F.message}`,!0)}},[e,v,r]),L=i.useCallback(async R=>{try{await r(R.daemonId,"restart_ide",{ideType:R.type}),v("info",`${lt(R.type)} restart initiated`,!0)}catch($){v("error",`Restart failed: ${$.message}`,!0)}},[v,r]),N=i.useCallback(async R=>{if(window.confirm(`Stop ${lt(R.type)}?
|
|
73
|
+
This will disconnect CDP and optionally kill the process.`))try{const $=await r(R.daemonId,"stop_ide",{ideType:R.type,killProcess:!0});$!=null&&$.success?v("info",`${lt(R.type)} stopped`,!0):v("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){v("error",`Stop failed: ${$.message}`,!0)}},[v,r]),P=i.useCallback(async()=>{if(e)try{const R=await r(e,"detect_ides",{});v("info",`Found ${((R==null?void 0:R.result)||[]).length} IDE(s)`,!0)}catch(R){v("error",`Detection failed: ${R.message}`,!0)}},[e,v,r]),B=i.useCallback(async R=>{if(!e||!R.trim())return!1;x(!0);try{const $=await r(e,"workspace_add",{path:R.trim()});return $!=null&&$.success?(v("info",`Workspace added: ${R.trim()}`),!0):(v("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return v("error",$.message),!1}finally{x(!1)}},[e,v,r]),D=i.useCallback(async R=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const $=await r(e,"workspace_remove",{id:R});$!=null&&$.success?v("info","Workspace removed",!0):v("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){v("error",$.message,!0)}finally{x(!1)}}},[e,v,r]),C=i.useCallback(async R=>{var $;if(e){x(!0);try{const z=await r(e,"workspace_set_default",R===null?{clear:!0}:{id:R});if(z!=null&&z.success){v("info",R?"Default workspace updated":"Default workspace cleared",!0);const F=typeof z.defaultWorkspacePath=="string"?z.defaultWorkspacePath:"";F&&(($=M.current)==null||$.call(M,F))}else v("error",(z==null?void 0:z.error)||"workspace_set_default failed",!0)}catch(z){v("error",z.message,!0)}finally{x(!1)}}},[e,v,r]),I=i.useCallback(async R=>{var z;if(!e||!R.trim())return;const $=R.trim();x(!0);try{const F=await r(e,"workspace_set_default",{path:$});F!=null&&F.success?(v("info","Default workspace set from history"),(z=M.current)==null||z.call(M,$)):v("error",(F==null?void 0:F.error)||"Could not set default (path missing on disk?)")}catch(F){v("error",F.message)}finally{x(!1)}},[e,v,r]),E=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(R){v("warn",`Live nickname updated, but account sync failed: ${R.message}`)}v("info",`Nickname set to "${y||"(cleared)"}"`),g(!1)}catch(R){v("error",`Failed: ${R.message}`)}},[e,y,t,v,n,r]);return{logs:o,launchingIde:c,launchingAgentType:m,workspaceBusy:f,launchPick:w,setLaunchPick:b,editingNickname:p,setEditingNickname:g,nicknameInput:y,setNicknameInput:h,addLog:v,handleLaunchIde:T,runLaunchCliCore:S,handleLaunchCli:k,handleStopCli:K,handleRestartIde:L,handleStopIde:N,handleDetectIdes:P,handleWorkspaceAdd:B,handleWorkspaceRemove:D,handleWorkspaceSetDefault:C,handleWorkspaceResumePath:I,handleSaveNickname:E,setOnDefaultWorkspaceChanged:j}}function yv({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,[f,x]=i.useState(!1),[w,b]=i.useState(""),[p,g]=i.useState([]),[y,h]=i.useState(!1),[M,j]=i.useState(""),v=i.useCallback(async N=>{h(!0),j("");try{const P=await qn(l,e,N);b(P.path),g(P.directories)}catch(P){j(P instanceof Error?P.message:"Could not load folder")}finally{h(!1)}},[e,l]),A=i.useCallback(()=>{x(!0);const N=[...r.map(B=>B.workspace),...n.map(B=>B.workspace),...a.map(B=>B.workspace)],P=Gn(t.platform,Vn(N,t.defaultWorkspacePath,(t.workspaces||[]).map(B=>B.path)));v(P)},[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,S=t.availableMem??t.freeMem??t.totalMem,k=T&&t.totalMem>0?Math.min(100,Math.max(0,Math.round((t.totalMem-S)/t.totalMem*100))):0,K=((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(lc,{size:16}),label:"Uptime",value:typeof t.uptime=="number"?Kp(t.uptime):"Waiting…"}),s.jsx(zr,{icon:s.jsx(_t,{size:16}),label:"IDEs",value:`${r.length}`}),s.jsx(zr,{icon:s.jsx(jo,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(zr,{icon:s.jsx(Km,{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(Li,{value:T?Math.min(Math.round(K/t.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:T?`${K.toFixed(2)} avg / ${t.cpus} cores`:"Polled from machine page"}),s.jsx(Li,{value:k,max:100,label:"Memory",color:"#3b82f6",detail:T?`${aa(t.totalMem-S)} / ${aa(t.totalMem)}${t.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${aa(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(ks,{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:N=>void u(N.target.value===""?null:N.target.value),children:[s.jsx("option",{value:"",children:"(none)"}),(t.workspaces||[]).map(N=>s.jsx("option",{value:N.id,children:N.label||N.path},N.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:A,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(N=>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:[N.id===t.defaultWorkspaceId&&s.jsx("span",{className:"text-[10px]",children:"⭐"}),s.jsx("span",{className:"font-medium text-text-primary truncate",children:Wn(N.path,N.label)})]}),s.jsx("div",{className:"font-mono truncate text-[10px]",title:N.path,children:N.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(N.id),children:"Remove"})]},N.id))})]}),f&&s.jsx(Yn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:p,busy:y,error:M,confirmLabel:"Add workspace",onClose:()=>x(!1),onNavigate:N=>{v(N)},onConfirm:N=>{(async()=>{if(!N)return;await d(N)&&x(!1)})()}})]})}function vv(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 Ra(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 Dl(e){if(!e||typeof e!="object")return null;if(Ra(e))return e;const t=e,r=t.result;return Ra(r)?r:Ra(t.sourceConfig)?t.sourceConfig:null}function jv(e){const t=e.trim();return t||null}const El=["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 Sv({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,f]=i.useState(""),[x,w]=i.useState([]),[b,p]=i.useState(""),g=i.useRef(null),y=i.useRef(null),h=S=>{m(k=>k.includes(S)?k.filter(K=>K!==S):[...k,S])},M=()=>m([...El]),j=()=>m([]);i.useEffect(()=>{var S;(S=g.current)==null||S.scrollIntoView({behavior:"smooth"})},[x]),i.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const v=i.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const S=await r(e,"provider_auto_fix_status",{providerType:t.type});(S==null?void 0:S.running)===!1&&a==="running"&&(o("done"),w(k=>[...k,`
|
|
74
|
+
✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,t.type,r,a]),A=async()=>{if(d.length!==0){o("running"),w(["🚀 Starting auto-fix...",`Agent: ${l}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),p("");try{const S=await r(e,"provider_auto_fix",{providerType:t.type,functions:d,agent:l,...u?{comment:u}:{}});S!=null&&S.success&&(S!=null&&S.started||S!=null&&S.running)?(w(k=>[...k,"✅ Agent started. Monitoring progress..."]),v()):(o("error"),p((S==null?void 0:S.error)||"Failed to start auto-fix"))}catch(S){o("error"),p((S==null?void 0:S.message)||"Connection failed")}}},T=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:t.type}),w(S=>[...S,`
|
|
75
|
+
⚠️ 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:S=>S.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(S=>s.jsxs("button",{onClick:()=>c(S.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:l===S.value?S.color+"66":"var(--border-subtle)",background:l===S.value?S.color+"0d":"transparent"},children:[s.jsx("div",{className:"text-[12px] font-semibold",style:{color:l===S.value?S.color:"var(--text-primary)"},children:S.label}),s.jsx("div",{className:"text-[10px] text-text-muted",children:S.desc})]},S.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:M,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:j,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:El.map(S=>s.jsxs("button",{onClick:()=>h(S),className:"px-2.5 py-1.5 rounded-md border text-[11px] font-medium text-left transition-all",style:{borderColor:d.includes(S)?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:d.includes(S)?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent",color:d.includes(S)?"#a78bfa":"var(--text-secondary)"},children:[d.includes(S)?"☑ ":"☐ ",S]},S))})]}),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:S=>f(S.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:[x.map((S,k)=>s.jsx("div",{className:S.startsWith("✅")?"text-green-400":"",style:S.startsWith("❌")||S.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:S},k)),a==="running"&&s.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),s.jsx("div",{ref:g})]}),b&&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:b})]})]}),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:A,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&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([]),p("")},className:"machine-btn",children:"← Back"}),s.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function Nv({machineId:e,providers:t,sendDaemonCommand:r,onClose:n,onCreated:a}){var v;const o=t.filter(A=>A.category==="ide"),[l,c]=i.useState(((v=o[0])==null?void 0:v.type)||""),[d,m]=i.useState(""),[u,f]=i.useState(""),[x,w]=i.useState(!1),[b,p]=i.useState(""),[g,y]=i.useState(!1),h=A=>{const T=A.toLowerCase().replace(/[^a-z0-9-]/g,"");m(T),(!u||u===M(d))&&f(M(T))},M=A=>A.split("-").map(T=>T.charAt(0).toUpperCase()+T.slice(1)).join(" "),j=async()=>{if(!(!d||!u||!l)){w(!0),p("");try{const A=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:l});A!=null&&A.success||A!=null&&A.created?(y(!0),a==null||a(d)):p((A==null?void 0:A.error)||"Failed to create provider")}catch(A){p((A==null?void 0:A.message)||"Connection failed")}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:A=>A.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(A=>s.jsxs("button",{onClick:()=>c(A.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:l===A.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l===A.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:A.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:l===A.type?"#a78bfa":"var(--text-secondary)"},children:A.displayName})]},A.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:A=>h(A.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),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:A=>f(A.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),b&&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:b})]})}),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:j,disabled:!d||!u||x,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||x?.4:1},children:x?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function $l(e){return e==="cli"||e==="acp"}function Cv(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 Iv(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 Bl(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 Mv({machineId:e,providers:t,sendDaemonCommand:r}){var B;const[n,a]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(null),[m,u]=i.useState("all"),[f,x]=i.useState(null),[w,b]=i.useState(!1),[p,g]=i.useState(null),[y,h]=i.useState("normal"),[M,j]=i.useState(""),[v,A]=i.useState(!1),T=i.useCallback(async()=>{if(e)try{const D=await r(e,"get_provider_source_config",{}),C=Dl(D);C&&(g(C),h(C.sourceMode),j(C.explicitProviderDir||""))}catch{}},[e,r]),S=i.useCallback(async()=>{if(e){l(!0);try{const D=await r(e,"get_provider_settings",{}),C=vv(D);if(C){const I=wv(C,t,{filterSchema:E=>E.filter(R=>R.key!=="enabled")});I.sort((E,R)=>E.category.localeCompare(R.category)||E.displayName.localeCompare(R.displayName)),a(I)}}catch{}l(!1)}},[e,t,r]);i.useEffect(()=>{n.length===0&&S(),p||T()},[]);const k=async(D,C,I)=>{d(`${D}.${C}`),a(E=>E.map(R=>R.type===D?{...R,values:{...R.values,[C]:I}}:R));try{const E=await r(e,"set_provider_setting",{providerType:D,key:C,value:I});E!=null&&E.success||S()}catch{S()}d(null)},K=async(D,C)=>{await k(D,"enabled",C),await S()},L=async D=>{d(`${D}.detect`);try{await r(e,"detect_provider",{providerType:D})}finally{await S(),d(null)}},N=async D=>{await k(D,"executablePath",""),await k(D,"executableArgs",""),await S()},P=async()=>{A(!0);try{const D=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:jv(M)}),C=Dl(D);C?(g(C),h(C.sourceMode),j(C.explicitProviderDir||"")):await T(),await S()}catch{await T()}A(!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(D=>s.jsx("button",{onClick:()=>u(D),className:`machine-btn text-[10px] px-2 py-0.5 ${m===D?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:D.toUpperCase()},D))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>b(!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:S,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:D=>h(D.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:M,onChange:D=>j(D.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void P(),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:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((B=p==null?void 0:p.providerRoots)==null?void 0:B.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(D=>D.category===m).length>1&&(()=>{const D=n.filter(R=>R.category===m),C=new Map;for(const R of D)for(const $ of R.schema){if($.type!=="boolean")continue;const z=C.get($.key),F=!!(R.values[$.key]??$.default);z?(z.onCount+=F?1:0,z.total+=1):C.set($.key,{label:$.label||$.key,onCount:F?1:0,total:1})}const I=[...C.entries()].filter(([,R])=>R.total===D.length);if(I.length===0)return null;const E=async(R,$)=>{for(const z of D)await k(z.type,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 (",D.length,")"]}),s.jsx("div",{className:"flex flex-wrap gap-2",children:I.map(([R,$])=>{const z=$.onCount===$.total,F=$.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:$.label}),s.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",$.onCount,"/",$.total,")"]}),s.jsx("button",{onClick:()=>void E(R,!0),disabled:z,className:`machine-btn text-[9px] px-1.5 py-px ${z?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),s.jsx("button",{onClick:()=>void E(R,!1),disabled:F,className:`machine-btn text-[9px] px-1.5 py-px ${F?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},R)})})]})})(),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(D=>m==="all"||D.category===m).map(D=>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:D.icon}),s.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:D.displayName}),s.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:D.category==="acp"?"rgba(139,92,246,0.08)":D.category==="cli"?"rgba(59,130,246,0.08)":D.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:D.category==="acp"?"#a78bfa":D.category==="cli"?"#60a5fa":D.category==="ide"?"#86efac":"var(--status-warning)"},children:D.category}),$l(D.category)&&(()=>{const C=t.find(R=>R.type===D.type),I=(C==null?void 0:C.enabled)===!0||D.values.enabled===!0,E=(C==null?void 0:C.machineStatus)||(I?"enabled_unchecked":"disabled");return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${Iv(E)}`,children:Cv(E)}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[s.jsx("button",{onClick:()=>void K(D.type,!I),disabled:c===`${D.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${I?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:I?"Disable":"Enable"}),s.jsx("button",{onClick:()=>void L(D.type),disabled:!I||c===`${D.type}.detect`,title:I?"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 ${I?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),s.jsx("button",{onClick:()=>void N(D.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),D.category==="ide"&&s.jsx("button",{onClick:()=>x(t.find(C=>C.type===D.type)||{type:D.type,name:D.displayName,displayName:D.displayName,icon:D.icon,category:D.category}),className:"ml-auto machine-btn text-[9px] px-2 py-0.5 bg-violet-500/[0.06] border-violet-500/20 text-violet-400 hover:bg-violet-500/[0.12]",children:"🔧 Auto-Fix"})]}),$l(D.category)&&(()=>{const C=t.find(I=>I.type===D.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:"})," ",Bl(C==null?void 0:C.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Bl(C==null?void 0:C.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:D.schema.map(C=>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:[C.label||C.key,c===`${D.type}.${C.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),C.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:C.description})]}),s.jsx("div",{className:"shrink-0",children:C.type==="boolean"?s.jsx("button",{onClick:()=>k(D.type,C.key,!(D.values[C.key]??C.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:D.values[C.key]??C.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:D.values[C.key]??C.default?21:3}})}):C.type==="number"?s.jsx("input",{type:"number",value:Number(D.values[C.key]??C.default??0)||0,min:C.min,max:C.max,onChange:I=>{const E=parseInt(I.target.value)||0;C.min!==void 0&&E<C.min||C.max!==void 0&&E>C.max||k(D.type,C.key,E)},className:"machine-input w-20 text-center text-[11px]"}):C.type==="select"&&C.options?s.jsx("select",{value:String(D.values[C.key]??C.default??""),onChange:I=>k(D.type,C.key,I.target.value),className:"machine-input text-[11px]",children:C.options.map(I=>s.jsx("option",{value:I,children:I},I))}):s.jsx("input",{type:"text",value:String(D.values[C.key]??C.default??""),onBlur:I=>k(D.type,C.key,I.target.value),className:"machine-input w-[120px] text-[11px]"})})]},C.key))})]},D.type))}),f&&s.jsx(Sv,{machineId:e,provider:f,sendDaemonCommand:r,onClose:()=>x(null)}),w&&s.jsx(Nv,{machineId:e,providers:t,sendDaemonCommand:r,onClose:()=>b(!1),onCreated:()=>{b(!1),S()}})]})}const Av=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function Tv({count:e,since:t,category:r}){return{count:e,since:t,...r==="all"?{}:{category:r}}}function _v(e,t){return t==="all"?e:e.filter(r=>r.category===t)}function Lv(e){return e.trim().toLowerCase()}function Jn(e,t){const r=Lv(t);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function ii(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Gs(e,t=220){const r=ii(e);return r?r.length>t?`${r.slice(0,t)}…`:r:""}function Rv(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 Pv(e,t){return e.filter(r=>Jn([r.level,r.message],t))}function Ol(e){return`${e.timestamp}:${e.level}:${e.message}`}function Dv(e,t,r=300){if(t.entries.length>0){const n=new Map;for(const l of e.entries)n.set(Ol(l),l);for(const l of t.entries)n.set(Ol(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 Ev(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 $v(e,t){return e.split(`
|
|
76
|
+
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>Jn([r],t))}function Bv(e,t){return e.filter(r=>Jn([r.level,r.category,r.stage,r.interactionId,ii(r.payload)],t))}function Ov(e,t){return e.filter(r=>Jn([r.kind,r.topic,r.interactionId,ii(r.payload)],t))}function Fl(e){return e==="warn"||e==="error"}function Fv({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=>Fl(a.level)).length+r.filter(a=>Fl(a.level)).length}}function Wv({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(`
|
|
77
|
+
`)):t.length>0&&a.push(["[daemon logs]",...t].join(`
|
|
78
|
+
`)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${Gs(o.payload,500)}`.trim())].join(`
|
|
79
|
+
`)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${Gs(o.payload,500)}`.trim())].join(`
|
|
80
|
+
`)),a.join(`
|
|
81
|
+
|
|
82
|
+
`)}function Kv({machineId:e,sendDaemonCommand:t}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[l,c]=i.useState(""),[d,m]=i.useState([]),[u,f]=i.useState([]),[x,w]=i.useState(null),[b,p]=i.useState(!0),[g,y]=i.useState("info"),[h,M]=i.useState("all"),[j,v]=i.useState(!0),[A,T]=i.useState(!0),[S,k]=i.useState(""),[K,L]=i.useState(""),[N,P]=i.useState(0),B=i.useRef(0),D=i.useRef(0),C=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),I=i.useRef([]),E=i.useCallback(()=>{const ee={entries:[],kind:"empty",rawText:"",lastTs:0};C.current=ee,B.current=0,n([]),c(""),o("empty"),v(!0)},[]),R=i.useCallback(()=>{I.current=[],D.current=0,m([]),T(!0)},[]),$=i.useCallback(ee=>{ee!==g&&(E(),y(ee))},[g,E]),z=i.useCallback(ee=>{M(ce=>ce===ee?ce:ee)},[]),F=i.useCallback(()=>{E(),R(),f([]),w(null),k(""),L(""),Os.clear()},[E,R]),me=i.useCallback(()=>{P(ee=>ee+1)},[]),ie=i.useCallback(async()=>{if(!e)return;const ee=B.current,ce=D.current,[je,Ne]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:g,since:ee}),t(e,"get_debug_trace",Tv({count:120,since:ce,category:h}))]);if(je.status==="fulfilled"){const q=je.value,ge=(q==null?void 0:q.result)||q,he=Rv(ge),we=Dv(C.current,he,300);C.current=we,B.current=we.lastTs,v(!1),k((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),k(je.reason instanceof Error?je.reason.message:"Could not load daemon logs");if(Ne.status==="fulfilled"){const q=Ne.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 he=ge.trace,we=Ev(I.current,he,120),xe=he.reduce((Se,J)=>Math.max(Se,Number(J.ts||0)),ce);I.current=we,xe>ce&&(D.current=xe),L(""),m(we)}else L("");T(!1)}else T(!1),L(Ne.reason instanceof Error?Ne.reason.message:"Could not load daemon trace");f(Os.list({limit:120})),w(Date.now())},[g,e,t,h]);return i.useEffect(()=>{R()},[R,h]),i.useEffect(()=>{if(!e||(ie(),!b))return;const ee=setInterval(()=>{ie()},3e3);return()=>clearInterval(ee)},[b,ie,e,N]),{daemonLogs:r,daemonLogKind:a,daemonRawText:l,debugTrace:d,webEvents:u,lastUpdatedAt:x,autoRefresh:b,logLevel:g,traceCategory:h,daemonLoading:j,traceLoading:A,daemonFetchError:S,traceFetchError:K,setAutoRefresh:p,setLogLevel:$,setTraceCategory:z,refresh:me,clear:F}}function Hv({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 Wl(e){return e==="warn"||e==="error"}function Uv(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 zv(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 Kl(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function Vv(e){const t=Gs(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function Gv(e){const t=Gs(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${r} ${t}`:`${e.kind}${r}`}function qv({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:Gv(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:Vv(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:zv(o,l),severity:Uv(o),message:o,raw:o})}),a.sort((o,l)=>o.ts!==l.ts?o.ts-l.ts:Kl(o.source)-Kl(l.source))}function Yv(e){return`${e.source}:${e.severity}:${e.message}`}function Xv(e){const t=e.filter(n=>Wl(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Wl(n.severity))continue;const a=Yv(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 Jv(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Hl(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${Jv(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${r} ${e.message}`.trim()}function Qv({events:e,summary:t,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
|
|
83
|
+
`)),a.push(["[source status]",...r.map(l=>`${l.label}: ${l.status} - ${l.detail}`)].join(`
|
|
84
|
+
`)),t.latestIssue&&a.push(["[latest issue]",Hl(t.latestIssue)].join(`
|
|
85
|
+
`)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(l=>`${l.count}x ${l.severity.toUpperCase()} ${l.source} ${l.message}`)].join(`
|
|
86
|
+
`));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(Hl):["No diagnostic events captured."]].join(`
|
|
87
|
+
`)),a.join(`
|
|
88
|
+
|
|
89
|
+
`)}function Zv(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function ew(e,t){return t==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):t==="info"?e.filter(r=>r.level!=="debug"):e}function tw({daemonLogs:e,daemonRawText:t,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:l,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f}){const x=_v(n,o),w=Pv(e,c),b=$v(t,c),p=Bv(x,c),g=Ov(a,c),y=Zv(w,l),h=l==="all"?b:[],M=ew(p,l),j=l==="issues"?[]:g,v=Fv({daemonLogs:w,daemonRawLines:b,trace:p,webEvents:g}),A=qv({daemonLogs:y,daemonRawLines:h,trace:M,webEvents:j}),T=Xv(A),S=Hv({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:f,daemonLogKind:r,daemonLogsCount:w.length,daemonRawLineCount:b.length,traceCount:p.length,webEventCount:g.length});return{filteredDaemonLogs:w,filteredDaemonRawLines:b,filteredTraceEntries:p,filteredWebEvents:g,visibleDaemonLogs:y,visibleDaemonRawLines:h,visibleTraceEntries:M,visibleWebEvents:j,quickFilterCounts:v,diagnosticEvents:A,diagnosticsSummary:T,sourceStates:S}}function sw(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function yu(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function po(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 Pa(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function li(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function rw({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${po(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:yu(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:li(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 nw({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(f=>s.jsx("button",{type:"button",onClick:()=>a(f.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===f.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:f.label},f.id))}),s.jsx("input",{value:r,onChange:f=>o(f.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 aw({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:Av.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 ow({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:l,traceFetchError:c}){var u,f;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((f=e.latestIssue)==null?void 0:f.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 ${Pa(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 ${Pa(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:[li(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:yu(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 ${Pa(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: ",sw(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(x=>s.jsxs("div",{children:[x.label,": ",x.status]},x.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()," · ",li(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function lw({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(rw,{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,f)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${f}`)),e.daemonLogKind!=="text"&&a.map((u,f)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${po(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-${f}`))]})]}),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 ${po(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:Gs(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:Gs(u.payload,360)||"No payload"})]},u.id))]})]})]})}function cw({machineId:e,sendDaemonCommand:t}){const r=Kv({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),f=i.useMemo(()=>tw({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&&f.diagnosticEvents.length>0){const b=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:b}),u.current=!0},50)}},[f.diagnosticEvents.length,r.autoRefresh]);const x=i.useCallback(async()=>{var p;const b=Wv({daemonLogs:f.visibleDaemonLogs,daemonRawLines:f.visibleDaemonRawLines,trace:f.visibleTraceEntries,webEvents:f.visibleWebEvents});if(!b.trim()){ot.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(b)),ot.showToast("Copied visible logs to clipboard.","success")}catch(g){ot.showToast(g instanceof Error?g.message:"Could not copy visible logs","warning")}},[f.visibleDaemonLogs,f.visibleDaemonRawLines,f.visibleTraceEntries,f.visibleWebEvents]),w=i.useCallback(async()=>{var p;const b=Qv({events:f.diagnosticEvents,summary:f.diagnosticsSummary,sources:f.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(b)),ot.showToast("Copied diagnostic bundle to clipboard.","success")}catch(g){ot.showToast(g instanceof Error?g.message:"Could not copy diagnostic bundle","warning")}},[f.diagnosticEvents,f.diagnosticsSummary,f.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(nw,{quickFilter:n,quickFilterCounts:f.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:l,onCopyDiagnostics:()=>{w()},onCopyVisible:()=>{x()},onToggleAutoRefresh:()=>r.setAutoRefresh(b=>!b),onRefresh:r.refresh,onClear:r.clear}),s.jsx(aw,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),s.jsx(ow,{diagnosticsSummary:f.diagnosticsSummary,diagnosticEventsCount:f.diagnosticEvents.length,sourceStates:f.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),s.jsx(iw,{patterns:f.diagnosticsSummary.repeatedPatterns}),s.jsx(lw,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:f.diagnosticEvents,visibleDaemonLogs:f.visibleDaemonLogs,visibleDaemonRawLines:f.visibleDaemonRawLines,visibleTraceEntries:f.visibleTraceEntries,visibleWebEvents:f.visibleWebEvents,quickFilter:n,searchQuery:o}),s.jsx("div",{ref:m})]})}function dw(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 vu(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 uw(e){var a;const t=[],r=[],n=[];for(const o of e||[]){const l=String((o==null?void 0:o.lifecycle)||"").trim(),c=vu((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 mw(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Da(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function Ea(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function $a(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ul(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 pw(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function fw(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 hw(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 xw({machineId:e,cliSessions:t,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,l]=i.useState(null),[c,d]=i.useState(!1),m=pb(e,{enabled:!!e,includeSessions:!0,limit:Ki,intervalMs:ch}),u=m.diagnostics,f=m.loading,x=m.applyDiagnostics,w=i.useMemo(()=>dw({diagnostics:u,loading:f,refreshing:c,error:n}),[u,f,c,n]),b=i.useMemo(()=>new Map(t.map(L=>[L.sessionId||L.id,L])),[t]),p=i.useCallback(async()=>{if(e){d(!0);try{const L=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Ki}),N=Ea(L);if(!(N!=null&&N.success))throw new Error((N==null?void 0:N.error)||"Could not load hosted runtime diagnostics");x(N.diagnostics||N.result||null),a("")}catch(L){const N=L instanceof Error?L.message:"Could not load hosted runtime diagnostics";a(N)}finally{d(!1)}}},[x,e,r]);i.useEffect(()=>{!e||u||f||c||p()},[u,f,e,p,c]);const g=i.useCallback(async(L,N)=>{const P=`${L}:${N.sessionId}`;if(!(L==="session_host_stop_session"&&!window.confirm(`Stop ${N.displayName}?
|
|
90
|
+
This will terminate the hosted runtime.`))){l(P);try{const B=await r(e,L,{sessionId:N.sessionId}),D=Ea(B);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Session host action failed");const C=L==="session_host_resume_session"?"resumed":L==="session_host_restart_session"?"restarted":"stopped";ot.showToast(`Session host ${C}: ${N.displayName}`,"success"),await p()}catch(B){const D=B instanceof Error?B.message:"Session host action failed";ot.showToast(D,"warning"),a(D)}finally{l(B=>B===P?null:B)}}},[e,p,r]),y=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
91
|
+
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){l("session_host_prune_duplicate_sessions");try{const N=await r(e,"session_host_prune_duplicate_sessions",{}),P=Ea(N);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const B=P.result||{},D=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,C=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;ot.showToast(`Pruned ${D} duplicate runtime(s) across ${C} group(s)`,"success"),await p()}catch(N){const P=N instanceof Error?N.message:"Duplicate prune failed";ot.showToast(P,"warning"),a(P)}finally{l(N=>N==="session_host_prune_duplicate_sessions"?null:N)}}},[e,p,r]),h=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((L,N)=>(N.lastActivityAt||0)-(L.lastActivityAt||0)),[u==null?void 0:u.sessions]),M=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)||[]}:uw(h),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,h]),j=M.liveRuntimes,v=M.recoverySnapshots,A=M.inactiveRecords,T=i.useMemo(()=>hw(j),[j]),S=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),k=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(L=>L.level==="warn"||L.level==="error")||null,[u==null?void 0:u.recentLogs]),K=(L,N)=>{var z;const P=o===`session_host_resume_session:${L.sessionId}`,B=o===`session_host_restart_session:${L.sessionId}`,D=o===`session_host_stop_session:${L.sessionId}`,C=vu(L.meta),I=b.get(L.sessionId),E=L.attachedClients.length===1?"1 client":`${L.attachedClients.length} clients`,R=N==="recovery"?"Recover":"Resume",$=mw(N);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||(I==null?void 0:I.cliName)||L.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${fw(L.lifecycle)}`,children:L.lifecycle}),C&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:C})]}),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||(I==null?void 0:I.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:((z=L.writeOwner)==null?void 0:z.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:pw(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(nc,{size:11})," ",E]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Ul(L.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[N==="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:P?`${R}ing…`:R}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{g("session_host_restart_session",L)},children:B?"Restarting…":"Restart"}),N==="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:D?"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(as,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:fx()})]}),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:()=>{p()},disabled:f||c,children:[s.jsx(Tr,{size:13}),f||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(Cr,{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:Ul(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:$a(u.hostStartedAt)})]})]}),k&&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(Cr,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:k.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[$a(k.timestamp),k.sessionId?` · ${k.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(jo,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Da("live")}),j.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:j.map(L=>K(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(as,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Da("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=>K(L,"recovery"))})]}),A.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:Da("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:A.map(L=>K(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"}),S.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:S.map(L=>{var P;const N=h.find(B=>B.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:(N==null?void 0:N.displayName)||((P=b.get(L.sessionId))==null?void 0:P.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:$a(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 bw({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 Ba({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 Oa({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 gw({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=Td(e),f=Rs(e,m),x=wr(e,f),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(Ba,{icon:s.jsx(Jt,{size:13}),children:"Current Chats"}),s.jsx(Oa,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(b=>{const p=lo(b);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(b),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(b)}),p>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:On(p)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Ns(b)})]},b.tabKey)})})})]}),d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ba,{icon:s.jsx(lc,{size:13}),children:"Recent Launches"}),s.jsx(Oa,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(b=>{const{metaText:p,updatedLabel:g}=Kd(b);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(b),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:b.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:p})]},b.id)})})})]}),e.versionMismatch&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ba,{icon:s.jsx(Cr,{size:13}),children:"Daemon Update"}),s.jsx(Oa,{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:x?"Daemon update required":"Version mismatch detected"}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[x?"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.",f&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",f,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 yw(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function vw({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?"⭐ ":"",Wn(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 nn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Fa({category:e,machine:t,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:l,sendDaemonCommand:c,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const f=qs(),{handleLaunchIde:x,handleStopCli:w,handleRestartIde:b,handleStopIde:p,handleDetectIdes:g,launchingIde:y,launchingAgentType:h,addLog:M}=l,[j,v]=i.useState(null),A=i.useCallback(_=>{_&&f(is(_))},[f]),T=ww[e],S=e==="ide",k=e==="acp",K=i.useMemo(()=>n.filter(_=>Cs(_,e)),[e,n]),L=i.useMemo(()=>new Map(K.map(_=>[_.type,_.displayName||_.type])),[K]),[N,P]=i.useState(""),[B,D]=i.useState(""),[C,I]=i.useState([]),[E,R]=i.useState(""),[$,z]=i.useState(""),[F,me]=i.useState([]),[ie,ee]=i.useState(!1),[ce,je]=i.useState(!1),[Ne,q]=i.useState(""),[ge,he]=i.useState(!1),[we,xe]=i.useState(()=>Nt()),[Se,J]=i.useState(null),[fe,ae]=i.useState(m?"__custom__":d||t.defaultWorkspaceId||""),[ue,oe]=i.useState(m||""),[de,Q]=i.useState([]),[ve,le]=i.useState(!1),[pe,ne]=i.useState(""),[Ie,Ce]=i.useState([]),[_e,H]=i.useState(!1),[Me,Ae]=i.useState(""),Ke=i.useRef(null),[Ve,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&&!fe&&ae(t.defaultWorkspaceId)},[t.defaultWorkspaceId]),i.useEffect(()=>{if(m){ae("__custom__"),oe(m);return}d&&(ae(d),oe(""))},[d,m]),i.useEffect(()=>{S||N&&(K.some(_=>_.type===N)||(P(""),z("")))},[K,S,N]);const Be=(()=>{if(fe==="__custom__")return ue.trim();if(!fe)return"";const _=(t.workspaces||[]).find(Y=>Y.id===fe);return(_==null?void 0:_.path)||""})(),qe=i.useCallback(_=>{const Y=Te.current[_];Y&&(clearTimeout(Y),delete Te.current[_]),Q(ye=>ye.includes(_)?ye.filter(We=>We!==_):ye)},[]),V=i.useRef(new Set),U=i.useCallback(async _=>{if(c){H(!0),Ae("");try{const Y=await qn(c,r,_);ne(Y.path),oe(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;ae("__custom__"),le(!0);const _=a.map(ye=>ye.workspace),Y=Gn(t.platform,Vn(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]),se=i.useCallback(_=>{const Y=String(_.workspace||"").trim();if(!Y)return;const ye=(t.workspaces||[]).find(We=>nn(We.path)===nn(Y));if(ye){ae(ye.id),oe("");return}ae("__custom__"),oe(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=>nn(We.path)===nn(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"){me([]),ee(!1),je(!1),q("");return}const Y=O.current+1;O.current=Y,ee(!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;me(Array.isArray(We==null?void 0:We.sessions)?We.sessions:[])}catch(ye){if(O.current!==Y)return;me([]),q(ye instanceof Error?ye.message:"Could not load saved sessions")}finally{O.current===Y&&(ee(!1),je(!0))}},[e,r,c]),te=i.useMemo(()=>{if(e!=="cli"||!N)return null;const _=L.get(N)||N;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:_,agentType:N,status:"idle",title:_,messages:[],ideType:N,workspaceName:Be,workspacePath:Be,displayPrimary:_,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${N}`}},[e,r,L,Be,$,N]),re=i.useCallback(_=>{if(e==="ide"||!_){I([]);return}I(mo(r,_))},[e,r]),ke=i.useCallback((_,Y)=>{e==="ide"||!_||(Iy(r,_,Y),I(mo(r,_)))},[e,r]);i.useEffect(()=>{O.current+=1,z(""),re(N),je(!1),me([]),q(""),ee(!1)},[e,re,G,N]);const Ee=i.useMemo(()=>F.find(_=>_.providerSessionId===$)||null,[F,$]);i.useEffect(()=>{if(!$)return;const _=F.find(Y=>Y.providerSessionId===$);_!=null&&_.canResume||z("")},[F,$]);const Oe=i.useCallback((_,Y)=>{Ke.current=Y,Ye.current=_.selectedWorkspaceKey||"__home__",ct(_.selectedWorkspaceKey||"__home__"),Xe(_)},[]),Re=i.useCallback(()=>{Ke.current&&(pt(!0),Ke.current().finally(()=>{Ke.current=null,pt(!1),Xe(null)}))},[]),Fe=i.useCallback(_=>{if(!_)return;Q(ye=>ye.includes(_)?ye:[...ye,_]);const Y=Te.current[_];Y&&clearTimeout(Y),Te.current[_]=setTimeout(()=>{Q(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)&&!V.current.has(Y.type)&&(V.current.add(Y.type),M("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));V.current.forEach(Y=>{!de.includes(Y)&&!_.has(Y)&&V.current.delete(Y)})},[M,qe,a,de,L]),i.useEffect(()=>()=>{Object.values(Te.current).forEach(clearTimeout),Te.current={}},[]);const[Ue,Le]=i.useState({}),[Qe,et]=i.useState(null);i.useEffect(()=>{if(!S||!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{}})()},[S,r,c]);const gt=_=>S?lt(_.type):e==="cli"?_.cliName:_.acpName,yt=S?t.detectedIdes||[]:[],dt=i.useCallback(async _=>{const Y=(_==null?void 0:_.type)||N,ye=(_==null?void 0:_.workspacePath)??Be;if(S){await x(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)??(B||void 0),model:(_==null?void 0:_.model)??(k&&E||void 0),resumeSessionId:(_==null?void 0:_.resumeSessionId)||!k&&e==="cli"&&Y===N&&$||void 0});if(We.success||We.pending){const Pe=(_==null?void 0:_.argsStr)??B;!S&&(Pe!=null&&Pe.trim())&&(su(r,Y,Pe),re(Y)),Fe(Y),We.success&&We.sessionId&&A(We.sessionId)}},[l,x,k,S,B,E,re,Fe,r,A,Be,$,N]),ht=ed(S?"ide":k?"acp":"cli",!S&&!k&&!!$),Ge=td(S?"ide":k?"acp":"cli",!S&&!k&&!!$),Wt=()=>{var Pe;const _=S?lt(N):L.get(N)||N,Y=!S&&!k&&!!$,{options:ye,selectedKey:We}=ws({machine:t,currentWorkspaceId:fe&&fe!=="__custom__"?fe:null,currentWorkspacePath:Be});Oe({title:Y?Wo(_):xs("start-fresh",_),description:Y?Ko():bs("start-fresh"),confirmLabel:ht,busyLabel:Ge,workspaceOptions:ye,selectedWorkspaceKey:We,details:[{label:"Mode",value:T.label},{label:"Provider",value:_},...!S&&e==="cli"&&$?[{label:"Resume",value:((Pe=F.find(He=>He.providerSessionId===$))==null?void 0:Pe.title)||$}]:[],...!S&&B.trim()?[{label:"Arguments",value:B.trim()}]:[],...k&&E.trim()?[{label:"Model",value:E.trim()}]:[]]},async()=>{const He=ye.find(rt=>rt.key===Ye.current);He!=null&&He.workspaceId?(ae(He.workspaceId),oe("")):He!=null&&He.workspacePath?(ae("__custom__"),oe(He.workspacePath)):(ae(""),oe("")),await dt({workspaceId:(He==null?void 0:He.workspaceId)??null,workspacePath:(He==null?void 0:He.workspacePath)??"",useHome:!(He!=null&&He.workspaceId)&&!(He!=null&&He.workspacePath)})})},Z=_=>{S?p(_):w(_.type,_.workspace,_.id)},$e=i.useCallback(async(_,Y,ye=!1)=>{if(_.mode===Y){ye&&_.sessionId&&A(_.sessionId);return}if(!c||!_.sessionId){ye&&_.sessionId&&A(_.sessionId);return}try{await c(r,"set_cli_view_mode",{targetSessionId:_.sessionId,cliType:_.type,mode:Y}),ye&&A(_.sessionId)}catch(We){const Pe=wd(We);vd(We)?console.warn(Pe?"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,A,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:S?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,Pe=de.includes(_.type||_.id||""),He=N===(_.type||"");return s.jsxs("button",{onClick:()=>{if(We&&Y){const rt=Y.sessionId;rt?f(is(rt),{state:{openRemoteForTabKey:rt}}):f("/dashboard",{state:{openRemoteForTabKey:Y.id}});return}Pe||P(rt=>rt===(_.type||"")?"":_.type||"")},disabled:!!y||Pe,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":He?"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":Pe?"text-orange-400":He?"text-accent-primary":"text-text-muted"}`,children:We?"Open Session":Pe?"Starting...":He?"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($m,{size:14})," Scan System"]})]}):K.length>0?K.map(_=>{const Y=N===_.type,ye=de.includes(_.type),Pe=!!a.find(He=>He.type===_.type&&vt(He.status)!=="stopped");return s.jsxs("button",{onClick:()=>P(He=>He===_.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}),Pe&&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."})]})}),N&&(S?yt.find(_=>_.type===N):K.find(_=>_.type===N))&&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:S?lt(N):L.get(N)||N})]}),s.jsx(vw,{machine:t,selectedWorkspace:fe,resolvedWorkspacePath:Be,customPath:ue,canBrowse:!!c,onWorkspaceChange:ae,onCustomPathChange:oe,onOpenBrowseDialog:X}),!S&&s.jsxs("div",{className:"flex flex-col gap-3",children:[!k&&e==="cli"&&s.jsx(nu,{busy:!!h||!!y||de.includes(N),savedSessionsLoading:ie,savedSessionsError:Ne,savedSessionsLoaded:ce,savedSessionsCount:F.length,selectedSession:Ee,onRefresh:()=>void G(N),onOpenHistory:()=>{N&&(he(!0),ru({hasLoadedInitialResults:ce,isLoading:ie})&&G(N))},onClearSelection:()=>z("")}),s.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[k&&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:E,onChange:_=>R(_.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:B,onChange:_=>D(_.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"}),C.length>0&&s.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:C.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:()=>D(_),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:()=>ke(N,_),"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:Wt,disabled:!!h||!!y||de.includes(N),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:h===N||y===N?"⏳ 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:S?lt(_):L.get(_)||_}),s.jsx("div",{className:"text-[11px] text-text-muted",children:h===_?"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=S?_:null,ye=!S&&!k?_: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:Pe=>{Pe.stopPropagation(),u(_.daemonId??r,_.workspace)},children:s.jsx(Us,{git:_.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Us,{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 Pe;(Pe=navigator.clipboard)==null||Pe.writeText(`adhdev attach ${ye.runtimeKey}`),v(ye.runtimeKey||null),window.setTimeout(()=>{v(He=>He===ye.runtimeKey?null:He)},1200)},children:j===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:yw(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}),S&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>{const Pe=_.sessionId;if(Pe){f(is(Pe),{state:{openRemoteForTabKey:Pe}});return}f("/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(_t,{size:13})}),s.jsx("button",{onClick:()=>{const Pe=_.workspace||"",{options:He,selectedKey:rt}=ws({machine:t,currentWorkspacePath:Pe});Oe({title:xs("restart-ide",lt(_.type)),description:bs("restart-ide"),confirmLabel:zs("restart-ide"),busyLabel:Vs("restart-ide"),workspaceOptions:He,selectedWorkspaceKey:rt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:lt(_.type)}]},async()=>{const Mt=He.find(Zt=>Zt.key===Ye.current),xt=(Mt==null?void 0:Mt.workspacePath)??"";if(xt&&xt!==Pe){await dt({type:_.type,workspacePath:xt});return}await b(_)})},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})})]}),k&&s.jsx("button",{onClick:()=>{const Pe=_.sessionId;Pe&&A(Pe)},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(Jt,{size:14})}),ye&&We!=="stopped"&&s.jsxs(s.Fragment,{children:[ye.mode&&s.jsx(Bo,{mode:ye.mode,onChange:Pe=>void $e(ye,Pe,!1),compact:!0}),s.jsx("button",{onClick:()=>{const Pe=_.sessionId;Pe&&A(Pe)},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(Jt,{size:14}):s.jsx(_t,{size:13})})]}),We==="stopped"?s.jsx("button",{onClick:()=>{const Pe=_.workspace||"",He=S?lt(_.type):gt(_),{options:rt,selectedKey:Mt}=ws({machine:t,currentWorkspacePath:Pe});Oe({title:xs("restart-stopped",He),description:bs("restart-stopped"),confirmLabel:zs("restart-stopped"),busyLabel:Vs("restart-stopped"),workspaceOptions:rt,selectedWorkspaceKey:Mt,details:[{label:"Mode",value:T.label},{label:"Provider",value:He}]},async()=>{const xt=rt.find(Zt=>Zt.key===Ye.current);await dt({type:_.type,workspaceId:(xt==null?void 0:xt.workspaceId)??null,workspacePath:(xt==null?void 0:xt.workspacePath)??"",useHome:!(xt!=null&&xt.workspaceId)&&!(xt!=null&&xt.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(ko,{size:14})}):s.jsx("button",{onClick:()=>Z(_),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(Pe=>s.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${Sn(Pe.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Pe.name," · ",vt(Pe.status)]},Pe.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(Pe=>s.jsxs("button",{disabled:Qe===`${Y.type}.${Pe.type}`,onClick:async()=>{const He=`${Y.type}.${Pe.type}`;et(He);try{await c(r,"set_ide_extension",{ideType:Y.type,extensionType:Pe.type,enabled:!Pe.enabled}),Le(rt=>({...rt,[Y.type]:(rt[Y.type]||[]).map(Mt=>Mt.type===Pe.type?{...Mt,enabled:!Mt.enabled}:Mt)}))}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 ${Pe.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 ${Pe.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Pe.name,s.jsx("span",{className:"text-[9px] font-normal",children:Pe.enabled?"ON":"OFF"})]},Pe.type))})]})]},_.id)})]}),ve&&c&&s.jsx(Yn,{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:()=>le(!1),onNavigate:_=>{U(_)},onConfirm:_=>{oe(_),ae("__custom__"),le(!1)}}),Ve&&s.jsx(Jo,{title:Ve.title,description:Ve.description,details:Ve.details,workspaceOptions:Ve.workspaceOptions,selectedWorkspaceKey:tt,onWorkspaceChange:_=>{Ye.current=_,ct(_)},confirmLabel:Ve.confirmLabel,busyLabel:Ve.busyLabel,busy:mt,onConfirm:Re,onCancel:()=>{Ke.current=null,Xe(null)}}),ge&&te&&s.jsx(Ho,{activeConv:te,ides:[],isCreatingChat:!1,isRefreshingHistory:ie,savedSessions:F,isSavedSessionsLoading:ie,isResumingSavedSessionId:Se,savedHistoryFilters:we,missingWorkspaceResumePath:Be||null,onSavedHistoryFiltersChange:xe,onClose:()=>he(!1),onNewChat:()=>{z(""),he(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{G(N)},onResumeSavedSession:_=>{if(!_.canResume||Se)return;const Y=W(_);z(_.providerSessionId),se(_),J(_.providerSessionId),he(!1),dt({type:_.providerType,workspaceId:Y.workspaceId,workspacePath:Y.workspacePath,useHome:Y.useHome,resumeSessionId:_.providerSessionId}).finally(()=>{J(ye=>ye===_.providerSessionId?null:ye)})}})]})}const zl=[{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 jw({machine:e,machineId:t,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:l,getIcon:c,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:f,onOpenGitDialog:x}){var g;const[w,b]=i.useState(d);i.useEffect(()=>{b(d)},[d]);const p=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:zl.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:()=>b(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:p[y.id]})]},y.id))}),s.jsx("div",{className:"text-xs text-text-muted italic",children:(g=zl.find(y=>y.id===w))==null?void 0:g.helper})]}),w==="ide"&&s.jsx(Fa,{category:"ide",machine:e,machineId:t,providers:r,managedEntries:n,getIcon:c,actions:l,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),w==="cli"&&s.jsx(Fa,{category:"cli",machine:e,machineId:t,providers:r,managedEntries:a,getIcon:c,actions:l,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x}),w==="acp"&&s.jsx(Fa,{category:"acp",machine:e,machineId:t,providers:r,managedEntries:o,getIcon:c,actions:l,sendDaemonCommand:f,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:x})]})}function kw({onNicknameSynced:e}={}){var oe,de,Q,ve,le,pe,ne,Ie,Ce,_e;const{id:t}=im(),r=qs(),n=bo(),{sendCommand:a}=kt(),o=Rr(),l=hd(),c=Vc(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(H=>H.id===t&&H.type==="adhdev-daemon"),f=d.some(H=>H.type==="adhdev-daemon"),x=t?(oe=c.connectionRetryStatuses)==null?void 0:oe[t]:void 0,w=!!(x!=null&&x.blocked),[b,p]=i.useState("workspace"),[g,y]=i.useState(null),h=i.useCallback((H,Me)=>{y({daemonId:H,workspace:Me})},[]),[M,j]=i.useState("ide"),v=i.useRef(null),[A,T]=i.useState(null),S=i.useRef("__home__"),[k,K]=i.useState("__home__"),[L,N]=i.useState(!1),P=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||b!=="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(()=>{})},[b,l,u,t]),mb(t&&b==="overview"?[t]:[],{enabled:b==="overview",intervalMs:ah});const B=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},D=gv({machineId:t,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:P});i.useEffect(()=>ot.onToast(Me=>{c.setToasts(Ke=>{if(Ke.some(Ye=>Ye.message===Me.message&&Me.timestamp-Ye.timestamp<3e3))return Ke;const Xe={id:Me.id,message:Me.message,type:Me.type,timestamp:Me.timestamp,targetKey:Me.targetKey,actions:Me.actions};return[...Ke.slice(-4),Xe]});const Ae=Me.duration||5e3;setTimeout(()=>c.setToasts(Ke=>Ke.filter(Ve=>Ve.id!==Me.id)),Ae)}),[c]);const C=(u==null?void 0:u.availableProviders)||[],I={};for(const H of C)I[H.type]=H.icon;const E=H=>I[H]||"",R=u?{id:u.id,hostname:vc(u,{fallbackId:u.id}),platform:((de=u.machine)==null?void 0:de.platform)||"unknown",arch:((Q=u.machine)==null?void 0:Q.arch)||"",cpus:((ve=u.machine)==null?void 0:ve.cpus)||0,totalMem:((le=u.machine)==null?void 0:le.totalMem)||0,freeMem:(pe=u.machine)==null?void 0:pe.freeMem,availableMem:(ne=u.machine)==null?void 0:ne.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,$=d.filter(H=>H.daemonId===t&&H.type!=="adhdev-daemon").filter(H=>!Ir(H)&&!Es(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:Xp(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})),z=d.filter(H=>H.daemonId===t&&Ir(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})),F=d.filter(H=>H.daemonId===t&&Es(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})),me=u?Tt(u,{fallbackId:t}):"",ie="workspace",ee=n.state,ce=ee==null?void 0:ee.initialMachineTab,je=ee==null?void 0:ee.initialWorkspaceCategory,Ne=ee==null?void 0:ee.initialWorkspaceId,q=ee==null?void 0:ee.initialWorkspacePath,ge=ce==="ides"||ce==="clis"||ce==="acps"?"workspace":ce||ie,he=ce==="ides"?"ide":ce==="clis"?"cli":ce==="acps"?"acp":je,we=[...$.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}}),...z.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}}),...F.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:Ss(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:Ss(H.summaryMetadata)||H.workspace||void 0,workspace:H.workspace,summaryMetadata:H.summaryMetadata,lastLaunchedAt:H.lastLaunchedAt})):we,Se=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=>Uo(Ae,{connectionStates:t&&H?{[t]:H}:void 0,defaultConnectionState:H})).filter(Ae=>!(Ae.transport==="pty"&&Ae.mode==="terminal")).sort((Ae,Ke)=>lo(Ke)-lo(Ae))},[d,c.connectionStates,t]),J=i.useCallback(H=>{const Me=Dd(H);Me&&r(is(Me))},[r]),fe=i.useCallback(()=>{v.current&&(N(!0),v.current().finally(()=>{v.current=null,N(!1),T(null)}))},[]),ae=i.useCallback(H=>{if(!R)return;const{options:Me,selectedKey:Ae}=ws({machine:R,currentWorkspacePath:H.workspace}),Ke=async()=>{j(H.kind),p("workspace")};v.current=async()=>{const Ve=Me.find(tt=>tt.key===S.current),Xe=(Ve==null?void 0:Ve.workspacePath)??null,Ye=(Ve==null?void 0:Ve.workspaceId)??null;if(H.kind==="ide"&&H.providerType){await D.handleLaunchIde(H.providerType,Xe?{workspace:Xe}:void 0);return}if((H.kind==="cli"||H.kind==="acp")&&H.providerType){await D.runLaunchCliCore({cliType:H.providerType,dir:Ye?void 0:Xe||"",workspaceId:Ye||void 0,model:H.kind==="acp"&&jc(H.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:H.providerSessionId});return}await Ke()},S.current=Ae,K(Ae),T({title:H.kind==="ide"?xs("restart-ide",H.label):H.providerSessionId?Wo(H.label):xs("start-fresh",H.label),description:H.kind==="ide"?bs("restart-ide"):H.providerSessionId?Ko():bs("start-fresh"),confirmLabel:H.kind==="ide"?zs("restart-ide"):H.providerSessionId?An(!0):zs("start-fresh"),busyLabel:H.kind==="ide"?Vs("restart-ide"):H.providerSessionId?Oo(!0):Vs("start-fresh"),workspaceOptions:Me,details:[{label:"Mode",value:H.kind.toUpperCase()},...H.providerType?[{label:"Provider",value:H.providerType}]:[]]})},[D,R]);if(i.useEffect(()=>{p(ge)},[ie,ge,t]),i.useEffect(()=>{he&&j(he)},[he,t]),!R)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:B,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(_t,{size:14})," Workspace"]}),count:$.length+z.length+F.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(as,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx($n,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Om,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Dm,{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:B,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:[D.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:D.nicknameInput,onChange:H=>D.setNicknameInput(H.target.value),onKeyDown:H=>{H.key==="Enter"&&D.handleSaveNickname(),H.key==="Escape"&&D.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:D.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>D.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{D.setEditingNickname(!0),D.setNicknameInput(R.machineNickname||"")},title:"Click to set nickname",children:me}),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:[R.platform," · ",R.arch]}),s.jsxs("span",{children:[R.cpus," cores"]}),(u==null?void 0:u.version)&&s.jsxs("span",{children:["v",u.version]}),R.p2p.available&&s.jsxs("span",{children:["P2P ",R.p2p.state==="connected"?"connected":R.p2p.state]}),R.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:R.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:()=>p(H.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${b===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 ${b===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:[b==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(gw,{machineEntry:u,providers:C,recentLaunches:xe,currentConversations:Se,onUpgradeDaemon:async()=>{try{await a(t,"daemon_upgrade",_d(u))}catch{}},onOpenRecent:ae,onOpenConversation:J}),s.jsx(jw,{machine:R,machineId:t,providers:C,ideSessions:$,cliSessions:z,acpSessions:F,actions:D,getIcon:E,initialCategory:M,initialWorkspaceId:Ne,initialWorkspacePath:q,sendDaemonCommand:a,onOpenGitDialog:h})]}),b==="providers"&&s.jsx(Mv,{machineId:t,providers:C,sendDaemonCommand:a}),b==="overview"&&s.jsx(yv,{machineId:t,machine:R,ideSessions:$,cliSessions:z,acpSessions:F,actions:D,sendDaemonCommand:a}),b==="session-host"&&s.jsx(xw,{machineId:t,cliSessions:z,sendDaemonCommand:a}),b==="logs"&&s.jsx(cw,{machineId:t,sendDaemonCommand:a})]})})}),D.launchPick&&R&&s.jsx(bw,{machine:R,launchPick:D.launchPick,actions:D}),A&&s.jsx(Jo,{title:A.title,description:A.description,details:A.details,workspaceOptions:A.workspaceOptions,selectedWorkspaceKey:k,onWorkspaceChange:H=>{S.current=H,K(H)},confirmLabel:A.confirmLabel,busyLabel:A.busyLabel,busy:L,onConfirm:fe,onCancel:()=>{v.current=null,T(null)}}),g&&s.jsx(gu,{daemonId:g.daemonId,workspace:g.workspace,onClose:()=>y(null)}),s.jsx(sd,{toasts:c.toasts||[],onDismiss:H=>c.setToasts(Me=>Me.filter(Ae=>Ae.id!==H)),onClickToast:H=>{H.targetKey&&r(is(H.targetKey))}}),s.jsx("style",{children:`
|
|
92
|
+
@keyframes toast-in {
|
|
93
|
+
from { opacity: 0; transform: translateX(40px); }
|
|
94
|
+
to { opacity: 1; transform: translateX(0); }
|
|
95
|
+
}
|
|
96
|
+
`})]})}const an=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],Sw={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function bn(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 Nw(e){const t=bn(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 Cw(e,t){return t.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function Iw(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 Mw(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 Wa(e){return{...Sw,...(e==null?void 0:e.policy)||{}}}function Aw({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=Pd(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(au,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function Tw(){var Ye,tt,ct,mt,pt;const{sendCommand:e}=kt(),{ides:t}=ls(),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=Cx(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,f]=i.useState(!0),[x,w]=i.useState(null),[b,p]=i.useState(!1),[g,y]=i.useState(null),[h,M]=i.useState({}),[j,v]=i.useState([]),[A,T]=i.useState(null),[S,k]=i.useState(null),[K,L]=i.useState(!1),[N,P]=i.useState(null),[B,D]=i.useState(null),[C,I]=i.useState(!1),[E,R]=i.useState(!1),[$,z]=i.useState(!1),[F,me]=i.useState(""),[ie,ee]=i.useState(""),[ce,je]=i.useState(!1),[Ne,q]=i.useState(""),[ge,he]=i.useState(""),[we,xe]=i.useState(!1),[Se,J]=i.useState(""),[fe,ae]=i.useState([]),ue=l.find(O=>O.id===d)||null;i.useEffect(()=>{M(Object.fromEntries(((ue==null?void 0:ue.nodes)||[]).map(O=>[O.id,bn(O)])))},[ue]),i.useEffect(()=>{const O=Ix(o);we&&fe.length===0&&O.length>0&&ae(O)},[we,o,fe.length]),i.useEffect(()=>{const O=new Set(((ue==null?void 0:ue.nodes)||[]).map(be=>be.id));A&&!O.has(A)&&T(null)},[ue,A]);const oe=i.useCallback(async()=>{if(n){f(!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{f(!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]),Q=i.useCallback(async O=>{var be;if(!n||!O){D(null),me(""),ee("");return}I(!0);try{const Te=await e(n,"get_mesh_host_pairing",{meshId:O});Te!=null&&Te.success?(D(Te),me(Te.hostAddress||((be=Te.meshHost)==null?void 0:be.hostAddress)||"")):D({success:!1,error:(Te==null?void 0:Te.error)||"Failed to load Mesh Host pairing"}),ee("")}catch(Te){D({success:!1,error:(Te==null?void 0:Te.message)||"Failed to load Mesh Host pairing"}),ee("")}finally{I(!1)}},[n,e]);i.useEffect(()=>{oe()},[oe]),i.useEffect(()=>{de(d)},[de,d]),i.useEffect(()=>{Q(d)},[Q,d]);async function ve(){if(!(!n||!d))try{L(!0),P(null);const O=await e(n,"mesh_status",{meshId:d});if((O==null?void 0:O.success)===!1){k(null),P((O==null?void 0:O.error)||"mesh_status failed");return}const be=hu(O);be?k(be):(k(null),P("mesh_status returned an unexpected payload."))}catch(O){k(null),P((O==null?void 0:O.message)||"Failed to load mesh graph")}finally{L(!1)}}i.useEffect(()=>{d&&(k(null),P(null),ve())},[d]);async function le(){var O;if(!(!n||!Ne.trim()))try{const be=await e(n,"create_mesh",{name:Ne.trim(),repoIdentity:ge.trim()||void 0});be!=null&&be.success?(je(!1),q(""),he(""),await oe(),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 oe()}catch(be){w((be==null?void 0:be.message)||"Delete failed")}}async function ne(){if(!(!n||!d||!Se.trim()))try{const O=await e(n,"add_mesh_node",{meshId:d,workspace:Se.trim(),providerPriority:ro(fe,o)});O!=null&&O.success?(xe(!1),J(""),ae([]),await oe(),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=Wa(ue),Te=((Be=an.find(qe=>qe.value===be.sessionCleanupOnNodeRemove))==null?void 0:Be.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
|
|
97
|
+
|
|
98
|
+
Node removal cleanup policy: ${Te}`))try{await e(n,"remove_mesh_node",{meshId:d,nodeId:O}),A===O&&T(null),await oe(),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={...Wa(ue),...O};try{p(!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 oe()}catch(Te){w((Te==null?void 0:Te.message)||"Policy update failed")}finally{p(!1)}}async function _e(){var O;if(!(!n||!d||!F.trim()||!ie.trim())){R(!0);try{const be=await e(n,"configure_mesh_host_pairing",{meshId:d,hostAddress:F.trim(),token:ie.trim()});be!=null&&be.success?(D(be),me(be.hostAddress||((O=be.meshHost)==null?void 0:O.hostAddress)||F.trim()),await oe()):D({success:!1,error:(be==null?void 0:be.error)||"Failed to save Mesh Host pairing"})}catch(be){D({success:!1,error:(be==null?void 0:be.message)||"Failed to save Mesh Host pairing"})}finally{R(!1)}}}async function H(){if(!(!n||!d||!ie.trim())){z(!0);try{const O=await e(n,"join_mesh_host_pairing",{meshId:d,token:ie.trim()});O!=null&&O.success?(D(O),ee(""),await oe(),await Q(d),await ve()):D({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){D({success:!1,error:(O==null?void 0:O.message)||"Failed to apply Mesh Host join"})}finally{z(!1)}}}async function Me(O){if(!n||!d)return;const be=ro(h[O.id]||bn(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 oe()}catch(Be){w((Be==null?void 0:Be.message)||"Node policy update failed")}finally{y(null)}}if(!n)return s.jsx(vr,{icon:s.jsx(rs,{}),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(vr,{icon:s.jsx(rs,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>je(!0),children:"+ Create Mesh"}),children:[x&&s.jsx(Ds,{variant:"error",className:"mb-4",children:x}),ce&&s.jsx(wt,{title:"New Mesh",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(At,{label:"Name",children:s.jsx(lr,{value:Ne,onChange:O=>q(O.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(At,{label:"Repo Identity (optional)",children:s.jsx(lr,{value:ge,onChange:O=>he(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:le,disabled:!Ne.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(Tn,{icon:s.jsx(rs,{}),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=Wa(ue),Ke=(B==null?void 0:B.meshHost)||ue.meshHost||{},Ve=((Ye=B==null?void 0:B.manualPairing)==null?void 0:Ye.status)||((tt=Ke.pairing)==null?void 0:tt.status)||"not_configured",Xe=((ct=B==null?void 0:B.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(vr,{icon:s.jsx(rs,{}),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:[x&&s.jsx(Ds,{variant:"error",className:"mb-4",children:x}),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:Ke.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:C?"loading":Ve})]}),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:Ke.hostAddress||"not configured"})]}),s.jsxs("div",{children:["Token id: ",s.jsx("code",{className:"text-text-primary",children:((mt=Ke.pairing)==null?void 0:mt.tokenId)||"not configured"})]}),s.jsxs("div",{children:["Can own coordinator: ",s.jsx("code",{className:"text-text-primary",children:String(Ke.canOwnCoordinator??Ke.role!=="member")})]}),s.jsxs("div",{children:["Can own queue: ",s.jsx("code",{className:"text-text-primary",children:String(Ke.canOwnQueue??Ke.role!=="member")})]})]}),s.jsx("p",{className:"mt-3 text-xs leading-relaxed text-text-secondary",children:Xe}),(B==null?void 0:B.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:B.error})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-panel p-4",children:[s.jsx(At,{label:"Mesh Host address",hint:"Example: http://127.0.0.1:3847 or a reachable HTTPS/WSS host endpoint.",children:s.jsx(lr,{value:F,onChange:O=>me(O.target.value),placeholder:"http://127.0.0.1:3847",disabled:E||$})}),s.jsx(At,{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(lr,{value:ie,onChange:O=>ee(O.target.value),placeholder:"paste Mesh Host pairing token",type:"password",disabled:E||$})}),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:E||$||!F.trim()||!ie.trim(),children:E?"Saving...":"Save manual pairing"}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:H,disabled:$||E||!ie.trim(),children:$?"Applying...":"Apply join"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>Q(d),disabled:C||E||$,children:C?"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(At,{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:b,children:[s.jsx("option",{value:"no",children:"No"}),s.jsx("option",{value:"yes",children:"Yes"})]})}),s.jsx(At,{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:b,children:[s.jsx("option",{value:"yes",children:"Yes"}),s.jsx("option",{value:"no",children:"No"})]})}),s.jsx(At,{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:b,children:[s.jsx("option",{value:"required",children:"Require approval before push"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(At,{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:b,children:[s.jsx("option",{value:"required",children:"Require approval"}),s.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),s.jsx(At,{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:b,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(At,{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:b,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(At,{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:b,children:an.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=an.find(O=>O.value===Ae.sessionCleanupOnNodeRemove))==null?void 0:pt.description)||an[0].description})]}),b&&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:K,children:K?"Loading...":"Refresh Graph"})]}),N&&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:N}),S?s.jsx(xu,{status:S,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:K?"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(At,{label:"Workspace Path",children:s.jsx(lr,{value:Se,onChange:O=>J(O.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),s.jsx(At,{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(Zi,{value:fe,availableProviders:o,onChange:ae})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:ne,disabled:!Se.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(Tn,{icon:s.jsx(ks,{}),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=bn(O),Te=Nw(O),Be=Cw(O,j),qe=Mw(O,r),V=A===O.id;return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${V?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>T(V?null:O.id),onKeyDown:U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),T(V?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(At,{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(Zi,{value:h[O.id]??be,availableProviders:o,onChange:U=>M(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})})]}),V&&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:Iw(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(Aw,{meshId:ue.id,availableCliAgents:a})]})}function ci(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function _w(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=ci();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 Kt(e,t){return await fetch(_w(e),{credentials:"same-origin",...t})}function wu(){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 Lw{constructor(){Ze(this,"adapters",new Map);Ze(this,"states",new Map);Ze(this,"runtimeListeners",new Map);Ze(this,"screenshotCallbacks",new Map);Ze(this,"statusCallbacks",new Set)}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)}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"}sendData(t,r){return!1}sendPtyInput(t,r,n){return!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 Kt(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const l=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof l.seq=="number"?l.seq:0,text:typeof l.text=="string"?l.text:"",truncated:!!l.truncated,cols:typeof l.cols=="number"?l.cols:void 0,rows:typeof l.rows=="number"?l.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(t,r){var n;(n=this.runtimeListeners.get(t))==null||n.forEach(a=>a(r))}}const Gt=new Lw;function Rw(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=ci();return r?`${t}?token=${encodeURIComponent(r)}`:t}const on=Rw(),Vl=3e3,Pw=3e4;let Bt=null,Dw=0;const En=new Map;let us=null,kr=null;function Gl(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function mr(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function Ew(e){return e==="connected"?"connected":e}async function gn(e,t,r){const n=od(e,r||{}),a=Bt;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++Dw}_${Date.now()}`;return new Promise((l,c)=>{const d=setTimeout(()=>{En.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);En.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 fo(e,t){const r=Bt;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 $w(e,t,r){const n=Bt;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=od(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}}class Bw{constructor(t){Ze(this,"daemonId");Ze(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(Bt==null?void 0:Bt.readyState)===WebSocket.OPEN}get connectionState(){return(Bt==null?void 0:Bt.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,r){return gn(this.daemonId,t,r)}async sendInput(t,r){return gn(this.daemonId,"cdp_remote_action",{action:t,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,us&&(clearInterval(us),us=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await gn(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(o=>o.blob());Gt.emitScreenshot(this.daemonId,a)}}catch{}};r(),us=setInterval(r,2e3)}stopScreenshots(t){us&&(clearInterval(us),us=null)}}let Pt=null;function Ow(e){return(!Pt||Pt.daemonId!==e)&&(Pt=new Bw(e)),Pt}function Fw({children:e}){const t=i.useRef(Nr()),r=Nr();t.current=r;const{setUserName:n}=ls(),a=i.useRef(n);a.current=n;const o=i.useRef(null),l=i.useRef(null),[,c]=i.useState("disconnected"),d=i.useCallback((p,g)=>{c(p),kr==null||kr(p,g)},[]),m=i.useRef(null),u=i.useRef(),f=i.useRef(Vl),x=i.useRef(!0),w=i.useRef(!1),b=i.useRef("initial_connect");return i.useEffect(()=>{x.current=!0,w.current=!1;function p(){var h,M;if(!x.current||((h=m.current)==null?void 0:h.readyState)===WebSocket.OPEN||((M=m.current)==null?void 0:M.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${on}...`),mr("connect_attempt",{url:on,reason:b.current,delayMs:f.current});let y;try{y=new WebSocket(on)}catch(j){console.error("[Standalone WS] Failed to create WebSocket:",j),g();return}m.current=y,y.onopen=()=>{if(!x.current){y.close();return}d("connected"),f.current=Vl,mr("open",{url:on,reason:b.current}),Xt.resubscribeAll({sendData:fo}),console.log("[Standalone WS] Connected")},Bt=y,y.onmessage=j=>{var v,A;try{const T=JSON.parse(j.data);if((T.type==="command_result"||T.type==="error")&&T.requestId){const S=En.get(T.requestId);S&&(En.delete(T.requestId),T.type==="error"?S.reject(new Error(((v=T.data)==null?void 0:v.message)||"Command failed")):S.resolve(T.data));return}if(T.type==="session_output"){const S=T.sessionId||T.cliId||T.cliType;S&&Gt.emitSessionOutput(S,typeof T.data=="string"?T.data:"",typeof T.seq=="number"?T.seq:void 0);return}if(T.type==="runtime_snapshot"){Gt.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 S=T.update;S&&Xt.publish(S);return}if(T.type==="status"||T.type==="initial_state"){const S=T.data;if(!S)return;const{injectEntries:k,markLoaded:K,getIdes:L}=t.current,N=S.instanceId||"standalone",P=L().find(C=>C.id===N),B=Ow(N);Gt.register(N,B),Gt.setState(N,"connected"),d("connected",N),Gt.emitStatus(N,S);const D=Mn(S,{daemonId:N,existingDaemon:P,existingEntries:L()});Gl("ws_status",{type:T.type,daemonId:N,sessions:(S.sessions||[]).map(C=>({id:C.id,parentId:C.parentId,providerType:C.providerType,kind:C.kind,transport:C.transport,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,title:C.title})),recentLaunches:(S.recentLaunches||[]).map(C=>({id:C.id,providerType:C.providerType,kind:C.kind,workspace:C.workspace,lastLaunchedAt:C.lastLaunchedAt}))}),Gl("entries",{daemonId:N,entries:D.filter(C=>C.type!=="adhdev-daemon").map(C=>({id:C.id,type:C.type,unread:C.unread,inboxBucket:C.inboxBucket,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,sessionId:C.sessionId}))}),D.length>0&&k(D,{authoritativeDaemonIds:[N]}),K(),l.current!==N&&((A=o.current)==null||A.call(o),l.current=N,o.current=Xt.subscribe({sendData:fo},N,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${N}`,params:{includeSessions:!0}},C=>{if(C.topic!=="daemon.metadata")return;const I=t.current.getIdes(),E=I.find($=>$.id===N),R=Mn(C.status,{daemonId:N,existingDaemon:E,existingEntries:I,timestamp:C.timestamp});R.length>0&&t.current.injectEntries(R,{authoritativeDaemonIds:[N]}),C.userName&&a.current&&a.current(C.userName)}))}}catch(T){console.error("[Standalone WS] Parse error:",T)}},y.onclose=j=>{x.current&&(Pt==null||Pt.stopScreenshots(),Pt&&Gt.setState(Pt.daemonId,"disconnected"),d("disconnected"),m.current=null,b.current=`close:${j.code}${j.wasClean?":clean":":unclean"}`,mr("close",{code:j.code,reason:j.reason||"",wasClean:j.wasClean}),g())},y.onerror=j=>{w.current||!x.current||(b.current="error",mr("error",{message:j instanceof Event?"event":String(j),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",j))}}function g(){if(!x.current)return;clearTimeout(u.current);const y=f.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),mr("schedule_reconnect",{reason:b.current,delayMs:y}),u.current=setTimeout(()=>{f.current=Math.min(f.current*1.5,Pw),p()},y)}return p(),()=>{var y;x.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,Bt=null),Pt&&(Pt.stopScreenshots(),Gt.unregister(Pt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function Ww({children:e}){const[t,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(kr=(l,c)=>{r(l),c&&a(c)},()=>{kr=null}),[]);const o=i.useMemo(()=>{const l=t==="connected",c=Ew(t),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:t,isConnected:l,connectionStates:d}},[t,n]);return s.jsx(Sm,{connectionOverrides:o,children:s.jsx(Fw,{children:e})})}const ju="adhdev_standalone_font_preferences",js={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Qn=[{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"}],Kw=new Set(Qn.map(e=>e.id)),Hw=new Set(Ar.map(e=>e.id));function Ut(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:yn("chat",t.chat),code:yn("code",t.code),terminal:yn("terminal",t.terminal)}}function yn(e,t){const r=js[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"?Kw:Hw).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function vn(e,t){var a;const r=yn(e,t);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Qn:Ar;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Uw(e){const t=Ut(e),r=vn("chat",t.chat),n=vn("code",t.code),a=vn("terminal",t.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function ps(e,t=document.documentElement){const r=Ut(e),n=Uw(r);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))t.style.setProperty(a,o);return r}function ho(e){const t=Ut(e);try{localStorage.setItem(ju,JSON.stringify(t))}catch{}return t}function zw(){try{const e=localStorage.getItem(ju);if(e)return Ut(JSON.parse(e))}catch{}return js}function Vw(){return ps(zw())}function pr(e,t){var n;const r=e==="chat"?Qn:Ar;return((n=r.find(a=>a.id===t))==null?void 0:n.label)||r[0].label}const Gw=[{id:"dashboard",path:"/dashboard",icon:s.jsx(rc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:s.jsx(as,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:s.jsx(Ws,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:s.jsx($n,{}),label:"Settings"}];function qw({children:e}){const t=qs(),r=bo(),n=i.useMemo(()=>Gw.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(ac,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:s.jsx(oc,{}),active:r.pathname==="/about",onSelect:()=>t("/about"),title:"About"}],[r.pathname,t]);return s.jsx(Bx,{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 Yw=[{icon:s.jsx(as,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Jt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(ic,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(_t,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(Ws,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(ac,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],Xw=[{icon:s.jsx(Wm,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(rc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Bn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Pm,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(nc,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Em,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],Jw=[{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 Qw(){return s.jsxs(vr,{icon:s.jsx(oc,{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:Yw.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:id.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:cd.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:ld.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:Xw.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:Jw.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(Tn,{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(Jm,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function Ka(e,t,r){return{...e,[t]:r}}function Ha({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:vn(e,n)})]})]})]})}function Zw({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(Ha,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Qn,onChange:u=>o(Ka(e,"chat",u))}),s.jsx(Ha,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Ar,onChange:u=>o(Ka(e,"code",u))}),s.jsx(Ha,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Ar,onChange:u=>o(Ka(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: ",pr("chat",e.chat.preset)," · Code: ",pr("code",e.code.preset)," · Terminal: ",pr("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",pr("chat",js.chat.preset)," / ",pr("code",js.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 ej(){const{ides:e}=ls(),t=e.find(q=>q.type==="adhdev-daemon"),r=(t==null?void 0:t.detectedIdes)||[],{sendCommand:n}=kt(),{userName:a}=ls(),[o,l]=i.useState(a||""),[c,d]=i.useState(null),[m,u]=i.useState(null),[f,x]=i.useState(js),[w,b]=i.useState(!1),[p,g]=i.useState(""),[y,h]=i.useState(""),[M,j]=i.useState("127.0.0.1"),[v,A]=i.useState(""),[T,S]=i.useState(""),[k,K]=i.useState(""),[L,N]=i.useState(""),[P,B]=i.useState(""),[D,C]=i.useState(!1),I=async()=>{const ge=await(await Kt("/auth/session")).json();d(ge)},E=async()=>{const ge=await(await Kt("/api/v1/standalone/preferences")).json();u(ge),j(ge.standaloneBindHost);const he=Ut(ge.standaloneFontPreferences);x(he),ps(he),ho(he)};i.useEffect(()=>{a!==void 0&&l(a)},[a]),i.useEffect(()=>{Promise.all([I(),E()]).catch(q=>{N(q instanceof Error?q.message:String(q))})},[]),i.useEffect(()=>{ps(f)},[f]);const R=q=>{const ge=q.target.value.trim();t!=null&&t.id&&ge!==a&&n(t.id,"set_user_name",{userName:ge}).catch(console.error)},[$,z]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),F=q=>{z(q);try{localStorage.setItem("adhdev_sound",q?"1":"0")}catch{}},me=async()=>{g(""),h(""),b(!0);try{const q=Ut(f),ge=await Kt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:q})}),he=await ge.json();if(!ge.ok)throw new Error((he==null?void 0:he.error)||"Failed to save standalone font preferences");const we=Ut(he.standaloneFontPreferences);u(he),x(we),ps(we),ho(we),h("Standalone chat fonts saved for this self-hosted dashboard.")}catch(q){g(q instanceof Error?q.message:String(q))}finally{b(!1)}},ie=()=>{const q=Ut(m==null?void 0:m.standaloneFontPreferences);g(""),h(""),x(q),ps(q)},ee=()=>{g(""),h(""),x(js),ps(js)},ce=async()=>{N(""),B(""),C(!0);try{const q=await Kt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:M})}),ge=await q.json();if(!q.ok)throw new Error((ge==null?void 0:ge.error)||"Failed to save standalone network preference");u(ge),j(ge.standaloneBindHost),B(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){N(q instanceof Error?q.message:String(q))}finally{C(!1)}},je=async()=>{if(N(""),B(""),T.trim().length<4){N("Password must be at least 4 characters.");return}if(T!==k){N("New password and confirmation do not match.");return}C(!0);try{const q=await Kt("/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 E(),A(""),S(""),K(""),B(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),wu()}catch(q){N(q instanceof Error?q.message:String(q))}finally{C(!1)}},Ne=async()=>{N(""),B(""),C(!0);try{const q=await Kt("/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 E(),A(""),S(""),K(""),B("Standalone password disabled.")}catch(q){N(q instanceof Error?q.message:String(q))}finally{C(!1)}};return s.jsxs(vr,{icon:s.jsx($n,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[s.jsx(Ds,{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(Ds,{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:M==="127.0.0.1",onChange:()=>j("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:M==="0.0.0.0",onChange:()=>j("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:()=>{ce()},disabled:D,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:D?"Saving…":"Save default network mode"}),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(Ds,{variant:"error",children:L}),P&&s.jsx(Ds,{variant:"success",children:P}),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=>A(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=>S(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:k,onChange:q=>K(q.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",onClick:()=>{je()},disabled:D,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:D?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&s.jsx("button",{type:"button",onClick:()=>{Ne()},disabled:D,className:"rounded-lg border border-red-500/30 bg-red-500/10 text-red-300 px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Disable password"})]})]})}),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(Gx,{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(Jx,{})]}),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(ab,{})]}),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(Zw,{value:f,savedValue:Ut(m==null?void 0:m.standaloneFontPreferences),saving:w,error:p,notice:y,onChange:x,onSave:()=>{me()},onResetToSaved:ie,onResetToDefaults:ee})]}),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(lb,{})]})]})}),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(Ux,{}),s.jsx(ms,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xm,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:F})]})}),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(Rm,{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:R,onKeyDown:q=>{q.key==="Enter"&&q.currentTarget.blur()}})]})})})]})}Ex();rb();Vw();const tj=tc({baseUrl:"",getToken:ci});function sj({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),f=async()=>{a(!0),d("");try{const b=await(await Kt("/auth/session")).json();r(b)}catch(w){d(w instanceof Error?w.message:String(w))}finally{a(!1)}};i.useEffect(()=>{f()},[]),i.useEffect(()=>{if(!t||t.required&&!t.authenticated)return;let w=!1;return(async()=>{try{const b=await Kt("/api/v1/standalone/preferences");if(!b.ok)return;const p=await b.json();if(w)return;const g=Ut(p.standaloneFontPreferences);ps(g),ho(g)}catch{}})(),()=>{w=!0}},[t==null?void 0:t.authenticated,t==null?void 0:t.required]);const x=async w=>{w.preventDefault(),u(!0),d("");try{const b=await Kt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await b.json();if(!b.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),l(""),wu()}catch(b){d(b instanceof Error?b.message:String(b))}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:x,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}=ls();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(Va,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Va,{to:"/dashboard",replace:!0})}function rj(){const e=i.useMemo(()=>({sendCommand:gn,sendData:fo,sendPtyInput:$w}),[]);return s.jsx(lm,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Im,{client:tj,children:s.jsx(sj,{children:s.jsx(Ww,{children:s.jsx(Am,{value:e,children:s.jsx(qw,{children:s.jsxs(cm,{children:[s.jsx(es,{path:"/dashboard",element:s.jsx(bv,{})}),s.jsx(es,{path:"/machine",element:s.jsx(ql,{})}),s.jsx(es,{path:"/machines/:id",element:s.jsx(kw,{})}),s.jsx(es,{path:"/machines",element:s.jsx(ql,{})}),s.jsx(es,{path:"/about",element:s.jsx(Qw,{})}),s.jsx(es,{path:"/settings",element:s.jsx(ej,{})}),s.jsx(es,{path:"/mesh",element:s.jsx(Tw,{})}),s.jsx(es,{path:"*",element:s.jsx(Va,{to:"/dashboard",replace:!0})})]})})})})})})})}Vh({connectionManager:Gt});dm(document.getElementById("root")).render(s.jsx(rj,{}));
|